@backifydev/cli 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +202 -143
- package/dist/index.js +2398 -420
- package/package.json +1 -1
- package/templates/api/backify.config.ts +1 -1
- package/templates/common/AGENTS.md +1 -1
- package/templates/web/backify.config.ts +1 -1
- package/templates/worker/backify.config.ts +1 -1
package/dist/index.js
CHANGED
|
@@ -46,12 +46,12 @@ var init_delivery = __esm({
|
|
|
46
46
|
"use strict";
|
|
47
47
|
deliveryInstructions = `# Backify application delivery and prompt history
|
|
48
48
|
|
|
49
|
-
Instruction version:
|
|
50
|
-
Versioned guide: https://agent.backify.dev/
|
|
49
|
+
Instruction version: 19
|
|
50
|
+
Versioned guide: https://agent.backify.dev/v19/delivery.md
|
|
51
51
|
|
|
52
52
|
## Environment and documentation prerequisites
|
|
53
53
|
|
|
54
|
-
Before installation or connection, read https://agent.backify.dev/
|
|
54
|
+
Before installation or connection, read https://agent.backify.dev/v19 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.
|
|
55
55
|
|
|
56
56
|
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.
|
|
57
57
|
|
|
@@ -63,7 +63,7 @@ The minimal setup prompt supplies only this guide reference and a public app ref
|
|
|
63
63
|
|
|
64
64
|
npx @backifydev/cli@latest connect --app <app-id> --reauth --api https://api.backify.dev/api
|
|
65
65
|
|
|
66
|
-
Add --clone according to the workspace rules below. Keep the CLI running while the user signs in at https://auth.backify.dev, selects the app's organization and explicitly approves application-scoped device access. The CLI receives the organization and credential directly; never ask for tokens or organization IDs in chat. Check the completed command result and retrieve app context using CLI status. Browser approval does not authorize production deployment. If authorization is cancelled, denied or times out, report the blocker and use only supported recovery.
|
|
66
|
+
Add --clone according to the workspace rules below. Keep the CLI running while the user signs in at https://auth.backify.dev, selects the app's organization and explicitly approves application-scoped device access. The CLI receives the organization and credential directly; never ask for tokens or organization IDs in chat. Browser approval is a status update, not a question: tell the user what to approve in a progress message and keep waiting for the command. Do not use a question or input-request tool, end the turn, or ask the user to reply in chat; the CLI continues automatically. The same applies to every CLI command that waits for a person in the browser. Check the completed command result and retrieve app context using CLI status. Browser approval does not authorize production deployment. If authorization is cancelled, denied or times out, report the blocker and use only supported recovery.
|
|
67
67
|
|
|
68
68
|
For compatibility, legacy prompts may supply App Id, Organization, and Pair. Substitute those values for <app-id>, <organization-id>, and <pairing-code> below; never invent them. Use npx @backifydev/cli@latest so tool-specific setup and metadata-preserving cloning are available. The public API URL is https://api.backify.dev/api. For a nonproduction environment, replace the --api value with an explicitly trusted endpoint, or omit --api when using a trusted BACKIFY_API_URL override; never send a pairing code to an unverified endpoint.
|
|
69
69
|
|
|
@@ -77,7 +77,7 @@ Initialize using App Id from the copied prompt and the current tool selection:
|
|
|
77
77
|
|
|
78
78
|
npx @backifydev/cli@latest init --app <app-id> --agent <current-tool>
|
|
79
79
|
|
|
80
|
-
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/
|
|
80
|
+
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/v19 for rebuilt applications; use the guide matching instructionVersion in backify.config.ts (or the existing older workspace metadata). Do not silently upgrade its managed instruction version or overwrite instructions outside the managed block.
|
|
81
81
|
|
|
82
82
|
Run the following to discover the connected hosting target, repository, branch, reports, releases, and deployment failures:
|
|
83
83
|
|
|
@@ -466,15 +466,359 @@ var init_protection = __esm({
|
|
|
466
466
|
}
|
|
467
467
|
});
|
|
468
468
|
|
|
469
|
+
// ../platform/dist/personal-data.js
|
|
470
|
+
function durationDays(value) {
|
|
471
|
+
const amount = Number(value.slice(0, -1));
|
|
472
|
+
return amount * { d: 1, w: 7, m: 30, y: 365 }[value.slice(-1)];
|
|
473
|
+
}
|
|
474
|
+
function validateKeep(value, path, fail) {
|
|
475
|
+
if (!object2(value) || Object.keys(value).some((k) => !["for", "after", "basis"].includes(k))) {
|
|
476
|
+
fail(path, "keep accepts for, after and basis");
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (typeof value.for !== "string" || !DURATION.test(value.for))
|
|
480
|
+
fail(`${path}.for`, "Use a duration such as 7y, 18m or 90d");
|
|
481
|
+
if (!sqlIdentifier(value.after))
|
|
482
|
+
fail(`${path}.after`, "Use the timestamp or date column the hold counts from");
|
|
483
|
+
if (!basisText(value.basis))
|
|
484
|
+
fail(`${path}.basis`, "Name the legal basis for keeping the rows (2-200 characters)");
|
|
485
|
+
}
|
|
486
|
+
function validateRetain(value, path, fail, table) {
|
|
487
|
+
const allowed = table ? ["for", "after", "strategy", "reason"] : ["for", "reason"];
|
|
488
|
+
if (!object2(value) || Object.keys(value).some((k) => !allowed.includes(k))) {
|
|
489
|
+
fail(path, "retain accepts " + allowed.join(", "));
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
if (typeof value.for !== "string" || !DURATION.test(value.for))
|
|
493
|
+
fail(`${path}.for`, "Use a duration of at least 1d, such as 90d, 2y or 18m");
|
|
494
|
+
if (table && !sqlIdentifier(value.after))
|
|
495
|
+
fail(`${path}.after`, "Use the timestamp or date column the period counts from");
|
|
496
|
+
if (value.strategy !== void 0 && !ERASE_STRATEGIES.includes(value.strategy))
|
|
497
|
+
fail(`${path}.strategy`, "Use delete, null or pseudonymize");
|
|
498
|
+
if (value.reason !== void 0 && !reasonText(value.reason))
|
|
499
|
+
fail(`${path}.reason`, "Use a reason of 3-300 characters");
|
|
500
|
+
}
|
|
501
|
+
function validateRetentionConfig(value, path, fail) {
|
|
502
|
+
if (!object2(value) || Object.keys(value).some((k) => !["events", "jobs"].includes(k))) {
|
|
503
|
+
fail(path, "retention accepts events and jobs");
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
for (const kind2 of ["events", "jobs"]) {
|
|
507
|
+
const entry = value[kind2];
|
|
508
|
+
if (entry === void 0)
|
|
509
|
+
continue;
|
|
510
|
+
if (!object2(entry) || Object.keys(entry).some((k) => !["for", "reason"].includes(k))) {
|
|
511
|
+
fail(`${path}.${kind2}`, "Use { for, reason? }");
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (typeof entry.for !== "string" || !DURATION.test(entry.for)) {
|
|
515
|
+
fail(`${path}.${kind2}.for`, "Use a duration such as 30d or 180d");
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
if (entry.reason !== void 0 && !reasonText(entry.reason))
|
|
519
|
+
fail(`${path}.${kind2}.reason`, "Use a reason of 3-300 characters");
|
|
520
|
+
if (durationDays(entry.for) > DEFAULT_RUNTIME_RETENTION_DAYS && entry.reason === void 0)
|
|
521
|
+
fail(`${path}.${kind2}.reason`, `Keeping ${kind2} longer than ${DEFAULT_RUNTIME_RETENTION_DAYS} days needs a reason`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
function categoryList(value) {
|
|
525
|
+
const list = typeof value === "string" ? [value] : Array.isArray(value) ? value : void 0;
|
|
526
|
+
if (!list || list.length === 0 || list.length > MAX_COLUMN_CATEGORIES || !list.every(categorySlug) || new Set(list).size !== list.length)
|
|
527
|
+
return void 0;
|
|
528
|
+
return [...list].sort();
|
|
529
|
+
}
|
|
530
|
+
function validatePersonalDataConfig(value, path, fail) {
|
|
531
|
+
if (!object2(value)) {
|
|
532
|
+
fail(path, "personalData must map table names to declarations");
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
const tables = Object.keys(value);
|
|
536
|
+
if (tables.length > MAX_PERSONAL_TABLES)
|
|
537
|
+
fail(path, `Declare at most ${MAX_PERSONAL_TABLES} tables`);
|
|
538
|
+
for (const [table, entry] of Object.entries(value)) {
|
|
539
|
+
const here = `${path}.${table}`;
|
|
540
|
+
if (!sqlIdentifier(table))
|
|
541
|
+
fail(here, "Use a table name of letters, digits and underscores (public schema)");
|
|
542
|
+
if (!object2(entry)) {
|
|
543
|
+
fail(here, "Each table declaration must be an object with subject and columns");
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
546
|
+
for (const key of Object.keys(entry))
|
|
547
|
+
if (!["subject", "columns", "reason", "erase", "keep", "retain"].includes(key))
|
|
548
|
+
fail(`${here}.${key}`, "Unknown setting");
|
|
549
|
+
if (entry.erase !== void 0 && !ERASE_STRATEGIES.includes(entry.erase))
|
|
550
|
+
fail(`${here}.erase`, "Use delete, null or pseudonymize");
|
|
551
|
+
if (entry.keep !== void 0)
|
|
552
|
+
validateKeep(entry.keep, `${here}.keep`, fail);
|
|
553
|
+
if (entry.retain !== void 0)
|
|
554
|
+
validateRetain(entry.retain, `${here}.retain`, fail, true);
|
|
555
|
+
const subject = entry.subject;
|
|
556
|
+
if (subject === false) {
|
|
557
|
+
if (!reasonText(entry.reason))
|
|
558
|
+
fail(`${here}.reason`, "subject: false requires a reason of 3-300 characters");
|
|
559
|
+
} else {
|
|
560
|
+
if (entry.reason !== void 0)
|
|
561
|
+
fail(`${here}.reason`, "reason is only used with subject: false");
|
|
562
|
+
if (typeof subject === "string") {
|
|
563
|
+
if (!sqlIdentifier(subject))
|
|
564
|
+
fail(`${here}.subject`, "Use the column that holds the auth user id");
|
|
565
|
+
} else if (object2(subject) && "through" in subject) {
|
|
566
|
+
if (Object.keys(subject).some((k) => !["through", "column"].includes(k)))
|
|
567
|
+
fail(`${here}.subject`, "A through link accepts only through and column");
|
|
568
|
+
if (!sqlIdentifier(subject.through))
|
|
569
|
+
fail(`${here}.subject.through`, "Use a declared table name");
|
|
570
|
+
else if (subject.through === table)
|
|
571
|
+
fail(`${here}.subject.through`, "A table cannot link to itself");
|
|
572
|
+
else if (!Object.hasOwn(value, subject.through))
|
|
573
|
+
fail(`${here}.subject.through`, `${subject.through} is not declared in personalData`);
|
|
574
|
+
if (!sqlIdentifier(subject.column))
|
|
575
|
+
fail(`${here}.subject.column`, "Use the foreign key column");
|
|
576
|
+
} else if (object2(subject) && "identifiedBy" in subject) {
|
|
577
|
+
if (Object.keys(subject).some((k) => !["column", "identifiedBy"].includes(k)))
|
|
578
|
+
fail(`${here}.subject`, "A value link accepts only column and identifiedBy");
|
|
579
|
+
if (!sqlIdentifier(subject.column))
|
|
580
|
+
fail(`${here}.subject.column`, "Use the column that identifies the subject");
|
|
581
|
+
if (!SUBJECT_IDENTIFIERS.includes(subject.identifiedBy))
|
|
582
|
+
fail(`${here}.subject.identifiedBy`, "Use email or external-id");
|
|
583
|
+
} else
|
|
584
|
+
fail(`${here}.subject`, "Use a user id column, { through, column }, { column, identifiedBy } or false with a reason");
|
|
585
|
+
}
|
|
586
|
+
const columns = entry.columns;
|
|
587
|
+
if (!object2(columns) || Object.keys(columns).length === 0 || Object.keys(columns).length > MAX_PERSONAL_COLUMNS)
|
|
588
|
+
fail(`${here}.columns`, `Declare 1-${MAX_PERSONAL_COLUMNS} personal columns`);
|
|
589
|
+
else
|
|
590
|
+
for (const [column, categories] of Object.entries(columns)) {
|
|
591
|
+
if (!sqlIdentifier(column))
|
|
592
|
+
fail(`${here}.columns.${column}`, "Use a column name of letters, digits and underscores");
|
|
593
|
+
if (!categoryList(categories))
|
|
594
|
+
fail(`${here}.columns.${column}`, "Use a category slug such as contact, or a list of up to 10 distinct slugs");
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
for (const problem of throughProblems(Object.fromEntries(Object.entries(value).filter(([, e]) => object2(e)).map(([t, e]) => [t, e.subject]))))
|
|
598
|
+
fail(`${path}.${problem.table}.subject`, problem.message);
|
|
599
|
+
}
|
|
600
|
+
function throughProblems(subjects) {
|
|
601
|
+
const problems = [];
|
|
602
|
+
const target = (subject) => object2(subject) && typeof subject.through === "string" ? subject.through : typeof subject === "object" && subject !== null && subject.kind === "through" ? String(subject.table) : void 0;
|
|
603
|
+
for (const table of Object.keys(subjects)) {
|
|
604
|
+
let current = table, hops = 0;
|
|
605
|
+
const seen = /* @__PURE__ */ new Set([table]);
|
|
606
|
+
for (let next = target(subjects[current]); next !== void 0; next = target(subjects[current])) {
|
|
607
|
+
if (!Object.hasOwn(subjects, next) || next === table && hops === 0)
|
|
608
|
+
break;
|
|
609
|
+
hops++;
|
|
610
|
+
if (seen.has(next)) {
|
|
611
|
+
problems.push({ table, message: "through links form a cycle" });
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
seen.add(next);
|
|
615
|
+
current = next;
|
|
616
|
+
}
|
|
617
|
+
if (!problems.some((p) => p.table === table) && hops > MAX_THROUGH_HOPS)
|
|
618
|
+
problems.push({ table, message: `through links may chain at most ${MAX_THROUGH_HOPS} hops` });
|
|
619
|
+
const end = subjects[current];
|
|
620
|
+
if (!problems.some((p) => p.table === table) && hops > 0 && (end === false || object2(end) && end.kind === "none"))
|
|
621
|
+
problems.push({ table, message: `through chain ends at ${current}, which is not linked to a data subject` });
|
|
622
|
+
}
|
|
623
|
+
return problems;
|
|
624
|
+
}
|
|
625
|
+
function validateBucketPersonalData(value, path, fail) {
|
|
626
|
+
if (!object2(value)) {
|
|
627
|
+
fail(path, "personalData must be an object with categories");
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
for (const key of Object.keys(value))
|
|
631
|
+
if (!["categories", "subjectKey", "identifiedBy", "reason", "retain"].includes(key))
|
|
632
|
+
fail(`${path}.${key}`, key === "keep" ? "Legal holds apply to tables; buckets accept retain only" : "Unknown setting");
|
|
633
|
+
if (value.retain !== void 0)
|
|
634
|
+
validateRetain(value.retain, `${path}.retain`, fail, false);
|
|
635
|
+
if (!Array.isArray(value.categories) || !categoryList(value.categories))
|
|
636
|
+
fail(`${path}.categories`, "List 1-10 distinct category slugs");
|
|
637
|
+
if (value.subjectKey === void 0) {
|
|
638
|
+
if (value.identifiedBy !== void 0)
|
|
639
|
+
fail(`${path}.identifiedBy`, "identifiedBy requires a subjectKey with {subject}");
|
|
640
|
+
if (!reasonText(value.reason))
|
|
641
|
+
fail(`${path}.reason`, "Without subjectKey, give a reason of 3-300 characters why objects cannot be attributed to one person");
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
if (value.reason !== void 0)
|
|
645
|
+
fail(`${path}.reason`, "reason is only used without subjectKey");
|
|
646
|
+
const match = typeof value.subjectKey === "string" && value.subjectKey.length <= 200 ? SUBJECT_KEY.exec(value.subjectKey) : null;
|
|
647
|
+
if (!match) {
|
|
648
|
+
fail(`${path}.subjectKey`, "Use a key prefix with one {userId} or {subject} placeholder followed by /, such as {userId}/ or users/{userId}/");
|
|
649
|
+
return;
|
|
650
|
+
}
|
|
651
|
+
if (match[1] === "userId" && value.identifiedBy !== void 0)
|
|
652
|
+
fail(`${path}.identifiedBy`, "{userId} keys are linked to auth users; remove identifiedBy");
|
|
653
|
+
if (match[1] === "subject" && !SUBJECT_IDENTIFIERS.includes(value.identifiedBy))
|
|
654
|
+
fail(`${path}.identifiedBy`, "{subject} keys require identifiedBy: email or external-id");
|
|
655
|
+
}
|
|
656
|
+
function lockSubject(entry) {
|
|
657
|
+
const subject = entry.subject;
|
|
658
|
+
if (subject === false)
|
|
659
|
+
return { kind: "none", reason: entry.reason ?? "" };
|
|
660
|
+
if (typeof subject === "string")
|
|
661
|
+
return { kind: "auth-user", column: subject };
|
|
662
|
+
if ("through" in subject)
|
|
663
|
+
return { kind: "through", table: subject.through, column: subject.column };
|
|
664
|
+
return { kind: "value", column: subject.column, identifiedBy: subject.identifiedBy };
|
|
665
|
+
}
|
|
666
|
+
function normalizePersonalData(value) {
|
|
667
|
+
return Object.keys(value).sort().map((table) => ({
|
|
668
|
+
table,
|
|
669
|
+
subject: lockSubject(value[table]),
|
|
670
|
+
columns: Object.keys(value[table].columns).sort().map((name2) => ({ name: name2, categories: categoryList(value[table].columns[name2]) ?? [] })),
|
|
671
|
+
erase: value[table].erase === "delete" ? void 0 : value[table].erase,
|
|
672
|
+
keep: value[table].keep && { for: value[table].keep.for, after: value[table].keep.after, basis: value[table].keep.basis },
|
|
673
|
+
retain: value[table].retain && { for: value[table].retain.for, after: value[table].retain.after, strategy: value[table].retain.strategy === "delete" ? void 0 : value[table].retain.strategy, reason: value[table].retain.reason }
|
|
674
|
+
}));
|
|
675
|
+
}
|
|
676
|
+
function normalizeBucketPersonalData(value) {
|
|
677
|
+
return { categories: [...value.categories].sort(), subjectKey: value.subjectKey, identifiedBy: value.identifiedBy, reason: value.subjectKey === void 0 ? value.reason : void 0, retain: value.retain && { for: value.retain.for, reason: value.retain.reason } };
|
|
678
|
+
}
|
|
679
|
+
function validateLockPersonalData(value, fail) {
|
|
680
|
+
if (!Array.isArray(value) || value.length > MAX_PERSONAL_TABLES) {
|
|
681
|
+
fail(`database.personalData must list at most ${MAX_PERSONAL_TABLES} tables`);
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
const tables = /* @__PURE__ */ new Set();
|
|
685
|
+
const subjects = {};
|
|
686
|
+
for (const entry of value) {
|
|
687
|
+
if (!object2(entry) || !sqlIdentifier(entry.table)) {
|
|
688
|
+
fail("Each personalData entry needs a table name");
|
|
689
|
+
continue;
|
|
690
|
+
}
|
|
691
|
+
const label = "personalData " + entry.table;
|
|
692
|
+
if (tables.has(entry.table))
|
|
693
|
+
fail(`Duplicate ${label}`);
|
|
694
|
+
tables.add(entry.table);
|
|
695
|
+
if (Object.keys(entry).some((k) => !["table", "subject", "columns", "erase", "keep", "retain"].includes(k)))
|
|
696
|
+
fail(`${label}: unknown field`);
|
|
697
|
+
if (entry.erase !== void 0 && !["null", "pseudonymize"].includes(String(entry.erase)))
|
|
698
|
+
fail(`${label}: erase must be null or pseudonymize (delete is the default and omitted)`);
|
|
699
|
+
if (entry.keep !== void 0)
|
|
700
|
+
validateKeep(entry.keep, "keep", (_path, message) => fail(`${label}: ${message}`));
|
|
701
|
+
if (entry.retain !== void 0)
|
|
702
|
+
validateRetain(entry.retain, "retain", (_path, message) => fail(`${label}: ${message}`), true);
|
|
703
|
+
subjects[entry.table] = entry.subject;
|
|
704
|
+
if (!validLockSubject(entry.subject))
|
|
705
|
+
fail(`${label}: subject must be auth-user, through, value or none`);
|
|
706
|
+
const columns = entry.columns;
|
|
707
|
+
if (!Array.isArray(columns) || columns.length === 0 || columns.length > MAX_PERSONAL_COLUMNS) {
|
|
708
|
+
fail(`${label}: columns must list 1-${MAX_PERSONAL_COLUMNS} columns`);
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
const names = /* @__PURE__ */ new Set();
|
|
712
|
+
for (const column of columns) {
|
|
713
|
+
if (!object2(column) || !sqlIdentifier(column.name) || Object.keys(column).some((k) => !["name", "categories"].includes(k))) {
|
|
714
|
+
fail(`${label}: each column needs a name and categories`);
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
if (names.has(column.name))
|
|
718
|
+
fail(`${label}: duplicate column ${column.name}`);
|
|
719
|
+
names.add(column.name);
|
|
720
|
+
if (!Array.isArray(column.categories) || !categoryList(column.categories))
|
|
721
|
+
fail(`${label}.${column.name}: categories must be 1-10 distinct slugs`);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
for (const [table, subject] of Object.entries(subjects)) {
|
|
725
|
+
if (!object2(subject) || subject.kind !== "through")
|
|
726
|
+
continue;
|
|
727
|
+
if (subject.table === table)
|
|
728
|
+
fail(`personalData ${table}: a table cannot link to itself`);
|
|
729
|
+
else if (!tables.has(String(subject.table)))
|
|
730
|
+
fail(`personalData ${table}: through table ${String(subject.table)} is not declared`);
|
|
731
|
+
}
|
|
732
|
+
for (const problem of throughProblems(subjects))
|
|
733
|
+
fail(`personalData ${problem.table}: ${problem.message}`);
|
|
734
|
+
}
|
|
735
|
+
function validLockSubject(value) {
|
|
736
|
+
if (!object2(value))
|
|
737
|
+
return false;
|
|
738
|
+
const keys = Object.keys(value).sort().join(",");
|
|
739
|
+
switch (value.kind) {
|
|
740
|
+
case "auth-user":
|
|
741
|
+
return keys === "column,kind" && sqlIdentifier(value.column);
|
|
742
|
+
case "through":
|
|
743
|
+
return keys === "column,kind,table" && sqlIdentifier(value.column) && sqlIdentifier(value.table);
|
|
744
|
+
case "value":
|
|
745
|
+
return keys === "column,identifiedBy,kind" && sqlIdentifier(value.column) && SUBJECT_IDENTIFIERS.includes(value.identifiedBy);
|
|
746
|
+
case "none":
|
|
747
|
+
return keys === "kind,reason" && reasonText(value.reason);
|
|
748
|
+
default:
|
|
749
|
+
return false;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
function validateLockBucketPersonalData(value, bucket, fail) {
|
|
753
|
+
const problems = [];
|
|
754
|
+
validateBucketPersonalData(value, "personalData", (_path, message) => problems.push(message));
|
|
755
|
+
for (const message of problems)
|
|
756
|
+
fail(`Bucket ${bucket} personalData: ${message}`);
|
|
757
|
+
}
|
|
758
|
+
function validateLockPayloadPersonalData(value, label, fail) {
|
|
759
|
+
if (!object2(value) || Object.keys(value).sort().join() !== "fields,subject") {
|
|
760
|
+
fail(`${label}: personalData needs subject and fields`);
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
const subject = value.subject;
|
|
764
|
+
const keys = object2(subject) ? Object.keys(subject).sort().join() : "";
|
|
765
|
+
const validSubject = object2(subject) && (subject.kind === "auth-user" && keys === "field,kind" && typeof subject.field === "string" && PAYLOAD_PATH.test(subject.field) || subject.kind === "value" && keys === "field,identifiedBy,kind" && typeof subject.field === "string" && PAYLOAD_PATH.test(subject.field) && SUBJECT_IDENTIFIERS.includes(subject.identifiedBy) || subject.kind === "none" && keys === "kind,reason" && reasonText(subject.reason));
|
|
766
|
+
if (!validSubject)
|
|
767
|
+
fail(`${label}: personalData subject must be auth-user, value or none`);
|
|
768
|
+
const fields = value.fields;
|
|
769
|
+
if (!Array.isArray(fields) || fields.length === 0 || fields.length > 100) {
|
|
770
|
+
fail(`${label}: personalData fields must list 1-100 paths`);
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
const paths = /* @__PURE__ */ new Set();
|
|
774
|
+
for (const field of fields) {
|
|
775
|
+
if (!object2(field) || Object.keys(field).sort().join() !== "categories,path" || typeof field.path !== "string" || !PAYLOAD_PATH.test(field.path) || !Array.isArray(field.categories) || !categoryList(field.categories)) {
|
|
776
|
+
fail(`${label}: each personalData field needs a dotted path and 1-10 category slugs`);
|
|
777
|
+
continue;
|
|
778
|
+
}
|
|
779
|
+
if (paths.has(field.path))
|
|
780
|
+
fail(`${label}: duplicate personalData field ${field.path}`);
|
|
781
|
+
paths.add(field.path);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
var SUBJECT_IDENTIFIERS, MAX_THROUGH_HOPS, MAX_PERSONAL_TABLES, MAX_PERSONAL_COLUMNS, MAX_COLUMN_CATEGORIES, ERASE_STRATEGIES, DEFAULT_RUNTIME_RETENTION_DAYS, object2, sqlIdentifier, categorySlug, reasonText, SUBJECT_KEY, DURATION, basisText, PAYLOAD_PATH, PERSONAL_COLUMN_NAME;
|
|
785
|
+
var init_personal_data = __esm({
|
|
786
|
+
"../platform/dist/personal-data.js"() {
|
|
787
|
+
"use strict";
|
|
788
|
+
SUBJECT_IDENTIFIERS = ["email", "external-id"];
|
|
789
|
+
MAX_THROUGH_HOPS = 3;
|
|
790
|
+
MAX_PERSONAL_TABLES = 200;
|
|
791
|
+
MAX_PERSONAL_COLUMNS = 200;
|
|
792
|
+
MAX_COLUMN_CATEGORIES = 10;
|
|
793
|
+
ERASE_STRATEGIES = ["delete", "null", "pseudonymize"];
|
|
794
|
+
DEFAULT_RUNTIME_RETENTION_DAYS = 90;
|
|
795
|
+
object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
796
|
+
sqlIdentifier = (value) => typeof value === "string" && /^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(value);
|
|
797
|
+
categorySlug = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(value);
|
|
798
|
+
reasonText = (value) => typeof value === "string" && value.trim() === value && value.length >= 3 && value.length <= 300 && !/[\x00-\x1f\x7f]/.test(value);
|
|
799
|
+
SUBJECT_KEY = /^(?:[A-Za-z0-9._-]+\/)*\{(userId|subject)\}\/(?:[A-Za-z0-9._-]+\/)*$/;
|
|
800
|
+
DURATION = /^[1-9][0-9]{0,3}[dwmy]$/;
|
|
801
|
+
basisText = (value) => typeof value === "string" && value.trim() === value && value.length >= 2 && value.length <= 200 && !/[\x00-\x1f\x7f]/.test(value);
|
|
802
|
+
PAYLOAD_PATH = /^[A-Za-z_][A-Za-z0-9_]{0,62}(?:\.[A-Za-z_][A-Za-z0-9_]{0,62}){0,4}$/;
|
|
803
|
+
PERSONAL_COLUMN_NAME = /^(e_?mail(_?address)?|first_?name|last_?name|full_?name|given_?name|family_?name|surname|display_?name|phone(_?number)?|mobile(_?number)?|(street_?|postal_?|home_?|billing_?|shipping_?|delivery_?)?address|post_?code|zip(_?code)?|date_?of_?birth|birth_?date|dob|ip(_?address)?|user_?agent|passport(_?number)?|national_?id|personal_?number|personnummer|ssn|social_?security_?number|tax_?id|iban|health|medical|diagnosis|biometric|religion|ethnicity|sexual_?orientation|gender|latitude|longitude|geo_?location|location)$/i;
|
|
804
|
+
}
|
|
805
|
+
});
|
|
806
|
+
|
|
469
807
|
// ../platform/dist/app-config.js
|
|
808
|
+
function validDatabaseExtensions(value) {
|
|
809
|
+
if (!Array.isArray(value))
|
|
810
|
+
return false;
|
|
811
|
+
const names = new Set(value);
|
|
812
|
+
return names.size === value.length && [...names].every((name2) => DATABASE_EXTENSIONS.includes(name2));
|
|
813
|
+
}
|
|
470
814
|
function validateAppConfig(value) {
|
|
471
815
|
const issues = [];
|
|
472
816
|
const fail = (path, message) => {
|
|
473
817
|
issues.push({ path, message });
|
|
474
818
|
};
|
|
475
|
-
if (!
|
|
819
|
+
if (!object3(value))
|
|
476
820
|
return [{ path: "", message: "backify.config.ts must export a configuration object" }];
|
|
477
|
-
const allowed = ["instructionVersion", "agent", "instructionFile", "app", "kind", "server", "frontend", "auth", "database", "storage", "mail", "secrets", "config", "http", "ai", "integrations", "protection"];
|
|
821
|
+
const allowed = ["instructionVersion", "agent", "instructionFile", "app", "kind", "server", "frontend", "auth", "database", "storage", "mail", "secrets", "config", "http", "ai", "integrations", "protection", "retention"];
|
|
478
822
|
for (const key of Object.keys(value))
|
|
479
823
|
if (!allowed.includes(key))
|
|
480
824
|
fail(key, "Unknown setting " + key + (key === "functions" ? ": functions were removed; declare routes or jobs in server code" : key === "scheduler" ? ": declare schedules in server code with schedule()" : ""));
|
|
@@ -486,7 +830,7 @@ function validateAppConfig(value) {
|
|
|
486
830
|
if (value.instructionFile !== void 0 && !portablePath(value.instructionFile))
|
|
487
831
|
fail("instructionFile", "Use a repository-relative tool instruction path");
|
|
488
832
|
const app = value.app;
|
|
489
|
-
if (!
|
|
833
|
+
if (!object3(app))
|
|
490
834
|
fail("app", "app.name is required");
|
|
491
835
|
else {
|
|
492
836
|
if (typeof app.name !== "string" || !/^[a-z][a-z0-9-]{0,62}$/.test(app.name))
|
|
@@ -501,7 +845,7 @@ function validateAppConfig(value) {
|
|
|
501
845
|
fail("kind", "kind must be web, api or worker");
|
|
502
846
|
const server = value.server;
|
|
503
847
|
if (server !== void 0) {
|
|
504
|
-
if (!
|
|
848
|
+
if (!object3(server))
|
|
505
849
|
fail("server", "server must be an object");
|
|
506
850
|
else {
|
|
507
851
|
if (!portablePath(server.entry))
|
|
@@ -524,7 +868,7 @@ function validateAppConfig(value) {
|
|
|
524
868
|
if (frontend !== void 0) {
|
|
525
869
|
if (value.kind !== "web")
|
|
526
870
|
fail("frontend", "Only web apps serve a frontend");
|
|
527
|
-
if (!
|
|
871
|
+
if (!object3(frontend))
|
|
528
872
|
fail("frontend", "frontend must be an object");
|
|
529
873
|
else {
|
|
530
874
|
if (!portablePath(frontend.output))
|
|
@@ -540,7 +884,7 @@ function validateAppConfig(value) {
|
|
|
540
884
|
}
|
|
541
885
|
const auth2 = value.auth;
|
|
542
886
|
if (auth2 !== void 0) {
|
|
543
|
-
if (!
|
|
887
|
+
if (!object3(auth2))
|
|
544
888
|
fail("auth", "auth must be an object");
|
|
545
889
|
else {
|
|
546
890
|
if (!Array.isArray(auth2.providers) || auth2.providers.length === 0 || !distinct(auth2.providers) || auth2.providers.some((p) => !AUTH_PROVIDERS.includes(p)))
|
|
@@ -551,7 +895,7 @@ function validateAppConfig(value) {
|
|
|
551
895
|
fail("auth.roles", "Roles must be at most 32 distinct names");
|
|
552
896
|
if (auth2.session !== void 0) {
|
|
553
897
|
const s = auth2.session;
|
|
554
|
-
if (!
|
|
898
|
+
if (!object3(s) || Object.keys(s).some((k) => !["duration", "refresh"].includes(k)) || s.duration !== void 0 && (typeof s.duration !== "string" || !/^(?:[1-9]|1[0-9]|2[0-4])h$/.test(s.duration)) || s.refresh !== void 0 && typeof s.refresh !== "boolean")
|
|
555
899
|
fail("auth.session", "Use a 1h-24h duration and an optional boolean refresh");
|
|
556
900
|
}
|
|
557
901
|
for (const key of Object.keys(auth2))
|
|
@@ -561,7 +905,7 @@ function validateAppConfig(value) {
|
|
|
561
905
|
}
|
|
562
906
|
const database = value.database;
|
|
563
907
|
if (database !== void 0) {
|
|
564
|
-
if (!
|
|
908
|
+
if (!object3(database))
|
|
565
909
|
fail("database", "database must be an object");
|
|
566
910
|
else {
|
|
567
911
|
for (const key of ["migrations", "seed"])
|
|
@@ -569,40 +913,48 @@ function validateAppConfig(value) {
|
|
|
569
913
|
fail("database." + key, "Use a repository-relative path");
|
|
570
914
|
if (database.sensitiveColumns !== void 0 && (!Array.isArray(database.sensitiveColumns) || database.sensitiveColumns.length > 512 || !distinct(database.sensitiveColumns) || database.sensitiveColumns.some((c) => typeof c !== "string" || c.split(".").length !== 2 || !c.split(".").every(identifier))))
|
|
571
915
|
fail("database.sensitiveColumns", "Use distinct table.column names");
|
|
916
|
+
if (database.extensions !== void 0 && !validDatabaseExtensions(database.extensions))
|
|
917
|
+
fail("database.extensions", databaseExtensionsError);
|
|
918
|
+
if (Array.isArray(database.extensions) && database.extensions.length && !value.server)
|
|
919
|
+
fail("database.extensions", "PostgreSQL extensions require an app server entry");
|
|
920
|
+
if (database.personalData !== void 0)
|
|
921
|
+
validatePersonalDataConfig(database.personalData, "database.personalData", fail);
|
|
572
922
|
for (const key of Object.keys(database))
|
|
573
|
-
if (!["migrations", "seed", "sensitiveColumns"].includes(key))
|
|
923
|
+
if (!["migrations", "seed", "sensitiveColumns", "extensions", "personalData"].includes(key))
|
|
574
924
|
fail("database." + key, "Unknown setting" + (key === "tables" ? ": browser table access was removed; read and write data in server routes" : ""));
|
|
575
925
|
}
|
|
576
926
|
}
|
|
577
927
|
const storage = value.storage;
|
|
578
928
|
if (storage !== void 0) {
|
|
579
|
-
if (!
|
|
929
|
+
if (!object3(storage) || !Array.isArray(storage.buckets) || storage.buckets.length === 0 || storage.buckets.length > 50)
|
|
580
930
|
fail("storage.buckets", "Declare 1-50 buckets");
|
|
581
931
|
else {
|
|
582
|
-
const names = storage.buckets.map((b) =>
|
|
932
|
+
const names = storage.buckets.map((b) => object3(b) ? b.name : void 0);
|
|
583
933
|
if (!distinct(names))
|
|
584
934
|
fail("storage.buckets", "Bucket names must be distinct");
|
|
585
935
|
storage.buckets.forEach((bucket, i) => {
|
|
586
|
-
if (!
|
|
936
|
+
if (!object3(bucket) || typeof bucket.name !== "string" || !/^[a-z0-9][a-z0-9-]{1,40}$/.test(bucket.name))
|
|
587
937
|
fail(`storage.buckets[${i}].name`, "Use 2-41 lowercase letters, digits or hyphens");
|
|
588
938
|
else {
|
|
589
939
|
if (bucket.public !== void 0 && typeof bucket.public !== "boolean")
|
|
590
940
|
fail(`storage.buckets[${i}].public`, "public must be a boolean");
|
|
941
|
+
if (bucket.personalData !== void 0)
|
|
942
|
+
validateBucketPersonalData(bucket.personalData, `storage.buckets[${i}].personalData`, fail);
|
|
591
943
|
for (const key of Object.keys(bucket))
|
|
592
|
-
if (!["name", "public"].includes(key))
|
|
944
|
+
if (!["name", "public", "personalData"].includes(key))
|
|
593
945
|
fail(`storage.buckets[${i}].${key}`, "Unknown setting");
|
|
594
946
|
}
|
|
595
947
|
});
|
|
596
948
|
}
|
|
597
949
|
}
|
|
598
|
-
if (value.mail !== void 0 && (!
|
|
950
|
+
if (value.mail !== void 0 && (!object3(value.mail) || Object.keys(value.mail).some((k) => k !== "enabled") || value.mail.enabled !== void 0 && typeof value.mail.enabled !== "boolean"))
|
|
599
951
|
fail("mail", "mail accepts only enabled");
|
|
600
|
-
if (value.integrations !== void 0 && (!
|
|
952
|
+
if (value.integrations !== void 0 && (!object3(value.integrations) || Object.keys(value.integrations).some((k) => k !== "enabled") || value.integrations.enabled !== void 0 && typeof value.integrations.enabled !== "boolean"))
|
|
601
953
|
fail("integrations", "integrations accepts only enabled");
|
|
602
954
|
if (value.secrets !== void 0 && (!Array.isArray(value.secrets) || value.secrets.length > 100 || !distinct(value.secrets) || value.secrets.some((s) => typeof s !== "string" || !/^[A-Z][A-Z0-9_]{0,63}$/.test(s))))
|
|
603
955
|
fail("secrets", "List distinct UPPER_SNAKE secret names");
|
|
604
956
|
if (value.config !== void 0) {
|
|
605
|
-
if (!
|
|
957
|
+
if (!object3(value.config) || Object.keys(value.config).length > 200)
|
|
606
958
|
fail("config", "config must be an object with at most 200 values");
|
|
607
959
|
else
|
|
608
960
|
for (const [key, v] of Object.entries(value.config)) {
|
|
@@ -614,20 +966,22 @@ function validateAppConfig(value) {
|
|
|
614
966
|
}
|
|
615
967
|
if (value.http !== void 0) {
|
|
616
968
|
const http = value.http;
|
|
617
|
-
if (!
|
|
969
|
+
if (!object3(http) || Object.keys(http).some((k) => k !== "allow") || http.allow !== void 0 && (!Array.isArray(http.allow) || http.allow.length > 100 || http.allow.some((h) => typeof h !== "string" || !/^(?:\*\.)?[a-z0-9-]+(?:\.[a-z0-9-]+)+$/.test(h))))
|
|
618
970
|
fail("http.allow", "List outbound hostnames such as api.example.com or *.example.com");
|
|
619
971
|
}
|
|
620
972
|
if (value.ai !== void 0) {
|
|
621
973
|
const ai = value.ai;
|
|
622
|
-
if (!
|
|
974
|
+
if (!object3(ai) || Object.keys(ai).some((k) => k !== "models") || ai.models !== void 0 && (!Array.isArray(ai.models) || ai.models.length === 0 || ai.models.length > 20 || !distinct(ai.models) || ai.models.some((m) => !AI_MODEL_ALIASES.includes(m) && !(typeof m === "string" && /^[a-z0-9][a-z0-9.-]{1,63}$/.test(m)))))
|
|
623
975
|
fail("ai.models", "Use model aliases (default, fast, smart) or catalog model names");
|
|
624
976
|
}
|
|
625
977
|
if (value.protection !== void 0)
|
|
626
978
|
validateProtectionConfig(value.protection, fail);
|
|
979
|
+
if (value.retention !== void 0)
|
|
980
|
+
validateRetentionConfig(value.retention, "retention", fail);
|
|
627
981
|
return issues;
|
|
628
982
|
}
|
|
629
983
|
function validateScale(value, path, fail) {
|
|
630
|
-
if (!
|
|
984
|
+
if (!object3(value)) {
|
|
631
985
|
fail(path, "Scale settings must be an object");
|
|
632
986
|
return;
|
|
633
987
|
}
|
|
@@ -645,10 +999,10 @@ function validateScale(value, path, fail) {
|
|
|
645
999
|
fail(path + ".size", "Use small, medium or large");
|
|
646
1000
|
}
|
|
647
1001
|
function noCloudCoupling(value, path, fail) {
|
|
648
|
-
if (
|
|
1002
|
+
if (object3(value)) {
|
|
649
1003
|
for (const [key, child] of Object.entries(value)) {
|
|
650
1004
|
const here = path ? path + "." + key : key;
|
|
651
|
-
if (path !== "config" && CREDENTIAL_KEY.test(key))
|
|
1005
|
+
if (path !== "config" && !path.startsWith("database.personalData") && CREDENTIAL_KEY.test(key))
|
|
652
1006
|
fail(here, "Credentials and cloud placement do not belong in backify.config.ts");
|
|
653
1007
|
noCloudCoupling(child, here, fail);
|
|
654
1008
|
}
|
|
@@ -683,16 +1037,19 @@ function configuredCapabilities(config2) {
|
|
|
683
1037
|
result.add("protection");
|
|
684
1038
|
return APP_CAPABILITIES.filter((name2) => result.has(name2));
|
|
685
1039
|
}
|
|
686
|
-
var APP_CAPABILITIES, APP_KINDS, AUTH_PROVIDERS, AI_MODEL_ALIASES,
|
|
1040
|
+
var APP_CAPABILITIES, APP_KINDS, AUTH_PROVIDERS, AI_MODEL_ALIASES, DATABASE_EXTENSIONS, databaseExtensionsError, object3, portablePath, identifier, bounded, distinct, CREDENTIAL_KEY, CLOUD_VALUE;
|
|
687
1041
|
var init_app_config = __esm({
|
|
688
1042
|
"../platform/dist/app-config.js"() {
|
|
689
1043
|
"use strict";
|
|
690
1044
|
init_protection();
|
|
1045
|
+
init_personal_data();
|
|
691
1046
|
APP_CAPABILITIES = ["auth", "database", "storage", "backend", "jobs", "events", "mail", "secrets", "config", "http", "ai", "integrations", "logs", "protection"];
|
|
692
1047
|
APP_KINDS = ["web", "api", "worker"];
|
|
693
1048
|
AUTH_PROVIDERS = ["entra", "google", "email", "passkey"];
|
|
694
1049
|
AI_MODEL_ALIASES = ["default", "fast", "smart"];
|
|
695
|
-
|
|
1050
|
+
DATABASE_EXTENSIONS = ["btree_gist", "citext", "pg_trgm", "pgcrypto", "uuid-ossp", "vector"];
|
|
1051
|
+
databaseExtensionsError = "database.extensions must list distinct supported extensions: " + DATABASE_EXTENSIONS.join(", ");
|
|
1052
|
+
object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
696
1053
|
portablePath = (value) => typeof value === "string" && value.length > 0 && value.length <= 260 && !value.includes("\\") && !value.startsWith("/") && !value.includes(":") && !value.split("/").includes("..");
|
|
697
1054
|
identifier = (value) => typeof value === "string" && /^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(value);
|
|
698
1055
|
bounded = (value, max = 100) => typeof value === "string" && value.trim() === value && value.length > 0 && value.length <= max && !/[\x00-\x1f\x7f]/.test(value);
|
|
@@ -708,12 +1065,12 @@ function validateLockfile(value) {
|
|
|
708
1065
|
const fail = (message) => {
|
|
709
1066
|
errors.push(message);
|
|
710
1067
|
};
|
|
711
|
-
if (!
|
|
1068
|
+
if (!object4(value))
|
|
712
1069
|
return ["The lockfile must be a JSON object"];
|
|
713
1070
|
if (value.lockfileVersion !== LOCKFILE_VERSION)
|
|
714
1071
|
return ["Unsupported lockfileVersion; regenerate it with the current backify CLI"];
|
|
715
1072
|
const app = value.app;
|
|
716
|
-
if (!
|
|
1073
|
+
if (!object4(app) || !name(app.name) || !APP_KINDS.includes(app.kind))
|
|
717
1074
|
fail("app requires a lowercase name and kind web, api or worker");
|
|
718
1075
|
if (!nonEmpty(value.sdkVersion, 40))
|
|
719
1076
|
fail("sdkVersion is required");
|
|
@@ -725,7 +1082,7 @@ function validateLockfile(value) {
|
|
|
725
1082
|
fail("jobs must be an array");
|
|
726
1083
|
else
|
|
727
1084
|
for (const job of value.jobs) {
|
|
728
|
-
if (!
|
|
1085
|
+
if (!object4(job) || !name(job.name)) {
|
|
729
1086
|
fail("Each job needs a lowercase name");
|
|
730
1087
|
continue;
|
|
731
1088
|
}
|
|
@@ -741,13 +1098,15 @@ function validateLockfile(value) {
|
|
|
741
1098
|
if (!Number.isInteger(job.concurrency) || job.concurrency < 1 || job.concurrency > 100)
|
|
742
1099
|
fail(`Job ${job.name}: concurrency must be 1-100`);
|
|
743
1100
|
validateSource(job.source, "Job " + job.name, fail);
|
|
1101
|
+
if (job.personalData !== void 0)
|
|
1102
|
+
validateLockPayloadPersonalData(job.personalData, "Job " + job.name, fail);
|
|
744
1103
|
}
|
|
745
1104
|
const scheduleNames = /* @__PURE__ */ new Set();
|
|
746
1105
|
if (!Array.isArray(value.schedules))
|
|
747
1106
|
fail("schedules must be an array");
|
|
748
1107
|
else
|
|
749
1108
|
for (const schedule of value.schedules) {
|
|
750
|
-
if (!
|
|
1109
|
+
if (!object4(schedule) || !name(schedule.name)) {
|
|
751
1110
|
fail("Each schedule needs a lowercase name");
|
|
752
1111
|
continue;
|
|
753
1112
|
}
|
|
@@ -762,12 +1121,12 @@ function validateLockfile(value) {
|
|
|
762
1121
|
fail(`Schedule ${schedule.name}: job ${String(schedule.job)} is not declared`);
|
|
763
1122
|
validateSource(schedule.source, "Schedule " + schedule.name, fail);
|
|
764
1123
|
}
|
|
765
|
-
if (!
|
|
1124
|
+
if (!object4(value.events) || !Array.isArray(value.events.subscriptions))
|
|
766
1125
|
fail("events.subscriptions must be an array");
|
|
767
1126
|
else {
|
|
768
1127
|
const seen = /* @__PURE__ */ new Set();
|
|
769
1128
|
for (const sub of value.events.subscriptions) {
|
|
770
|
-
if (!
|
|
1129
|
+
if (!object4(sub) || typeof sub.event !== "string" || !/^[a-z][a-z0-9_.-]{0,99}$/.test(sub.event) || typeof sub.job !== "string") {
|
|
771
1130
|
fail("Each event subscription needs an event name and a job");
|
|
772
1131
|
continue;
|
|
773
1132
|
}
|
|
@@ -778,27 +1137,45 @@ function validateLockfile(value) {
|
|
|
778
1137
|
seen.add(sub.event + "\0" + sub.job);
|
|
779
1138
|
validateSource(sub.source, "Subscription " + sub.event, fail);
|
|
780
1139
|
}
|
|
1140
|
+
if (value.events.declarations !== void 0) {
|
|
1141
|
+
if (!Array.isArray(value.events.declarations))
|
|
1142
|
+
fail("events.declarations must be an array");
|
|
1143
|
+
else {
|
|
1144
|
+
const declared = /* @__PURE__ */ new Set();
|
|
1145
|
+
for (const declaration of value.events.declarations) {
|
|
1146
|
+
if (!object4(declaration) || typeof declaration.event !== "string" || !/^[a-z][a-z0-9_.-]{0,99}$/.test(declaration.event)) {
|
|
1147
|
+
fail("Each event declaration needs an event name");
|
|
1148
|
+
continue;
|
|
1149
|
+
}
|
|
1150
|
+
if (declared.has(declaration.event))
|
|
1151
|
+
fail("Duplicate event declaration " + declaration.event);
|
|
1152
|
+
declared.add(declaration.event);
|
|
1153
|
+
validateLockPayloadPersonalData(declaration.personalData, "Event " + declaration.event, fail);
|
|
1154
|
+
validateSource(declaration.source, "Event " + declaration.event, fail);
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
781
1158
|
}
|
|
782
1159
|
if (value.backend !== void 0) {
|
|
783
1160
|
const backend = value.backend;
|
|
784
1161
|
if (!capabilities.has("backend"))
|
|
785
1162
|
fail("backend is present but the backend capability is not declared");
|
|
786
|
-
if (!
|
|
1163
|
+
if (!object4(backend))
|
|
787
1164
|
fail("backend must be an object");
|
|
788
1165
|
else {
|
|
789
1166
|
if (typeof backend.health !== "string" || !ROUTE_PATH.test(backend.health))
|
|
790
1167
|
fail("backend.health must be a path");
|
|
791
|
-
if (!
|
|
1168
|
+
if (!object4(backend.schemas))
|
|
792
1169
|
fail("backend.schemas must be an object");
|
|
793
|
-
if (!
|
|
1170
|
+
if (!object4(backend.openapi) || typeof backend.openapi.openapi !== "string" || !backend.openapi.openapi.startsWith("3.1"))
|
|
794
1171
|
fail("backend.openapi must be an OpenAPI 3.1 document");
|
|
795
|
-
const schemas =
|
|
1172
|
+
const schemas = object4(backend.schemas) ? backend.schemas : {};
|
|
796
1173
|
const operations = /* @__PURE__ */ new Set(), endpoints = /* @__PURE__ */ new Set();
|
|
797
1174
|
if (!Array.isArray(backend.routes))
|
|
798
1175
|
fail("backend.routes must be an array");
|
|
799
1176
|
else
|
|
800
1177
|
for (const route of backend.routes) {
|
|
801
|
-
if (!
|
|
1178
|
+
if (!object4(route) || !HTTP_METHODS.includes(route.method) || typeof route.path !== "string" || !ROUTE_PATH.test(route.path)) {
|
|
802
1179
|
fail("Each route needs a method and a path");
|
|
803
1180
|
continue;
|
|
804
1181
|
}
|
|
@@ -816,7 +1193,7 @@ function validateLockfile(value) {
|
|
|
816
1193
|
fail(`${label}: auth must be public, user, role or permission`);
|
|
817
1194
|
if (route.summary !== void 0 && !nonEmpty(route.summary, 300))
|
|
818
1195
|
fail(`${label}: summary must be at most 300 characters`);
|
|
819
|
-
for (const ref of [...
|
|
1196
|
+
for (const ref of [...object4(route.request) ? Object.values(route.request) : [], route.response])
|
|
820
1197
|
if (ref !== void 0 && (typeof ref !== "string" || !Object.hasOwn(schemas, ref)))
|
|
821
1198
|
fail(`${label}: unknown schema ${String(ref)}`);
|
|
822
1199
|
if (route.protection !== void 0)
|
|
@@ -826,16 +1203,25 @@ function validateLockfile(value) {
|
|
|
826
1203
|
}
|
|
827
1204
|
} else if (capabilities.has("backend"))
|
|
828
1205
|
fail("The backend capability requires a backend section");
|
|
829
|
-
if (value.frontend !== void 0 && (!
|
|
1206
|
+
if (value.frontend !== void 0 && (!object4(value.frontend) || typeof value.frontend.output !== "string" || typeof value.frontend.spa !== "boolean"))
|
|
830
1207
|
fail("frontend requires output and spa");
|
|
831
|
-
if (value.storage !== void 0 && (!
|
|
1208
|
+
if (value.storage !== void 0 && (!object4(value.storage) || !Array.isArray(value.storage.buckets) || value.storage.buckets.some((b) => !object4(b) || typeof b.name !== "string" || typeof b.public !== "boolean")))
|
|
832
1209
|
fail("storage.buckets must list name and public");
|
|
1210
|
+
else if (object4(value.storage) && Array.isArray(value.storage.buckets))
|
|
1211
|
+
for (const bucket of value.storage.buckets) {
|
|
1212
|
+
if (bucket.personalData !== void 0)
|
|
1213
|
+
validateLockBucketPersonalData(bucket.personalData, String(bucket.name), fail);
|
|
1214
|
+
}
|
|
833
1215
|
if (value.database !== void 0) {
|
|
834
1216
|
const db = value.database;
|
|
835
|
-
if (!
|
|
1217
|
+
if (!object4(db) || !Array.isArray(db.migrations) || db.migrations.some((m) => !object4(m) || !nonEmpty(m.file, 260) || !sha256(m.sha256)) || !Array.isArray(db.sensitiveColumns))
|
|
836
1218
|
fail("database requires migrations with file and sha256, and sensitiveColumns");
|
|
1219
|
+
else if (db.personalData !== void 0)
|
|
1220
|
+
validateLockPersonalData(db.personalData, fail);
|
|
1221
|
+
if (object4(db) && db.extensions !== void 0 && !validDatabaseExtensions(db.extensions))
|
|
1222
|
+
fail(databaseExtensionsError);
|
|
837
1223
|
}
|
|
838
|
-
if (value.auth !== void 0 && (!
|
|
1224
|
+
if (value.auth !== void 0 && (!object4(value.auth) || !Array.isArray(value.auth.providers) || !Array.isArray(value.auth.roles)))
|
|
839
1225
|
fail("auth requires providers and roles");
|
|
840
1226
|
if (!Array.isArray(value.secrets) || value.secrets.some((s) => typeof s !== "string"))
|
|
841
1227
|
fail("secrets must be an array of names");
|
|
@@ -846,17 +1232,19 @@ function validateLockfile(value) {
|
|
|
846
1232
|
fail("protection is present but the protection capability is not declared");
|
|
847
1233
|
validateProtectionConfig(value.protection, (path, message) => fail(`${path}: ${message}`));
|
|
848
1234
|
}
|
|
1235
|
+
if (value.retention !== void 0)
|
|
1236
|
+
validateRetentionConfig(value.retention, "retention", (path, message) => fail(`${path}: ${message}`));
|
|
849
1237
|
const carried = Object.fromEntries(["config", "ai", "http", "mail", "integrations"].filter((key) => value[key] !== void 0).map((key) => [key, value[key]]));
|
|
850
1238
|
for (const issue2 of validateAppConfig({ app: { name: "lock-validation" }, kind: "worker", server: { entry: "server/index.ts" }, ...carried }))
|
|
851
1239
|
if (["config", "ai", "http", "mail", "integrations"].some((key) => issue2.path === key || issue2.path.startsWith(key + ".")))
|
|
852
1240
|
fail(issue2.path + ": " + issue2.message);
|
|
853
1241
|
for (const key of Object.keys(value))
|
|
854
|
-
if (!["lockfileVersion", "app", "sdkVersion", "capabilities", "backend", "frontend", "jobs", "schedules", "events", "storage", "database", "auth", "secrets", "protection", "config", "ai", "http", "mail", "integrations"].includes(key))
|
|
1242
|
+
if (!["lockfileVersion", "app", "sdkVersion", "capabilities", "backend", "frontend", "jobs", "schedules", "events", "storage", "database", "auth", "secrets", "protection", "config", "ai", "http", "mail", "integrations", "retention"].includes(key))
|
|
855
1243
|
fail("Unknown lockfile field " + key);
|
|
856
1244
|
return errors;
|
|
857
1245
|
}
|
|
858
1246
|
function validAuth(value) {
|
|
859
|
-
if (!
|
|
1247
|
+
if (!object4(value))
|
|
860
1248
|
return false;
|
|
861
1249
|
if (value.kind === "public" || value.kind === "user")
|
|
862
1250
|
return Object.keys(value).length === 1;
|
|
@@ -869,24 +1257,25 @@ function validAuth(value) {
|
|
|
869
1257
|
function validateSource(value, label, fail) {
|
|
870
1258
|
if (value === void 0)
|
|
871
1259
|
return;
|
|
872
|
-
if (!
|
|
1260
|
+
if (!object4(value) || typeof value.file !== "string" || value.file.startsWith("/") || value.file.includes("..") || !Number.isInteger(value.line) || value.line < 1)
|
|
873
1261
|
fail(label + ": source must be a repository-relative file and line");
|
|
874
1262
|
}
|
|
875
1263
|
function serializeLockfile(lockfile) {
|
|
876
|
-
const sort = (value) => Array.isArray(value) ? value.map(sort) :
|
|
1264
|
+
const sort = (value) => Array.isArray(value) ? value.map(sort) : object4(value) ? Object.fromEntries(Object.keys(value).sort().filter((k) => value[k] !== void 0).map((k) => [k, sort(value[k])])) : value;
|
|
877
1265
|
return JSON.stringify(sort(lockfile), null, 2) + "\n";
|
|
878
1266
|
}
|
|
879
|
-
var LOCKFILE_VERSION, LOCKFILE_NAME, LOCKFILE_MAX_BYTES, HTTP_METHODS,
|
|
1267
|
+
var LOCKFILE_VERSION, LOCKFILE_NAME, LOCKFILE_MAX_BYTES, HTTP_METHODS, object4, name, nonEmpty, sha256, ROUTE_PATH, CRON;
|
|
880
1268
|
var init_lockfile = __esm({
|
|
881
1269
|
"../platform/dist/lockfile.js"() {
|
|
882
1270
|
"use strict";
|
|
883
1271
|
init_app_config();
|
|
884
1272
|
init_protection();
|
|
1273
|
+
init_personal_data();
|
|
885
1274
|
LOCKFILE_VERSION = 1;
|
|
886
1275
|
LOCKFILE_NAME = "backify.lock.json";
|
|
887
1276
|
LOCKFILE_MAX_BYTES = 2 * 1024 * 1024;
|
|
888
1277
|
HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
|
|
889
|
-
|
|
1278
|
+
object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
890
1279
|
name = (value) => typeof value === "string" && /^[a-z][a-z0-9-]{0,62}$/.test(value);
|
|
891
1280
|
nonEmpty = (value, max = 200) => typeof value === "string" && value.length > 0 && value.length <= max && !/[\x00-\x1f\x7f]/.test(value);
|
|
892
1281
|
sha256 = (value) => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
|
|
@@ -895,6 +1284,186 @@ var init_lockfile = __esm({
|
|
|
895
1284
|
}
|
|
896
1285
|
});
|
|
897
1286
|
|
|
1287
|
+
// ../platform/dist/schema-scan.js
|
|
1288
|
+
function splitTop(text2, separator) {
|
|
1289
|
+
const parts = [];
|
|
1290
|
+
let depth = 0, quote = "", start = 0;
|
|
1291
|
+
for (let i = 0; i < text2.length; i++) {
|
|
1292
|
+
const c = text2[i];
|
|
1293
|
+
if (quote) {
|
|
1294
|
+
if (c === quote)
|
|
1295
|
+
quote = "";
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
if (c === "'" || c === '"')
|
|
1299
|
+
quote = c;
|
|
1300
|
+
else if (c === "(")
|
|
1301
|
+
depth++;
|
|
1302
|
+
else if (c === ")")
|
|
1303
|
+
depth--;
|
|
1304
|
+
else if (c === separator && depth === 0) {
|
|
1305
|
+
parts.push(text2.slice(start, i));
|
|
1306
|
+
start = i + 1;
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
parts.push(text2.slice(start));
|
|
1310
|
+
return parts;
|
|
1311
|
+
}
|
|
1312
|
+
function stripSql(sql) {
|
|
1313
|
+
const blank = (match) => match.replace(/[^\n]/g, " ");
|
|
1314
|
+
return sql.replace(/\$([A-Za-z_]*)\$[\s\S]*?\$\1\$/g, blank).replace(/\/\*[\s\S]*?\*\//g, blank).replace(/--[^\n]*/g, blank);
|
|
1315
|
+
}
|
|
1316
|
+
function scanMigrations(files) {
|
|
1317
|
+
const tables = /* @__PURE__ */ new Map();
|
|
1318
|
+
const uncertain = /* @__PURE__ */ new Set();
|
|
1319
|
+
for (const { file, sql } of files) {
|
|
1320
|
+
const text2 = stripSql(sql);
|
|
1321
|
+
let offset = 0;
|
|
1322
|
+
for (const statement of splitTop(text2, ";")) {
|
|
1323
|
+
const bodyStart = offset + statement.length - statement.trimStart().length;
|
|
1324
|
+
const lineAt = (index) => text2.slice(0, bodyStart + index).split("\n").length;
|
|
1325
|
+
const body = statement.trim();
|
|
1326
|
+
offset += statement.length + 1;
|
|
1327
|
+
const create = /^create\s+(?:(?:global\s+|local\s+)?(?:temporary|temp|unlogged)\s+)?table\s+(?:if\s+not\s+exists\s+)?/i.exec(body);
|
|
1328
|
+
if (create) {
|
|
1329
|
+
const name2 = QUALIFIED.exec(body.slice(create[0].length));
|
|
1330
|
+
if (!name2)
|
|
1331
|
+
continue;
|
|
1332
|
+
const schema = name2[1] ? unquote(name2[1]) : "public", table = unquote(name2[2]);
|
|
1333
|
+
if (schema !== "public")
|
|
1334
|
+
continue;
|
|
1335
|
+
const open2 = body.indexOf("(", create[0].length + name2[0].length);
|
|
1336
|
+
if (open2 < 0 || /\bas\s+select\b|\bpartition\s+of\b|\bof\s+/i.test(body.slice(create[0].length + name2[0].length, open2))) {
|
|
1337
|
+
uncertain.add(table);
|
|
1338
|
+
tables.set(table, []);
|
|
1339
|
+
continue;
|
|
1340
|
+
}
|
|
1341
|
+
const columns = [];
|
|
1342
|
+
let position2 = open2 + 1;
|
|
1343
|
+
const inner = body.slice(open2 + 1, body.lastIndexOf(")"));
|
|
1344
|
+
for (const definition of splitTop(inner, ",")) {
|
|
1345
|
+
const trimmed = definition.trim();
|
|
1346
|
+
const at = position2 + (definition.length - definition.trimStart().length);
|
|
1347
|
+
position2 += definition.length + 1;
|
|
1348
|
+
if (!trimmed || /^(constraint|primary\s+key|unique|check|foreign\s+key|exclude)\b/i.test(trimmed))
|
|
1349
|
+
continue;
|
|
1350
|
+
if (/^like\b/i.test(trimmed)) {
|
|
1351
|
+
uncertain.add(table);
|
|
1352
|
+
continue;
|
|
1353
|
+
}
|
|
1354
|
+
const column = new RegExp("^" + IDENT).exec(trimmed);
|
|
1355
|
+
if (column)
|
|
1356
|
+
columns.push({ name: unquote(column[0]), file, line: lineAt(at) });
|
|
1357
|
+
}
|
|
1358
|
+
tables.set(table, columns);
|
|
1359
|
+
continue;
|
|
1360
|
+
}
|
|
1361
|
+
const alter = /^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?/i.exec(body);
|
|
1362
|
+
if (alter) {
|
|
1363
|
+
const name2 = QUALIFIED.exec(body.slice(alter[0].length));
|
|
1364
|
+
if (!name2)
|
|
1365
|
+
continue;
|
|
1366
|
+
const schema = name2[1] ? unquote(name2[1]) : "public", table = unquote(name2[2]);
|
|
1367
|
+
if (schema !== "public")
|
|
1368
|
+
continue;
|
|
1369
|
+
const rest = body.slice(alter[0].length + name2[0].length).trim();
|
|
1370
|
+
const rename = /^rename\s+to\s+(\S+)$/i.exec(rest);
|
|
1371
|
+
if (rename) {
|
|
1372
|
+
const target = unquote(rename[1]);
|
|
1373
|
+
tables.set(target, tables.get(table) ?? []);
|
|
1374
|
+
tables.delete(table);
|
|
1375
|
+
if (uncertain.delete(table))
|
|
1376
|
+
uncertain.add(target);
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
const columns = tables.get(table);
|
|
1380
|
+
if (!columns) {
|
|
1381
|
+
uncertain.add(table);
|
|
1382
|
+
tables.set(table, []);
|
|
1383
|
+
}
|
|
1384
|
+
const list = tables.get(table);
|
|
1385
|
+
const renameColumn = /^rename\s+(?:column\s+)?(\S+)\s+to\s+(\S+)$/i.exec(rest);
|
|
1386
|
+
if (renameColumn) {
|
|
1387
|
+
const from = unquote(renameColumn[1]);
|
|
1388
|
+
const found = list.find((c) => c.name === from);
|
|
1389
|
+
if (found)
|
|
1390
|
+
found.name = unquote(renameColumn[2]);
|
|
1391
|
+
else
|
|
1392
|
+
uncertain.add(table);
|
|
1393
|
+
continue;
|
|
1394
|
+
}
|
|
1395
|
+
let actionOffset = alter[0].length + name2[0].length;
|
|
1396
|
+
for (const action of splitTop(body.slice(actionOffset), ",")) {
|
|
1397
|
+
const trimmed = action.trim();
|
|
1398
|
+
const at = actionOffset + (action.length - action.trimStart().length);
|
|
1399
|
+
actionOffset += action.length + 1;
|
|
1400
|
+
const add = new RegExp(String.raw`^add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?(${IDENT})`, "i").exec(trimmed);
|
|
1401
|
+
const drop = new RegExp(String.raw`^drop\s+(?:column\s+)?(?:if\s+exists\s+)?(${IDENT})`, "i").exec(trimmed);
|
|
1402
|
+
if (add && !/^add\s+(constraint|primary\s+key|unique|check|foreign\s+key|exclude)\b/i.test(trimmed)) {
|
|
1403
|
+
const columnName = unquote(add[1]);
|
|
1404
|
+
if (!list.some((c) => c.name === columnName))
|
|
1405
|
+
list.push({ name: columnName, file, line: lineAt(at) });
|
|
1406
|
+
} else if (drop && !/^drop\s+constraint\b/i.test(trimmed)) {
|
|
1407
|
+
const columnName = unquote(drop[1]);
|
|
1408
|
+
const index = list.findIndex((c) => c.name === columnName);
|
|
1409
|
+
if (index >= 0)
|
|
1410
|
+
list.splice(index, 1);
|
|
1411
|
+
} else if (!/^(add|drop|alter|set|reset|enable|disable|force|no\s+force|owner|cluster|inherit|no\s+inherit|validate|replica|attach|detach)\b/i.test(trimmed))
|
|
1412
|
+
uncertain.add(table);
|
|
1413
|
+
}
|
|
1414
|
+
continue;
|
|
1415
|
+
}
|
|
1416
|
+
const dropTable = /^drop\s+table\s+(?:if\s+exists\s+)?([\s\S]+?)(?:\s+(?:cascade|restrict))?$/i.exec(body);
|
|
1417
|
+
if (dropTable)
|
|
1418
|
+
for (const item of splitTop(dropTable[1], ",")) {
|
|
1419
|
+
const name2 = QUALIFIED.exec(item.trim());
|
|
1420
|
+
if (name2 && (!name2[1] || unquote(name2[1]) === "public")) {
|
|
1421
|
+
tables.delete(unquote(name2[2]));
|
|
1422
|
+
uncertain.delete(unquote(name2[2]));
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
return { tables, uncertain };
|
|
1428
|
+
}
|
|
1429
|
+
function personalDataDrift(declared, schema) {
|
|
1430
|
+
const tables = schema instanceof Map ? schema : new Map(Object.entries(schema));
|
|
1431
|
+
const missingTables = [], missingColumns = [], undeclaredCandidates = [];
|
|
1432
|
+
const covered = /* @__PURE__ */ new Set();
|
|
1433
|
+
for (const table of declared) {
|
|
1434
|
+
const columns = tables.get(table.table);
|
|
1435
|
+
const needed = [...table.columns.map((c) => c.name), ...table.subject.kind === "none" ? [] : [table.subject.column], ...table.keep ? [table.keep.after] : [], ...table.retain ? [table.retain.after] : []];
|
|
1436
|
+
for (const name2 of needed)
|
|
1437
|
+
covered.add(`${table.table}.${name2}`);
|
|
1438
|
+
if (!columns) {
|
|
1439
|
+
missingTables.push(table.table);
|
|
1440
|
+
continue;
|
|
1441
|
+
}
|
|
1442
|
+
for (const name2 of new Set(needed))
|
|
1443
|
+
if (!columns.includes(name2))
|
|
1444
|
+
missingColumns.push(`${table.table}.${name2}`);
|
|
1445
|
+
}
|
|
1446
|
+
for (const [table, columns] of tables)
|
|
1447
|
+
for (const name2 of columns)
|
|
1448
|
+
if (PERSONAL_COLUMN_NAME.test(name2) && !covered.has(`${table}.${name2}`))
|
|
1449
|
+
undeclaredCandidates.push(`${table}.${name2}`);
|
|
1450
|
+
return { missingTables: missingTables.sort(), missingColumns: missingColumns.sort(), undeclaredCandidates: undeclaredCandidates.sort() };
|
|
1451
|
+
}
|
|
1452
|
+
function personalDataSnippet(table, columns) {
|
|
1453
|
+
const category = (name2) => /^ip(_?address)?$|user_?agent/i.test(name2) ? "usage" : /mail|phone|mobile|address|post_?code|zip/i.test(name2) ? "contact" : /birth|dob|passport|national|personnummer|ssn|social|tax|name|gender/i.test(name2) ? "identity" : /iban/i.test(name2) ? "financial" : /lat|lon|location|geo/i.test(name2) ? "location" : /health|medical|diagnosis|biometric|religion|ethnic|sexual/i.test(name2) ? "special-category" : "usage";
|
|
1454
|
+
return `${table}: { subject: "user_id", columns: { ${columns.map((c) => `${c}: "${category(c)}"`).join(", ")} } },`;
|
|
1455
|
+
}
|
|
1456
|
+
var unquote, IDENT, QUALIFIED;
|
|
1457
|
+
var init_schema_scan = __esm({
|
|
1458
|
+
"../platform/dist/schema-scan.js"() {
|
|
1459
|
+
"use strict";
|
|
1460
|
+
init_personal_data();
|
|
1461
|
+
unquote = (name2) => name2.startsWith('"') && name2.endsWith('"') ? name2.slice(1, -1).replace(/""/g, '"') : name2.toLowerCase();
|
|
1462
|
+
IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`;
|
|
1463
|
+
QUALIFIED = new RegExp(String.raw`^(?:(${IDENT})\.)?(${IDENT})`);
|
|
1464
|
+
}
|
|
1465
|
+
});
|
|
1466
|
+
|
|
898
1467
|
// ../platform/dist/auth-setup.js
|
|
899
1468
|
function authSetupWarnings(providers) {
|
|
900
1469
|
const missing = (providers ?? []).filter((provider) => AUTH_PROVIDERS.includes(provider) && needsCredentials(provider));
|
|
@@ -919,6 +1488,170 @@ var init_auth_setup = __esm({
|
|
|
919
1488
|
}
|
|
920
1489
|
});
|
|
921
1490
|
|
|
1491
|
+
// ../platform/dist/operations.js
|
|
1492
|
+
function missingOperationScopes(required2, granted) {
|
|
1493
|
+
if (!required2)
|
|
1494
|
+
return null;
|
|
1495
|
+
return required2.filter((scope) => !granted.includes(scope));
|
|
1496
|
+
}
|
|
1497
|
+
function nearlyEqual(left, right) {
|
|
1498
|
+
if (Math.abs(left.length - right.length) > 1 || left.length < 5)
|
|
1499
|
+
return false;
|
|
1500
|
+
let i = 0, j = 0, edits = 0;
|
|
1501
|
+
while (i < left.length && j < right.length) {
|
|
1502
|
+
if (left[i] === right[j]) {
|
|
1503
|
+
i++;
|
|
1504
|
+
j++;
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1507
|
+
if (++edits > 1)
|
|
1508
|
+
return false;
|
|
1509
|
+
if (left.length > right.length)
|
|
1510
|
+
i++;
|
|
1511
|
+
else if (right.length > left.length)
|
|
1512
|
+
j++;
|
|
1513
|
+
else {
|
|
1514
|
+
i++;
|
|
1515
|
+
j++;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
return edits + (left.length - i) + (right.length - j) <= 1;
|
|
1519
|
+
}
|
|
1520
|
+
function searchOperations(operations, query = "", group) {
|
|
1521
|
+
const inGroup = operations.filter((operation) => !group || operation.group.toLowerCase() === group.toLowerCase());
|
|
1522
|
+
const terms = words(query);
|
|
1523
|
+
if (!terms.length)
|
|
1524
|
+
return [...inGroup];
|
|
1525
|
+
const scored = inGroup.map((operation) => {
|
|
1526
|
+
const fields = [[[...words(operation.group), ...words(operation.action)], 5], [words(operation.summary ?? ""), 2], [words(operation.path), 1], [[operation.method.toLowerCase()], 1]];
|
|
1527
|
+
let score = 0, matched = 0;
|
|
1528
|
+
for (const term of terms) {
|
|
1529
|
+
const exact = singular(term);
|
|
1530
|
+
const related = new Set([...synonyms[term] ?? [], ...synonyms[exact] ?? []].map(singular));
|
|
1531
|
+
let best = 0;
|
|
1532
|
+
for (const [fieldWords, weight] of fields)
|
|
1533
|
+
for (const word of fieldWords) {
|
|
1534
|
+
const base = singular(word);
|
|
1535
|
+
const value = base === exact ? weight : related.has(base) ? weight * 0.8 : base.startsWith(exact) && term.length >= 3 ? weight * 0.6 : nearlyEqual(base, exact) ? weight * 0.5 : 0;
|
|
1536
|
+
if (value > best)
|
|
1537
|
+
best = value;
|
|
1538
|
+
}
|
|
1539
|
+
if (best > 0)
|
|
1540
|
+
matched++;
|
|
1541
|
+
score += best;
|
|
1542
|
+
}
|
|
1543
|
+
return { operation, score: score + matched * 10 + (matched === terms.length ? 50 : 0) };
|
|
1544
|
+
}).filter((entry) => entry.score > 0);
|
|
1545
|
+
return scored.sort((left, right) => right.score - left.score || left.operation.id.localeCompare(right.operation.id)).map((entry) => entry.operation);
|
|
1546
|
+
}
|
|
1547
|
+
function checkedBase64(value, limit) {
|
|
1548
|
+
if (value.length > limit || !base64.test(value))
|
|
1549
|
+
throw new OperationRequestError("Invalid or oversized base64 payload.");
|
|
1550
|
+
return value;
|
|
1551
|
+
}
|
|
1552
|
+
function buildOperationRequest(operation, input, maximumBase64Length = 16 * 1024 * 1024) {
|
|
1553
|
+
if (!/^\/api\/[a-zA-Z0-9{}/_.:-]+$/.test(operation.path) || !["GET", "POST", "PUT", "PATCH", "DELETE"].includes(operation.method))
|
|
1554
|
+
throw new OperationRequestError("Invalid catalog route.");
|
|
1555
|
+
let path = operation.path;
|
|
1556
|
+
const supplied = input.parameters ?? {};
|
|
1557
|
+
const routed = operation.parameters.filter((parameter) => ["path", "query"].includes(parameter.location));
|
|
1558
|
+
const accepted = new Set(routed.map((parameter) => parameter.name));
|
|
1559
|
+
for (const name2 of Object.keys(supplied))
|
|
1560
|
+
if (!accepted.has(name2))
|
|
1561
|
+
throw new OperationRequestError("Unknown parameter: " + name2);
|
|
1562
|
+
const query = new URLSearchParams();
|
|
1563
|
+
for (const parameter of routed) {
|
|
1564
|
+
const organizationParameter = ["org", "organizationId", "orgId"].includes(parameter.name);
|
|
1565
|
+
const value = organizationParameter ? input.organizationId : supplied[parameter.name];
|
|
1566
|
+
if (organizationParameter && supplied[parameter.name] !== void 0 && String(supplied[parameter.name]).toLowerCase() !== String(value).toLowerCase())
|
|
1567
|
+
throw new OperationRequestError("Pass the organization with --organization, not as an operation parameter.");
|
|
1568
|
+
if (value === void 0) {
|
|
1569
|
+
if (parameter.required)
|
|
1570
|
+
throw new OperationRequestError("Missing parameter: " + parameter.name);
|
|
1571
|
+
continue;
|
|
1572
|
+
}
|
|
1573
|
+
if (parameter.location === "path") {
|
|
1574
|
+
if (Array.isArray(value) || /[/\\%?#\u0000-\u001f\u007f]/.test(String(value)) || !String(value) || [".", ".."].includes(String(value)))
|
|
1575
|
+
throw new OperationRequestError("Invalid route parameter: " + parameter.name);
|
|
1576
|
+
path = path.replace(new RegExp("\\{" + parameter.name + "(?::[^}]+)?\\}", "g"), encodeURIComponent(String(value)));
|
|
1577
|
+
} else
|
|
1578
|
+
for (const item of Array.isArray(value) ? value : [value])
|
|
1579
|
+
query.append(parameter.name, String(item));
|
|
1580
|
+
}
|
|
1581
|
+
if (path.includes("{") || path.split("/").some((segment) => segment === "." || segment === ".."))
|
|
1582
|
+
throw new OperationRequestError("Unresolved or unsafe route.");
|
|
1583
|
+
const request = { method: operation.method, path: path.substring(4) + (query.size ? "?" + query : "") };
|
|
1584
|
+
const bodyParameter = operation.parameters.find((parameter) => parameter.location === "body");
|
|
1585
|
+
const formFile = operation.parameters.find((parameter) => parameter.location === "formfile");
|
|
1586
|
+
if (operation.rawBodyContentType) {
|
|
1587
|
+
if (!input.rawBodyBase64 || input.body !== void 0 || input.file)
|
|
1588
|
+
throw new OperationRequestError("This operation takes a raw " + operation.rawBodyContentType + " body only.");
|
|
1589
|
+
request.body = { kind: "raw", contentType: operation.rawBodyContentType, contentBase64: checkedBase64(input.rawBodyBase64, maximumBase64Length) };
|
|
1590
|
+
} else if (formFile) {
|
|
1591
|
+
if (!input.file || input.body !== void 0 || input.rawBodyBase64)
|
|
1592
|
+
throw new OperationRequestError("This operation takes a single file (" + formFile.name + ") only.");
|
|
1593
|
+
request.body = { kind: "file", field: formFile.name, name: input.file.name, contentType: input.file.contentType, contentBase64: checkedBase64(input.file.contentBase64, maximumBase64Length) };
|
|
1594
|
+
} else {
|
|
1595
|
+
if (input.file || input.rawBodyBase64 || input.body !== void 0 && !bodyParameter)
|
|
1596
|
+
throw new OperationRequestError("Unexpected request body.");
|
|
1597
|
+
if (bodyParameter?.required && input.body === void 0)
|
|
1598
|
+
throw new OperationRequestError("Request body is required. Describe the operation for its schema.");
|
|
1599
|
+
if (input.body !== void 0)
|
|
1600
|
+
request.body = { kind: "json", value: input.body };
|
|
1601
|
+
}
|
|
1602
|
+
return request;
|
|
1603
|
+
}
|
|
1604
|
+
var OperationRequestError, synonyms, words, singular, base64;
|
|
1605
|
+
var init_operations = __esm({
|
|
1606
|
+
"../platform/dist/operations.js"() {
|
|
1607
|
+
"use strict";
|
|
1608
|
+
OperationRequestError = class extends Error {
|
|
1609
|
+
};
|
|
1610
|
+
synonyms = {
|
|
1611
|
+
app: ["apps", "application", "applications"],
|
|
1612
|
+
application: ["app", "apps"],
|
|
1613
|
+
list: ["get", "all", "search", "page"],
|
|
1614
|
+
show: ["get", "list", "summary"],
|
|
1615
|
+
get: ["list", "details"],
|
|
1616
|
+
remove: ["delete"],
|
|
1617
|
+
delete: ["remove"],
|
|
1618
|
+
add: ["create", "invite", "set"],
|
|
1619
|
+
create: ["add", "new"],
|
|
1620
|
+
new: ["create"],
|
|
1621
|
+
change: ["update", "set"],
|
|
1622
|
+
edit: ["update"],
|
|
1623
|
+
rename: ["update"],
|
|
1624
|
+
update: ["set", "change"],
|
|
1625
|
+
deploy: ["deployment", "deployments", "publish", "promote", "preview", "release"],
|
|
1626
|
+
release: ["releases", "promote", "publish"],
|
|
1627
|
+
ship: ["promote", "publish"],
|
|
1628
|
+
member: ["members", "users", "people", "invitation"],
|
|
1629
|
+
user: ["member", "members"],
|
|
1630
|
+
people: ["members"],
|
|
1631
|
+
cost: ["costs", "billing", "spend"],
|
|
1632
|
+
spend: ["costs"],
|
|
1633
|
+
price: ["billing", "costs"],
|
|
1634
|
+
secret: ["secrets"],
|
|
1635
|
+
env: ["environment", "environments"],
|
|
1636
|
+
db: ["database"],
|
|
1637
|
+
database: ["databases"],
|
|
1638
|
+
domain: ["domains"],
|
|
1639
|
+
log: ["logs"],
|
|
1640
|
+
schedule: ["schedules", "scheduler"],
|
|
1641
|
+
cron: ["schedules", "scheduler"],
|
|
1642
|
+
workspace: ["workspaces"],
|
|
1643
|
+
team: ["teams"],
|
|
1644
|
+
role: ["roles"],
|
|
1645
|
+
storage: ["files", "blob"],
|
|
1646
|
+
function: ["functions"],
|
|
1647
|
+
ai: ["model", "models"]
|
|
1648
|
+
};
|
|
1649
|
+
words = (value) => value.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
1650
|
+
singular = (word) => word.length > 4 && word.endsWith("s") && !/(ss|us|is)$/.test(word) ? word.slice(0, -1) : word;
|
|
1651
|
+
base64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
1652
|
+
}
|
|
1653
|
+
});
|
|
1654
|
+
|
|
922
1655
|
// ../platform/dist/index.js
|
|
923
1656
|
function managedInstructions() {
|
|
924
1657
|
return `${MANAGED_START}
|
|
@@ -1031,9 +1764,12 @@ var init_dist = __esm({
|
|
|
1031
1764
|
init_delivery();
|
|
1032
1765
|
init_app_config();
|
|
1033
1766
|
init_lockfile();
|
|
1767
|
+
init_personal_data();
|
|
1768
|
+
init_schema_scan();
|
|
1034
1769
|
init_protection();
|
|
1035
1770
|
init_auth_setup();
|
|
1036
|
-
|
|
1771
|
+
init_operations();
|
|
1772
|
+
INSTRUCTION_VERSION = 19;
|
|
1037
1773
|
SDK_PACKAGE = "@backifydev/sdk";
|
|
1038
1774
|
DOCS_URL = "https://docs.backify.dev";
|
|
1039
1775
|
MAIL_LIMITS = Object.freeze({
|
|
@@ -1091,19 +1827,19 @@ function configObject(text2) {
|
|
|
1091
1827
|
requireStaticProperties(expression);
|
|
1092
1828
|
return { source, object: expression };
|
|
1093
1829
|
}
|
|
1094
|
-
function requireStaticProperties(
|
|
1830
|
+
function requireStaticProperties(object8) {
|
|
1095
1831
|
const seen = /* @__PURE__ */ new Set();
|
|
1096
|
-
for (const item of
|
|
1832
|
+
for (const item of object8.properties) {
|
|
1097
1833
|
if (!ts.isPropertyAssignment(item) || !(ts.isIdentifier(item.name) || ts.isStringLiteral(item.name))) throw new Error("Top-level configuration and app metadata require literal properties; spreads and computed keys can hide connection metadata.");
|
|
1098
1834
|
if (seen.has(item.name.text)) throw new Error(`Duplicate configuration property ${item.name.text}.`);
|
|
1099
1835
|
seen.add(item.name.text);
|
|
1100
1836
|
}
|
|
1101
1837
|
}
|
|
1102
|
-
function property(
|
|
1103
|
-
return
|
|
1838
|
+
function property(object8, name2) {
|
|
1839
|
+
return object8.properties.find((item) => ts.isPropertyAssignment(item) && (ts.isIdentifier(item.name) || ts.isStringLiteral(item.name)) && item.name.text === name2);
|
|
1104
1840
|
}
|
|
1105
|
-
function literal(
|
|
1106
|
-
const item = property(
|
|
1841
|
+
function literal(object8, name2) {
|
|
1842
|
+
const item = property(object8, name2);
|
|
1107
1843
|
if (!item) return void 0;
|
|
1108
1844
|
if (ts.isStringLiteral(item.initializer)) return item.initializer.text;
|
|
1109
1845
|
if (ts.isNumericLiteral(item.initializer)) return Number(item.initializer.text);
|
|
@@ -1114,8 +1850,8 @@ function readProjectMetadata(root) {
|
|
|
1114
1850
|
const legacy = existsSync(legacyPath) ? JSON.parse(readFileSync(legacyPath, "utf8")) : {};
|
|
1115
1851
|
const path = join(root, APP_CONFIG_FILE);
|
|
1116
1852
|
if (!existsSync(path)) return legacy;
|
|
1117
|
-
const { object:
|
|
1118
|
-
const app = property(
|
|
1853
|
+
const { object: object8 } = configObject(readFileSync(path, "utf8"));
|
|
1854
|
+
const app = property(object8, "app")?.initializer;
|
|
1119
1855
|
if (!app || !ts.isObjectLiteralExpression(app)) throw new Error("app in backify.config.ts must be a literal object.");
|
|
1120
1856
|
requireStaticProperties(app);
|
|
1121
1857
|
const appId = literal(app, "id");
|
|
@@ -1125,9 +1861,9 @@ function readProjectMetadata(root) {
|
|
|
1125
1861
|
...legacy,
|
|
1126
1862
|
...appId ? createConfig(appId) : {},
|
|
1127
1863
|
appId: appId ?? legacy.appId,
|
|
1128
|
-
instructionVersion: literal(
|
|
1129
|
-
agent: literal(
|
|
1130
|
-
instructionFile: literal(
|
|
1864
|
+
instructionVersion: literal(object8, "instructionVersion") ?? legacy.instructionVersion,
|
|
1865
|
+
agent: literal(object8, "agent") ?? legacy.agent,
|
|
1866
|
+
instructionFile: literal(object8, "instructionFile") ?? legacy.instructionFile
|
|
1131
1867
|
};
|
|
1132
1868
|
}
|
|
1133
1869
|
function writeProjectMetadata(root, value) {
|
|
@@ -1138,8 +1874,8 @@ function writeProjectMetadata(root, value) {
|
|
|
1138
1874
|
return;
|
|
1139
1875
|
}
|
|
1140
1876
|
const text2 = readFileSync(path, "utf8");
|
|
1141
|
-
const { source, object:
|
|
1142
|
-
const app = property(
|
|
1877
|
+
const { source, object: object8 } = configObject(text2);
|
|
1878
|
+
const app = property(object8, "app")?.initializer;
|
|
1143
1879
|
if (!app || !ts.isObjectLiteralExpression(app)) throw new Error("app in backify.config.ts must be a literal object.");
|
|
1144
1880
|
requireStaticProperties(app);
|
|
1145
1881
|
const edits = [];
|
|
@@ -1159,7 +1895,7 @@ function writeProjectMetadata(root, value) {
|
|
|
1159
1895
|
}
|
|
1160
1896
|
}
|
|
1161
1897
|
update(app, { id: value.appId });
|
|
1162
|
-
update(
|
|
1898
|
+
update(object8, { instructionVersion: value.instructionVersion, agent: value.agent, instructionFile: value.instructionFile });
|
|
1163
1899
|
let result = text2;
|
|
1164
1900
|
for (const edit of edits.sort((a, b) => b.start - a.start)) result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
|
|
1165
1901
|
writeFileSync(path, result);
|
|
@@ -1178,13 +1914,87 @@ var init_project_metadata = __esm({
|
|
|
1178
1914
|
}
|
|
1179
1915
|
});
|
|
1180
1916
|
|
|
1917
|
+
// src/human-task.ts
|
|
1918
|
+
import { hostname } from "node:os";
|
|
1919
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
1920
|
+
function portalOrigin2(input) {
|
|
1921
|
+
const url2 = new URL(input);
|
|
1922
|
+
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.");
|
|
1923
|
+
return url2.origin;
|
|
1924
|
+
}
|
|
1925
|
+
function validateHumanTask(status, kind2, applicationId) {
|
|
1926
|
+
if (!status || !uuid3.test(status.id) || status.kind !== kind2 || !states.includes(status.state) || applicationId !== void 0 && status.applicationId?.toLowerCase() !== applicationId.toLowerCase() || status.subjectId !== null && !uuid3.test(status.subjectId))
|
|
1927
|
+
throw new Error("The server returned invalid task metadata.");
|
|
1928
|
+
return status;
|
|
1929
|
+
}
|
|
1930
|
+
function humanTaskUrl(origin, status) {
|
|
1931
|
+
const url2 = new URL(status.path, origin);
|
|
1932
|
+
if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/setup/tasks/" + status.id.toLowerCase() || url2.search || url2.hash || url2.username || url2.password) throw new Error("The server returned an invalid task link.");
|
|
1933
|
+
return url2.href;
|
|
1934
|
+
}
|
|
1935
|
+
async function requestHumanTask(call2, kind2, draft) {
|
|
1936
|
+
return call2("/tasks", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ kind: kind2, draft, ...humanTaskClient }) });
|
|
1937
|
+
}
|
|
1938
|
+
async function waitForHumanTask(initial, read, options, describe2) {
|
|
1939
|
+
const timeout = options.timeoutMs ?? 6e5, now = options.now ?? Date.now, deadline = now() + timeout, origin = portalOrigin2(options.portalUrl);
|
|
1940
|
+
if (!Number.isFinite(timeout) || timeout < 1e3 || timeout > 36e5) throw new Error("Use --timeout between 1 and 3600 seconds.");
|
|
1941
|
+
let status = initial;
|
|
1942
|
+
const link = humanTaskUrl(origin, status);
|
|
1943
|
+
if (status.state !== "pending") return { status, link };
|
|
1944
|
+
if (options.signal?.aborted) return { status, link, reason: "cancelled" };
|
|
1945
|
+
options.progress?.(`Open this page to ${describe2}:
|
|
1946
|
+
${link}` + (status.matchCode ? `
|
|
1947
|
+
Check that the page shows the code ${status.matchCode}.` : ""));
|
|
1948
|
+
if (!options.noBrowser) {
|
|
1949
|
+
try {
|
|
1950
|
+
options.openBrowser(link);
|
|
1951
|
+
} catch {
|
|
1952
|
+
options.progress?.("Automatic browser launch failed. Open the page manually.");
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
if (options.noWait) return { status, link, reason: "waiting_in_browser" };
|
|
1956
|
+
options.progress?.("Waiting for you in the browser; no reply is needed in chat. The CLI continues automatically.\nCoding agents: tell the user this as a status update, not a question or input request, and keep waiting for this command to finish.");
|
|
1957
|
+
while (true) {
|
|
1958
|
+
if (status.state !== "pending") {
|
|
1959
|
+
options.progress?.(status.nextAction);
|
|
1960
|
+
return { status, link };
|
|
1961
|
+
}
|
|
1962
|
+
if (options.signal?.aborted) return { status, link, reason: "cancelled" };
|
|
1963
|
+
if (now() >= deadline) return { status, link, reason: "timed_out" };
|
|
1964
|
+
try {
|
|
1965
|
+
await (options.sleep ?? ((ms) => delay2(ms, void 0, { signal: options.signal })))(Math.min(options.intervalMs ?? 3e3, deadline - now()));
|
|
1966
|
+
} catch (error2) {
|
|
1967
|
+
if (options.signal?.aborted) return { status, link, reason: "cancelled" };
|
|
1968
|
+
throw error2;
|
|
1969
|
+
}
|
|
1970
|
+
if (options.signal?.aborted) return { status, link, reason: "cancelled" };
|
|
1971
|
+
const next = await read();
|
|
1972
|
+
if (next.id !== status.id || next.kind !== status.kind || humanTaskUrl(origin, next) !== link) throw new Error("The task changed while waiting.");
|
|
1973
|
+
status = { ...next, matchCode: status.matchCode };
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
var uuid3, states, isUuid, humanTaskClient, readHumanTask;
|
|
1977
|
+
var init_human_task = __esm({
|
|
1978
|
+
"src/human-task.ts"() {
|
|
1979
|
+
"use strict";
|
|
1980
|
+
uuid3 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
|
1981
|
+
states = ["pending", "completed", "declined", "expired", "failed"];
|
|
1982
|
+
isUuid = (value) => uuid3.test(value);
|
|
1983
|
+
humanTaskClient = { clientName: "Backify CLI", clientDevice: hostname() };
|
|
1984
|
+
readHumanTask = (call2, id) => {
|
|
1985
|
+
if (!uuid3.test(id)) throw new Error("Use a valid task ID.");
|
|
1986
|
+
return call2("/tasks/" + id.toLowerCase());
|
|
1987
|
+
};
|
|
1988
|
+
}
|
|
1989
|
+
});
|
|
1990
|
+
|
|
1181
1991
|
// package.json
|
|
1182
1992
|
var package_default;
|
|
1183
1993
|
var init_package = __esm({
|
|
1184
1994
|
"package.json"() {
|
|
1185
1995
|
package_default = {
|
|
1186
1996
|
name: "@backifydev/cli",
|
|
1187
|
-
version: "0.4.
|
|
1997
|
+
version: "0.4.2",
|
|
1188
1998
|
description: "Command-line setup and diagnostics for Backify applications",
|
|
1189
1999
|
type: "module",
|
|
1190
2000
|
bin: {
|
|
@@ -1236,9 +2046,9 @@ var init_package = __esm({
|
|
|
1236
2046
|
});
|
|
1237
2047
|
|
|
1238
2048
|
// src/cli-session.ts
|
|
1239
|
-
import { hostname, platform, release, arch } from "node:os";
|
|
2049
|
+
import { hostname as hostname2, platform, release, arch } from "node:os";
|
|
1240
2050
|
function cliDevice() {
|
|
1241
|
-
return { deviceName:
|
|
2051
|
+
return { deviceName: hostname2(), operatingSystem: platform() + " " + release(), architecture: arch(), cliVersion: package_default.version };
|
|
1242
2052
|
}
|
|
1243
2053
|
async function registerCliSession(client, applicationId, apiUrl) {
|
|
1244
2054
|
const session = await client("/apps/" + applicationId + "/developer/session", { method: "POST", body: JSON.stringify(cliDevice()) });
|
|
@@ -1848,6 +2658,9 @@ async function token(endpoint2, values, transport = fetch) {
|
|
|
1848
2658
|
const body = await response.json().catch(() => void 0);
|
|
1849
2659
|
if (response.status === 400 && body?.error === "invalid_grant") throw new McpGrantRejected("The Backify MCP connection expired or was disconnected.");
|
|
1850
2660
|
if (!response.ok || !body) throw new Error("The Backify MCP could not renew access (HTTP " + response.status + ").");
|
|
2661
|
+
return grantTokens(body);
|
|
2662
|
+
}
|
|
2663
|
+
function grantTokens(body) {
|
|
1851
2664
|
if (typeof body.access_token !== "string" || !/^bfmcp_[A-Za-z0-9_-]{43}$/.test(body.access_token) || typeof body.refresh_token !== "string" || !/^bfmcpr_[A-Za-z0-9_-]{43}$/.test(body.refresh_token) || !Number.isInteger(body.expires_in) || body.expires_in < 1 || body.expires_in > 3600 || typeof body.scope !== "string" || !body.scope.split(" ").every((scope) => scopes.has(scope)) || !body.scope.split(" ").includes("organization:read"))
|
|
1852
2665
|
throw new Error("Invalid MCP token response.");
|
|
1853
2666
|
return { access: { token: body.access_token, expires: Date.now() + body.expires_in * 1e3, scope: body.scope }, refreshToken: body.refresh_token };
|
|
@@ -1860,7 +2673,25 @@ async function refreshMcpGrant(grant, transport) {
|
|
|
1860
2673
|
const { access, refreshToken } = await token(grant.endpoint, { grant_type: "refresh_token", client_id: cliClientId, refresh_token: grant.refreshToken }, transport);
|
|
1861
2674
|
return { grant: { ...grant, refreshToken, scope: access.scope }, access };
|
|
1862
2675
|
}
|
|
1863
|
-
|
|
2676
|
+
function storedGrant(config2, endpoint2) {
|
|
2677
|
+
const grant = config2.mcp;
|
|
2678
|
+
return grant && grant.endpoint === resourceOf(endpoint2) && /^bfmcpr_[A-Za-z0-9_-]{43}$/.test(grant.refreshToken) && Array.isArray(grant.organizationIds) && grant.organizationIds.length > 0 && grant.organizationIds.every((id) => uuid6.test(id)) ? grant : void 0;
|
|
2679
|
+
}
|
|
2680
|
+
async function renewStoredGrant(file, endpoint2, transport) {
|
|
2681
|
+
for (let attempt = 0; ; attempt++) {
|
|
2682
|
+
const current = storedGrant(file.read(), endpoint2);
|
|
2683
|
+
if (!current) return void 0;
|
|
2684
|
+
try {
|
|
2685
|
+
const renewed = await refreshMcpGrant(current, transport);
|
|
2686
|
+
file.save({ ...file.read(), mcp: renewed.grant });
|
|
2687
|
+
return renewed;
|
|
2688
|
+
} catch (error2) {
|
|
2689
|
+
if (error2 instanceof McpGrantRejected && attempt === 0 && storedGrant(file.read(), endpoint2)?.refreshToken !== current.refreshToken) continue;
|
|
2690
|
+
throw error2;
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
var cliClientId, McpGrantRejected, scopes, resourceOf, uuid6;
|
|
1864
2695
|
var init_mcp_grant = __esm({
|
|
1865
2696
|
"src/mcp-grant.ts"() {
|
|
1866
2697
|
"use strict";
|
|
@@ -1869,6 +2700,7 @@ var init_mcp_grant = __esm({
|
|
|
1869
2700
|
};
|
|
1870
2701
|
scopes = /* @__PURE__ */ new Set(["organization:read", "organization:write", "deployment:manage", "billing:manage", "access:manage"]);
|
|
1871
2702
|
resourceOf = (endpoint2) => new URL(endpoint2).href.replace(/\/$/, "");
|
|
2703
|
+
uuid6 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1872
2704
|
}
|
|
1873
2705
|
});
|
|
1874
2706
|
|
|
@@ -2000,9 +2832,9 @@ function floatSafeRemainder(val, step) {
|
|
|
2000
2832
|
return 0;
|
|
2001
2833
|
return ratio - roundedRatio;
|
|
2002
2834
|
}
|
|
2003
|
-
function defineLazy(
|
|
2835
|
+
function defineLazy(object8, key, getter) {
|
|
2004
2836
|
let value = void 0;
|
|
2005
|
-
Object.defineProperty(
|
|
2837
|
+
Object.defineProperty(object8, key, {
|
|
2006
2838
|
get() {
|
|
2007
2839
|
if (value === EVALUATING) {
|
|
2008
2840
|
return void 0;
|
|
@@ -2014,7 +2846,7 @@ function defineLazy(object7, key, getter) {
|
|
|
2014
2846
|
return value;
|
|
2015
2847
|
},
|
|
2016
2848
|
set(v) {
|
|
2017
|
-
Object.defineProperty(
|
|
2849
|
+
Object.defineProperty(object8, key, {
|
|
2018
2850
|
value: v
|
|
2019
2851
|
// configurable: true,
|
|
2020
2852
|
});
|
|
@@ -2476,8 +3308,8 @@ function cleanEnum(obj) {
|
|
|
2476
3308
|
return Number.isNaN(Number.parseInt(k, 10));
|
|
2477
3309
|
}).map((el) => el[1]);
|
|
2478
3310
|
}
|
|
2479
|
-
function base64ToUint8Array(
|
|
2480
|
-
const binaryString = atob(
|
|
3311
|
+
function base64ToUint8Array(base643) {
|
|
3312
|
+
const binaryString = atob(base643);
|
|
2481
3313
|
const bytes = new Uint8Array(binaryString.length);
|
|
2482
3314
|
for (let i = 0; i < binaryString.length; i++) {
|
|
2483
3315
|
bytes[i] = binaryString.charCodeAt(i);
|
|
@@ -2492,9 +3324,9 @@ function uint8ArrayToBase64(bytes) {
|
|
|
2492
3324
|
return btoa(binaryString);
|
|
2493
3325
|
}
|
|
2494
3326
|
function base64urlToUint8Array(base64url2) {
|
|
2495
|
-
const
|
|
2496
|
-
const padding = "=".repeat((4 -
|
|
2497
|
-
return base64ToUint8Array(
|
|
3327
|
+
const base643 = base64url2.replace(/-/g, "+").replace(/_/g, "/");
|
|
3328
|
+
const padding = "=".repeat((4 - base643.length % 4) % 4);
|
|
3329
|
+
return base64ToUint8Array(base643 + padding);
|
|
2498
3330
|
}
|
|
2499
3331
|
function uint8ArrayToBase64url(bytes) {
|
|
2500
3332
|
return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
@@ -3164,7 +3996,7 @@ function datetime(args2) {
|
|
|
3164
3996
|
const timeRegex = args2.local ? `${qualified}|${timeSource({ precision: args2.precision })}` : qualified;
|
|
3165
3997
|
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
|
|
3166
3998
|
}
|
|
3167
|
-
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration,
|
|
3999
|
+
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid3, uuid7, email, _emoji, ipv4, ipv6, cidrv4, cidrv6, base642, base64url, httpProtocol, e164, dateSource, date, anyString, bigint, integer, number, boolean, _null, lowercase, uppercase;
|
|
3168
4000
|
var init_regexes = __esm({
|
|
3169
4001
|
"../../node_modules/zod/v4/core/regexes.js"() {
|
|
3170
4002
|
cuid = /^[cC][0-9a-z]{6,}$/;
|
|
@@ -3174,8 +4006,8 @@ var init_regexes = __esm({
|
|
|
3174
4006
|
ksuid = /^[A-Za-z0-9]{27}$/;
|
|
3175
4007
|
nanoid = /^[a-zA-Z0-9_-]{21}$/;
|
|
3176
4008
|
duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
|
|
3177
|
-
|
|
3178
|
-
|
|
4009
|
+
guid3 = /^([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})$/;
|
|
4010
|
+
uuid7 = (version2) => {
|
|
3179
4011
|
if (!version2)
|
|
3180
4012
|
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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
|
|
3181
4013
|
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})$`);
|
|
@@ -3186,7 +4018,7 @@ var init_regexes = __esm({
|
|
|
3186
4018
|
ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
|
|
3187
4019
|
cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
|
|
3188
4020
|
cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
|
|
3189
|
-
|
|
4021
|
+
base642 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
|
|
3190
4022
|
base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
|
|
3191
4023
|
httpProtocol = /^https?$/;
|
|
3192
4024
|
e164 = /^\+[1-9]\d{6,14}$/;
|
|
@@ -3644,9 +4476,9 @@ function parseURLObject(trimmed, def) {
|
|
|
3644
4476
|
function stripTabAndNewline(value) {
|
|
3645
4477
|
return value.replace(asciiTabOrNewline, "");
|
|
3646
4478
|
}
|
|
3647
|
-
function urlHostnameOk(url2,
|
|
3648
|
-
|
|
3649
|
-
return
|
|
4479
|
+
function urlHostnameOk(url2, hostname3) {
|
|
4480
|
+
hostname3.lastIndex = 0;
|
|
4481
|
+
return hostname3.test(url2.hostname);
|
|
3650
4482
|
}
|
|
3651
4483
|
function urlProtocolOk(url2, protocol) {
|
|
3652
4484
|
protocol.lastIndex = 0;
|
|
@@ -3688,8 +4520,8 @@ function isValidBase64(data) {
|
|
|
3688
4520
|
function isValidBase64URL(data) {
|
|
3689
4521
|
if (!base64urlCharset.test(data))
|
|
3690
4522
|
return false;
|
|
3691
|
-
const
|
|
3692
|
-
const padded =
|
|
4523
|
+
const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
|
|
4524
|
+
const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
|
|
3693
4525
|
return isValidBase64(padded);
|
|
3694
4526
|
}
|
|
3695
4527
|
function isValidJWT(token2, algorithm = null) {
|
|
@@ -4189,7 +5021,7 @@ var init_schemas = __esm({
|
|
|
4189
5021
|
$ZodString.init(inst, def);
|
|
4190
5022
|
});
|
|
4191
5023
|
$ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
|
|
4192
|
-
def.pattern ?? (def.pattern =
|
|
5024
|
+
def.pattern ?? (def.pattern = guid3);
|
|
4193
5025
|
$ZodStringFormat.init(inst, def);
|
|
4194
5026
|
});
|
|
4195
5027
|
$ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
|
|
@@ -4207,9 +5039,9 @@ var init_schemas = __esm({
|
|
|
4207
5039
|
const v = versionMap[def.version];
|
|
4208
5040
|
if (v === void 0)
|
|
4209
5041
|
throw new Error(`Invalid UUID version: "${def.version}"`);
|
|
4210
|
-
def.pattern ?? (def.pattern =
|
|
5042
|
+
def.pattern ?? (def.pattern = uuid7(v));
|
|
4211
5043
|
} else
|
|
4212
|
-
def.pattern ?? (def.pattern =
|
|
5044
|
+
def.pattern ?? (def.pattern = uuid7());
|
|
4213
5045
|
$ZodStringFormat.init(inst, def);
|
|
4214
5046
|
});
|
|
4215
5047
|
$ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
|
|
@@ -5355,8 +6187,8 @@ function isRecursive(inst, stack, resolve9) {
|
|
|
5355
6187
|
result = answer;
|
|
5356
6188
|
};
|
|
5357
6189
|
const def = inst._zod.def;
|
|
5358
|
-
const
|
|
5359
|
-
switch (
|
|
6190
|
+
const kind2 = def.type;
|
|
6191
|
+
switch (kind2) {
|
|
5360
6192
|
case "object": {
|
|
5361
6193
|
const raw = rawShape(def);
|
|
5362
6194
|
merge2(raw ? shape(raw, true) : ASSUMED);
|
|
@@ -5436,7 +6268,7 @@ function isRecursive(inst, stack, resolve9) {
|
|
|
5436
6268
|
case "custom":
|
|
5437
6269
|
break;
|
|
5438
6270
|
default: {
|
|
5439
|
-
|
|
6271
|
+
kind2;
|
|
5440
6272
|
for (const key in def) {
|
|
5441
6273
|
const desc = Object.getOwnPropertyDescriptor(def, key);
|
|
5442
6274
|
if (!desc || desc.get)
|
|
@@ -6603,8 +7435,8 @@ function foldObjects(members2) {
|
|
|
6603
7435
|
}
|
|
6604
7436
|
const properties = {};
|
|
6605
7437
|
const required2 = /* @__PURE__ */ new Set();
|
|
6606
|
-
for (const
|
|
6607
|
-
for (const key in
|
|
7438
|
+
for (const object8 of objects) {
|
|
7439
|
+
for (const key in object8.properties) {
|
|
6608
7440
|
if (Object.prototype.hasOwnProperty.call(properties, key))
|
|
6609
7441
|
continue;
|
|
6610
7442
|
const parts = [];
|
|
@@ -6618,18 +7450,18 @@ function foldObjects(members2) {
|
|
|
6618
7450
|
const merged = parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts };
|
|
6619
7451
|
assignProp(properties, key, merged);
|
|
6620
7452
|
}
|
|
6621
|
-
for (const key of
|
|
7453
|
+
for (const key of object8.required ?? [])
|
|
6622
7454
|
required2.add(key);
|
|
6623
7455
|
}
|
|
6624
7456
|
const folded = { type: "object", properties };
|
|
6625
7457
|
if (required2.size)
|
|
6626
7458
|
folded.required = [...required2];
|
|
6627
|
-
if (objects.every((
|
|
7459
|
+
if (objects.every((object8) => object8.additionalProperties === false)) {
|
|
6628
7460
|
folded.additionalProperties = false;
|
|
6629
7461
|
} else {
|
|
6630
7462
|
const constraints = [];
|
|
6631
|
-
for (const
|
|
6632
|
-
const constraint = undeclaredConstraint(
|
|
7463
|
+
for (const object8 of objects) {
|
|
7464
|
+
const constraint = undeclaredConstraint(object8);
|
|
6633
7465
|
if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint)))
|
|
6634
7466
|
constraints.push(constraint);
|
|
6635
7467
|
}
|
|
@@ -7091,7 +7923,7 @@ var init_json_schema_processors = __esm({
|
|
|
7091
7923
|
// do not set
|
|
7092
7924
|
};
|
|
7093
7925
|
exactPatterns = /* @__PURE__ */ new Map([
|
|
7094
|
-
[base64Charset,
|
|
7926
|
+
[base64Charset, base642],
|
|
7095
7927
|
[base64urlCharset, base64url]
|
|
7096
7928
|
]);
|
|
7097
7929
|
exactPattern = (p) => exactPatterns.get(p) ?? p;
|
|
@@ -7724,7 +8556,7 @@ function never(params) {
|
|
|
7724
8556
|
function array(element, params) {
|
|
7725
8557
|
return _array(ZodArray, element, params);
|
|
7726
8558
|
}
|
|
7727
|
-
function
|
|
8559
|
+
function object6(shape, params) {
|
|
7728
8560
|
const def = {
|
|
7729
8561
|
type: "object",
|
|
7730
8562
|
shape: shape ?? {},
|
|
@@ -8856,10 +9688,10 @@ var init_types = __esm({
|
|
|
8856
9688
|
*/
|
|
8857
9689
|
pollInterval: number2().optional()
|
|
8858
9690
|
});
|
|
8859
|
-
TaskMetadataSchema =
|
|
9691
|
+
TaskMetadataSchema = object6({
|
|
8860
9692
|
ttl: number2().optional()
|
|
8861
9693
|
});
|
|
8862
|
-
RelatedTaskMetadataSchema =
|
|
9694
|
+
RelatedTaskMetadataSchema = object6({
|
|
8863
9695
|
taskId: string2()
|
|
8864
9696
|
});
|
|
8865
9697
|
RequestMetaSchema = looseObject({
|
|
@@ -8872,7 +9704,7 @@ var init_types = __esm({
|
|
|
8872
9704
|
*/
|
|
8873
9705
|
[RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
|
|
8874
9706
|
});
|
|
8875
|
-
BaseRequestParamsSchema =
|
|
9707
|
+
BaseRequestParamsSchema = object6({
|
|
8876
9708
|
/**
|
|
8877
9709
|
* See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
|
|
8878
9710
|
*/
|
|
@@ -8890,18 +9722,18 @@ var init_types = __esm({
|
|
|
8890
9722
|
task: TaskMetadataSchema.optional()
|
|
8891
9723
|
});
|
|
8892
9724
|
isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
|
|
8893
|
-
RequestSchema =
|
|
9725
|
+
RequestSchema = object6({
|
|
8894
9726
|
method: string2(),
|
|
8895
9727
|
params: BaseRequestParamsSchema.loose().optional()
|
|
8896
9728
|
});
|
|
8897
|
-
NotificationsParamsSchema =
|
|
9729
|
+
NotificationsParamsSchema = object6({
|
|
8898
9730
|
/**
|
|
8899
9731
|
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
8900
9732
|
* for notes on _meta usage.
|
|
8901
9733
|
*/
|
|
8902
9734
|
_meta: RequestMetaSchema.optional()
|
|
8903
9735
|
});
|
|
8904
|
-
NotificationSchema =
|
|
9736
|
+
NotificationSchema = object6({
|
|
8905
9737
|
method: string2(),
|
|
8906
9738
|
params: NotificationsParamsSchema.loose().optional()
|
|
8907
9739
|
});
|
|
@@ -8913,18 +9745,18 @@ var init_types = __esm({
|
|
|
8913
9745
|
_meta: RequestMetaSchema.optional()
|
|
8914
9746
|
});
|
|
8915
9747
|
RequestIdSchema = union([string2(), number2().int()]);
|
|
8916
|
-
JSONRPCRequestSchema =
|
|
9748
|
+
JSONRPCRequestSchema = object6({
|
|
8917
9749
|
jsonrpc: literal2(JSONRPC_VERSION),
|
|
8918
9750
|
id: RequestIdSchema,
|
|
8919
9751
|
...RequestSchema.shape
|
|
8920
9752
|
}).strict();
|
|
8921
9753
|
isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
|
|
8922
|
-
JSONRPCNotificationSchema =
|
|
9754
|
+
JSONRPCNotificationSchema = object6({
|
|
8923
9755
|
jsonrpc: literal2(JSONRPC_VERSION),
|
|
8924
9756
|
...NotificationSchema.shape
|
|
8925
9757
|
}).strict();
|
|
8926
9758
|
isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
|
|
8927
|
-
JSONRPCResultResponseSchema =
|
|
9759
|
+
JSONRPCResultResponseSchema = object6({
|
|
8928
9760
|
jsonrpc: literal2(JSONRPC_VERSION),
|
|
8929
9761
|
id: RequestIdSchema,
|
|
8930
9762
|
result: ResultSchema
|
|
@@ -8940,10 +9772,10 @@ var init_types = __esm({
|
|
|
8940
9772
|
ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
|
|
8941
9773
|
ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
|
|
8942
9774
|
})(ErrorCode || (ErrorCode = {}));
|
|
8943
|
-
JSONRPCErrorResponseSchema =
|
|
9775
|
+
JSONRPCErrorResponseSchema = object6({
|
|
8944
9776
|
jsonrpc: literal2(JSONRPC_VERSION),
|
|
8945
9777
|
id: RequestIdSchema.optional(),
|
|
8946
|
-
error:
|
|
9778
|
+
error: object6({
|
|
8947
9779
|
/**
|
|
8948
9780
|
* The error type that occurred.
|
|
8949
9781
|
*/
|
|
@@ -8983,7 +9815,7 @@ var init_types = __esm({
|
|
|
8983
9815
|
method: literal2("notifications/cancelled"),
|
|
8984
9816
|
params: CancelledNotificationParamsSchema
|
|
8985
9817
|
});
|
|
8986
|
-
IconSchema =
|
|
9818
|
+
IconSchema = object6({
|
|
8987
9819
|
/**
|
|
8988
9820
|
* URL or data URI for the icon.
|
|
8989
9821
|
*/
|
|
@@ -9008,7 +9840,7 @@ var init_types = __esm({
|
|
|
9008
9840
|
*/
|
|
9009
9841
|
theme: _enum(["light", "dark"]).optional()
|
|
9010
9842
|
});
|
|
9011
|
-
IconsSchema =
|
|
9843
|
+
IconsSchema = object6({
|
|
9012
9844
|
/**
|
|
9013
9845
|
* Optional set of sized icons that the client can display in a user interface.
|
|
9014
9846
|
*
|
|
@@ -9022,7 +9854,7 @@ var init_types = __esm({
|
|
|
9022
9854
|
*/
|
|
9023
9855
|
icons: array(IconSchema).optional()
|
|
9024
9856
|
});
|
|
9025
|
-
BaseMetadataSchema =
|
|
9857
|
+
BaseMetadataSchema = object6({
|
|
9026
9858
|
/** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
|
|
9027
9859
|
name: string2(),
|
|
9028
9860
|
/**
|
|
@@ -9052,7 +9884,7 @@ var init_types = __esm({
|
|
|
9052
9884
|
*/
|
|
9053
9885
|
description: string2().optional()
|
|
9054
9886
|
});
|
|
9055
|
-
FormElicitationCapabilitySchema = intersection(
|
|
9887
|
+
FormElicitationCapabilitySchema = intersection(object6({
|
|
9056
9888
|
applyDefaults: boolean2().optional()
|
|
9057
9889
|
}), record(string2(), unknown()));
|
|
9058
9890
|
ElicitationCapabilitySchema = preprocess((value) => {
|
|
@@ -9062,7 +9894,7 @@ var init_types = __esm({
|
|
|
9062
9894
|
}
|
|
9063
9895
|
}
|
|
9064
9896
|
return value;
|
|
9065
|
-
}, intersection(
|
|
9897
|
+
}, intersection(object6({
|
|
9066
9898
|
form: FormElicitationCapabilitySchema.optional(),
|
|
9067
9899
|
url: AssertObjectSchema.optional()
|
|
9068
9900
|
}), record(string2(), unknown()).optional()));
|
|
@@ -9114,7 +9946,7 @@ var init_types = __esm({
|
|
|
9114
9946
|
}).optional()
|
|
9115
9947
|
}).optional()
|
|
9116
9948
|
});
|
|
9117
|
-
ClientCapabilitiesSchema =
|
|
9949
|
+
ClientCapabilitiesSchema = object6({
|
|
9118
9950
|
/**
|
|
9119
9951
|
* Experimental, non-standard capabilities that the client supports.
|
|
9120
9952
|
*/
|
|
@@ -9122,7 +9954,7 @@ var init_types = __esm({
|
|
|
9122
9954
|
/**
|
|
9123
9955
|
* Present if the client supports sampling from an LLM.
|
|
9124
9956
|
*/
|
|
9125
|
-
sampling:
|
|
9957
|
+
sampling: object6({
|
|
9126
9958
|
/**
|
|
9127
9959
|
* Present if the client supports context inclusion via includeContext parameter.
|
|
9128
9960
|
* If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
|
|
@@ -9140,7 +9972,7 @@ var init_types = __esm({
|
|
|
9140
9972
|
/**
|
|
9141
9973
|
* Present if the client supports listing roots.
|
|
9142
9974
|
*/
|
|
9143
|
-
roots:
|
|
9975
|
+
roots: object6({
|
|
9144
9976
|
/**
|
|
9145
9977
|
* Whether the client supports issuing notifications for changes to the roots list.
|
|
9146
9978
|
*/
|
|
@@ -9167,7 +9999,7 @@ var init_types = __esm({
|
|
|
9167
9999
|
method: literal2("initialize"),
|
|
9168
10000
|
params: InitializeRequestParamsSchema
|
|
9169
10001
|
});
|
|
9170
|
-
ServerCapabilitiesSchema =
|
|
10002
|
+
ServerCapabilitiesSchema = object6({
|
|
9171
10003
|
/**
|
|
9172
10004
|
* Experimental, non-standard capabilities that the server supports.
|
|
9173
10005
|
*/
|
|
@@ -9183,7 +10015,7 @@ var init_types = __esm({
|
|
|
9183
10015
|
/**
|
|
9184
10016
|
* Present if the server offers any prompt templates.
|
|
9185
10017
|
*/
|
|
9186
|
-
prompts:
|
|
10018
|
+
prompts: object6({
|
|
9187
10019
|
/**
|
|
9188
10020
|
* Whether this server supports issuing notifications for changes to the prompt list.
|
|
9189
10021
|
*/
|
|
@@ -9192,7 +10024,7 @@ var init_types = __esm({
|
|
|
9192
10024
|
/**
|
|
9193
10025
|
* Present if the server offers any resources to read.
|
|
9194
10026
|
*/
|
|
9195
|
-
resources:
|
|
10027
|
+
resources: object6({
|
|
9196
10028
|
/**
|
|
9197
10029
|
* Whether this server supports clients subscribing to resource updates.
|
|
9198
10030
|
*/
|
|
@@ -9205,7 +10037,7 @@ var init_types = __esm({
|
|
|
9205
10037
|
/**
|
|
9206
10038
|
* Present if the server offers any tools to call.
|
|
9207
10039
|
*/
|
|
9208
|
-
tools:
|
|
10040
|
+
tools: object6({
|
|
9209
10041
|
/**
|
|
9210
10042
|
* Whether this server supports issuing notifications for changes to the tool list.
|
|
9211
10043
|
*/
|
|
@@ -9243,7 +10075,7 @@ var init_types = __esm({
|
|
|
9243
10075
|
method: literal2("ping"),
|
|
9244
10076
|
params: BaseRequestParamsSchema.optional()
|
|
9245
10077
|
});
|
|
9246
|
-
ProgressSchema =
|
|
10078
|
+
ProgressSchema = object6({
|
|
9247
10079
|
/**
|
|
9248
10080
|
* The progress thus far. This should increase every time progress is made, even if the total is unknown.
|
|
9249
10081
|
*/
|
|
@@ -9257,7 +10089,7 @@ var init_types = __esm({
|
|
|
9257
10089
|
*/
|
|
9258
10090
|
message: optional(string2())
|
|
9259
10091
|
});
|
|
9260
|
-
ProgressNotificationParamsSchema =
|
|
10092
|
+
ProgressNotificationParamsSchema = object6({
|
|
9261
10093
|
...NotificationsParamsSchema.shape,
|
|
9262
10094
|
...ProgressSchema.shape,
|
|
9263
10095
|
/**
|
|
@@ -9287,7 +10119,7 @@ var init_types = __esm({
|
|
|
9287
10119
|
nextCursor: CursorSchema.optional()
|
|
9288
10120
|
});
|
|
9289
10121
|
TaskStatusSchema = _enum(["working", "input_required", "completed", "failed", "cancelled"]);
|
|
9290
|
-
TaskSchema =
|
|
10122
|
+
TaskSchema = object6({
|
|
9291
10123
|
taskId: string2(),
|
|
9292
10124
|
status: TaskStatusSchema,
|
|
9293
10125
|
/**
|
|
@@ -9344,7 +10176,7 @@ var init_types = __esm({
|
|
|
9344
10176
|
})
|
|
9345
10177
|
});
|
|
9346
10178
|
CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
|
|
9347
|
-
ResourceContentsSchema =
|
|
10179
|
+
ResourceContentsSchema = object6({
|
|
9348
10180
|
/**
|
|
9349
10181
|
* The URI of this resource.
|
|
9350
10182
|
*/
|
|
@@ -9380,7 +10212,7 @@ var init_types = __esm({
|
|
|
9380
10212
|
blob: Base64Schema
|
|
9381
10213
|
});
|
|
9382
10214
|
RoleSchema = _enum(["user", "assistant"]);
|
|
9383
|
-
AnnotationsSchema =
|
|
10215
|
+
AnnotationsSchema = object6({
|
|
9384
10216
|
/**
|
|
9385
10217
|
* Intended audience(s) for the resource.
|
|
9386
10218
|
*/
|
|
@@ -9394,7 +10226,7 @@ var init_types = __esm({
|
|
|
9394
10226
|
*/
|
|
9395
10227
|
lastModified: iso_exports2.datetime({ offset: true }).optional()
|
|
9396
10228
|
});
|
|
9397
|
-
ResourceSchema =
|
|
10229
|
+
ResourceSchema = object6({
|
|
9398
10230
|
...BaseMetadataSchema.shape,
|
|
9399
10231
|
...IconsSchema.shape,
|
|
9400
10232
|
/**
|
|
@@ -9427,7 +10259,7 @@ var init_types = __esm({
|
|
|
9427
10259
|
*/
|
|
9428
10260
|
_meta: optional(looseObject({}))
|
|
9429
10261
|
});
|
|
9430
|
-
ResourceTemplateSchema =
|
|
10262
|
+
ResourceTemplateSchema = object6({
|
|
9431
10263
|
...BaseMetadataSchema.shape,
|
|
9432
10264
|
...IconsSchema.shape,
|
|
9433
10265
|
/**
|
|
@@ -9506,7 +10338,7 @@ var init_types = __esm({
|
|
|
9506
10338
|
method: literal2("notifications/resources/updated"),
|
|
9507
10339
|
params: ResourceUpdatedNotificationParamsSchema
|
|
9508
10340
|
});
|
|
9509
|
-
PromptArgumentSchema =
|
|
10341
|
+
PromptArgumentSchema = object6({
|
|
9510
10342
|
/**
|
|
9511
10343
|
* The name of the argument.
|
|
9512
10344
|
*/
|
|
@@ -9520,7 +10352,7 @@ var init_types = __esm({
|
|
|
9520
10352
|
*/
|
|
9521
10353
|
required: optional(boolean2())
|
|
9522
10354
|
});
|
|
9523
|
-
PromptSchema =
|
|
10355
|
+
PromptSchema = object6({
|
|
9524
10356
|
...BaseMetadataSchema.shape,
|
|
9525
10357
|
...IconsSchema.shape,
|
|
9526
10358
|
/**
|
|
@@ -9557,7 +10389,7 @@ var init_types = __esm({
|
|
|
9557
10389
|
method: literal2("prompts/get"),
|
|
9558
10390
|
params: GetPromptRequestParamsSchema
|
|
9559
10391
|
});
|
|
9560
|
-
TextContentSchema =
|
|
10392
|
+
TextContentSchema = object6({
|
|
9561
10393
|
type: literal2("text"),
|
|
9562
10394
|
/**
|
|
9563
10395
|
* The text content of the message.
|
|
@@ -9573,7 +10405,7 @@ var init_types = __esm({
|
|
|
9573
10405
|
*/
|
|
9574
10406
|
_meta: record(string2(), unknown()).optional()
|
|
9575
10407
|
});
|
|
9576
|
-
ImageContentSchema =
|
|
10408
|
+
ImageContentSchema = object6({
|
|
9577
10409
|
type: literal2("image"),
|
|
9578
10410
|
/**
|
|
9579
10411
|
* The base64-encoded image data.
|
|
@@ -9593,7 +10425,7 @@ var init_types = __esm({
|
|
|
9593
10425
|
*/
|
|
9594
10426
|
_meta: record(string2(), unknown()).optional()
|
|
9595
10427
|
});
|
|
9596
|
-
AudioContentSchema =
|
|
10428
|
+
AudioContentSchema = object6({
|
|
9597
10429
|
type: literal2("audio"),
|
|
9598
10430
|
/**
|
|
9599
10431
|
* The base64-encoded audio data.
|
|
@@ -9613,7 +10445,7 @@ var init_types = __esm({
|
|
|
9613
10445
|
*/
|
|
9614
10446
|
_meta: record(string2(), unknown()).optional()
|
|
9615
10447
|
});
|
|
9616
|
-
ToolUseContentSchema =
|
|
10448
|
+
ToolUseContentSchema = object6({
|
|
9617
10449
|
type: literal2("tool_use"),
|
|
9618
10450
|
/**
|
|
9619
10451
|
* The name of the tool to invoke.
|
|
@@ -9636,7 +10468,7 @@ var init_types = __esm({
|
|
|
9636
10468
|
*/
|
|
9637
10469
|
_meta: record(string2(), unknown()).optional()
|
|
9638
10470
|
});
|
|
9639
|
-
EmbeddedResourceSchema =
|
|
10471
|
+
EmbeddedResourceSchema = object6({
|
|
9640
10472
|
type: literal2("resource"),
|
|
9641
10473
|
resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
|
|
9642
10474
|
/**
|
|
@@ -9659,7 +10491,7 @@ var init_types = __esm({
|
|
|
9659
10491
|
ResourceLinkSchema,
|
|
9660
10492
|
EmbeddedResourceSchema
|
|
9661
10493
|
]);
|
|
9662
|
-
PromptMessageSchema =
|
|
10494
|
+
PromptMessageSchema = object6({
|
|
9663
10495
|
role: RoleSchema,
|
|
9664
10496
|
content: ContentBlockSchema
|
|
9665
10497
|
});
|
|
@@ -9674,7 +10506,7 @@ var init_types = __esm({
|
|
|
9674
10506
|
method: literal2("notifications/prompts/list_changed"),
|
|
9675
10507
|
params: NotificationsParamsSchema.optional()
|
|
9676
10508
|
});
|
|
9677
|
-
ToolAnnotationsSchema =
|
|
10509
|
+
ToolAnnotationsSchema = object6({
|
|
9678
10510
|
/**
|
|
9679
10511
|
* A human-readable title for the tool.
|
|
9680
10512
|
*/
|
|
@@ -9713,7 +10545,7 @@ var init_types = __esm({
|
|
|
9713
10545
|
*/
|
|
9714
10546
|
openWorldHint: boolean2().optional()
|
|
9715
10547
|
});
|
|
9716
|
-
ToolExecutionSchema =
|
|
10548
|
+
ToolExecutionSchema = object6({
|
|
9717
10549
|
/**
|
|
9718
10550
|
* Indicates the tool's preference for task-augmented execution.
|
|
9719
10551
|
* - "required": Clients MUST invoke the tool as a task
|
|
@@ -9724,7 +10556,7 @@ var init_types = __esm({
|
|
|
9724
10556
|
*/
|
|
9725
10557
|
taskSupport: _enum(["required", "optional", "forbidden"]).optional()
|
|
9726
10558
|
});
|
|
9727
|
-
ToolSchema =
|
|
10559
|
+
ToolSchema = object6({
|
|
9728
10560
|
...BaseMetadataSchema.shape,
|
|
9729
10561
|
...IconsSchema.shape,
|
|
9730
10562
|
/**
|
|
@@ -9735,7 +10567,7 @@ var init_types = __esm({
|
|
|
9735
10567
|
* A JSON Schema 2020-12 object defining the expected parameters for the tool.
|
|
9736
10568
|
* Must have type: 'object' at the root level per MCP spec.
|
|
9737
10569
|
*/
|
|
9738
|
-
inputSchema:
|
|
10570
|
+
inputSchema: object6({
|
|
9739
10571
|
type: literal2("object"),
|
|
9740
10572
|
properties: record(string2(), AssertObjectSchema).optional(),
|
|
9741
10573
|
required: array(string2()).optional()
|
|
@@ -9745,7 +10577,7 @@ var init_types = __esm({
|
|
|
9745
10577
|
* returned in the structuredContent field of a CallToolResult.
|
|
9746
10578
|
* Must have type: 'object' at the root level per MCP spec.
|
|
9747
10579
|
*/
|
|
9748
|
-
outputSchema:
|
|
10580
|
+
outputSchema: object6({
|
|
9749
10581
|
type: literal2("object"),
|
|
9750
10582
|
properties: record(string2(), AssertObjectSchema).optional(),
|
|
9751
10583
|
required: array(string2()).optional()
|
|
@@ -9821,7 +10653,7 @@ var init_types = __esm({
|
|
|
9821
10653
|
method: literal2("notifications/tools/list_changed"),
|
|
9822
10654
|
params: NotificationsParamsSchema.optional()
|
|
9823
10655
|
});
|
|
9824
|
-
ListChangedOptionsBaseSchema =
|
|
10656
|
+
ListChangedOptionsBaseSchema = object6({
|
|
9825
10657
|
/**
|
|
9826
10658
|
* If true, the list will be refreshed automatically when a list changed notification is received.
|
|
9827
10659
|
* The callback will be called with the updated list.
|
|
@@ -9870,13 +10702,13 @@ var init_types = __esm({
|
|
|
9870
10702
|
method: literal2("notifications/message"),
|
|
9871
10703
|
params: LoggingMessageNotificationParamsSchema
|
|
9872
10704
|
});
|
|
9873
|
-
ModelHintSchema =
|
|
10705
|
+
ModelHintSchema = object6({
|
|
9874
10706
|
/**
|
|
9875
10707
|
* A hint for a model name.
|
|
9876
10708
|
*/
|
|
9877
10709
|
name: string2().optional()
|
|
9878
10710
|
});
|
|
9879
|
-
ModelPreferencesSchema =
|
|
10711
|
+
ModelPreferencesSchema = object6({
|
|
9880
10712
|
/**
|
|
9881
10713
|
* Optional hints to use for model selection.
|
|
9882
10714
|
*/
|
|
@@ -9894,7 +10726,7 @@ var init_types = __esm({
|
|
|
9894
10726
|
*/
|
|
9895
10727
|
intelligencePriority: number2().min(0).max(1).optional()
|
|
9896
10728
|
});
|
|
9897
|
-
ToolChoiceSchema =
|
|
10729
|
+
ToolChoiceSchema = object6({
|
|
9898
10730
|
/**
|
|
9899
10731
|
* Controls when tools are used:
|
|
9900
10732
|
* - "auto": Model decides whether to use tools (default)
|
|
@@ -9903,11 +10735,11 @@ var init_types = __esm({
|
|
|
9903
10735
|
*/
|
|
9904
10736
|
mode: _enum(["auto", "required", "none"]).optional()
|
|
9905
10737
|
});
|
|
9906
|
-
ToolResultContentSchema =
|
|
10738
|
+
ToolResultContentSchema = object6({
|
|
9907
10739
|
type: literal2("tool_result"),
|
|
9908
10740
|
toolUseId: string2().describe("The unique identifier for the corresponding tool call."),
|
|
9909
10741
|
content: array(ContentBlockSchema).default([]),
|
|
9910
|
-
structuredContent:
|
|
10742
|
+
structuredContent: object6({}).loose().optional(),
|
|
9911
10743
|
isError: boolean2().optional(),
|
|
9912
10744
|
/**
|
|
9913
10745
|
* See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
|
|
@@ -9923,7 +10755,7 @@ var init_types = __esm({
|
|
|
9923
10755
|
ToolUseContentSchema,
|
|
9924
10756
|
ToolResultContentSchema
|
|
9925
10757
|
]);
|
|
9926
|
-
SamplingMessageSchema =
|
|
10758
|
+
SamplingMessageSchema = object6({
|
|
9927
10759
|
role: RoleSchema,
|
|
9928
10760
|
content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
|
|
9929
10761
|
/**
|
|
@@ -10023,13 +10855,13 @@ var init_types = __esm({
|
|
|
10023
10855
|
*/
|
|
10024
10856
|
content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
|
|
10025
10857
|
});
|
|
10026
|
-
BooleanSchemaSchema =
|
|
10858
|
+
BooleanSchemaSchema = object6({
|
|
10027
10859
|
type: literal2("boolean"),
|
|
10028
10860
|
title: string2().optional(),
|
|
10029
10861
|
description: string2().optional(),
|
|
10030
10862
|
default: boolean2().optional()
|
|
10031
10863
|
});
|
|
10032
|
-
StringSchemaSchema =
|
|
10864
|
+
StringSchemaSchema = object6({
|
|
10033
10865
|
type: literal2("string"),
|
|
10034
10866
|
title: string2().optional(),
|
|
10035
10867
|
description: string2().optional(),
|
|
@@ -10038,7 +10870,7 @@ var init_types = __esm({
|
|
|
10038
10870
|
format: _enum(["email", "uri", "date", "date-time"]).optional(),
|
|
10039
10871
|
default: string2().optional()
|
|
10040
10872
|
});
|
|
10041
|
-
NumberSchemaSchema =
|
|
10873
|
+
NumberSchemaSchema = object6({
|
|
10042
10874
|
type: _enum(["number", "integer"]),
|
|
10043
10875
|
title: string2().optional(),
|
|
10044
10876
|
description: string2().optional(),
|
|
@@ -10046,24 +10878,24 @@ var init_types = __esm({
|
|
|
10046
10878
|
maximum: number2().optional(),
|
|
10047
10879
|
default: number2().optional()
|
|
10048
10880
|
});
|
|
10049
|
-
UntitledSingleSelectEnumSchemaSchema =
|
|
10881
|
+
UntitledSingleSelectEnumSchemaSchema = object6({
|
|
10050
10882
|
type: literal2("string"),
|
|
10051
10883
|
title: string2().optional(),
|
|
10052
10884
|
description: string2().optional(),
|
|
10053
10885
|
enum: array(string2()),
|
|
10054
10886
|
default: string2().optional()
|
|
10055
10887
|
});
|
|
10056
|
-
TitledSingleSelectEnumSchemaSchema =
|
|
10888
|
+
TitledSingleSelectEnumSchemaSchema = object6({
|
|
10057
10889
|
type: literal2("string"),
|
|
10058
10890
|
title: string2().optional(),
|
|
10059
10891
|
description: string2().optional(),
|
|
10060
|
-
oneOf: array(
|
|
10892
|
+
oneOf: array(object6({
|
|
10061
10893
|
const: string2(),
|
|
10062
10894
|
title: string2()
|
|
10063
10895
|
})),
|
|
10064
10896
|
default: string2().optional()
|
|
10065
10897
|
});
|
|
10066
|
-
LegacyTitledEnumSchemaSchema =
|
|
10898
|
+
LegacyTitledEnumSchemaSchema = object6({
|
|
10067
10899
|
type: literal2("string"),
|
|
10068
10900
|
title: string2().optional(),
|
|
10069
10901
|
description: string2().optional(),
|
|
@@ -10072,26 +10904,26 @@ var init_types = __esm({
|
|
|
10072
10904
|
default: string2().optional()
|
|
10073
10905
|
});
|
|
10074
10906
|
SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
|
|
10075
|
-
UntitledMultiSelectEnumSchemaSchema =
|
|
10907
|
+
UntitledMultiSelectEnumSchemaSchema = object6({
|
|
10076
10908
|
type: literal2("array"),
|
|
10077
10909
|
title: string2().optional(),
|
|
10078
10910
|
description: string2().optional(),
|
|
10079
10911
|
minItems: number2().optional(),
|
|
10080
10912
|
maxItems: number2().optional(),
|
|
10081
|
-
items:
|
|
10913
|
+
items: object6({
|
|
10082
10914
|
type: literal2("string"),
|
|
10083
10915
|
enum: array(string2())
|
|
10084
10916
|
}),
|
|
10085
10917
|
default: array(string2()).optional()
|
|
10086
10918
|
});
|
|
10087
|
-
TitledMultiSelectEnumSchemaSchema =
|
|
10919
|
+
TitledMultiSelectEnumSchemaSchema = object6({
|
|
10088
10920
|
type: literal2("array"),
|
|
10089
10921
|
title: string2().optional(),
|
|
10090
10922
|
description: string2().optional(),
|
|
10091
10923
|
minItems: number2().optional(),
|
|
10092
10924
|
maxItems: number2().optional(),
|
|
10093
|
-
items:
|
|
10094
|
-
anyOf: array(
|
|
10925
|
+
items: object6({
|
|
10926
|
+
anyOf: array(object6({
|
|
10095
10927
|
const: string2(),
|
|
10096
10928
|
title: string2()
|
|
10097
10929
|
}))
|
|
@@ -10116,7 +10948,7 @@ var init_types = __esm({
|
|
|
10116
10948
|
* A restricted subset of JSON Schema.
|
|
10117
10949
|
* Only top-level properties are allowed, without nesting.
|
|
10118
10950
|
*/
|
|
10119
|
-
requestedSchema:
|
|
10951
|
+
requestedSchema: object6({
|
|
10120
10952
|
type: literal2("object"),
|
|
10121
10953
|
properties: record(string2(), PrimitiveSchemaDefinitionSchema),
|
|
10122
10954
|
required: array(string2()).optional()
|
|
@@ -10172,14 +11004,14 @@ var init_types = __esm({
|
|
|
10172
11004
|
*/
|
|
10173
11005
|
content: preprocess((val) => val === null ? void 0 : val, record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional())
|
|
10174
11006
|
});
|
|
10175
|
-
ResourceTemplateReferenceSchema =
|
|
11007
|
+
ResourceTemplateReferenceSchema = object6({
|
|
10176
11008
|
type: literal2("ref/resource"),
|
|
10177
11009
|
/**
|
|
10178
11010
|
* The URI or URI template of the resource.
|
|
10179
11011
|
*/
|
|
10180
11012
|
uri: string2()
|
|
10181
11013
|
});
|
|
10182
|
-
PromptReferenceSchema =
|
|
11014
|
+
PromptReferenceSchema = object6({
|
|
10183
11015
|
type: literal2("ref/prompt"),
|
|
10184
11016
|
/**
|
|
10185
11017
|
* The name of the prompt or prompt template
|
|
@@ -10191,7 +11023,7 @@ var init_types = __esm({
|
|
|
10191
11023
|
/**
|
|
10192
11024
|
* The argument's information
|
|
10193
11025
|
*/
|
|
10194
|
-
argument:
|
|
11026
|
+
argument: object6({
|
|
10195
11027
|
/**
|
|
10196
11028
|
* The name of the argument
|
|
10197
11029
|
*/
|
|
@@ -10201,7 +11033,7 @@ var init_types = __esm({
|
|
|
10201
11033
|
*/
|
|
10202
11034
|
value: string2()
|
|
10203
11035
|
}),
|
|
10204
|
-
context:
|
|
11036
|
+
context: object6({
|
|
10205
11037
|
/**
|
|
10206
11038
|
* Previously-resolved variables in a URI template or prompt.
|
|
10207
11039
|
*/
|
|
@@ -10228,7 +11060,7 @@ var init_types = __esm({
|
|
|
10228
11060
|
hasMore: optional(boolean2())
|
|
10229
11061
|
})
|
|
10230
11062
|
});
|
|
10231
|
-
RootSchema =
|
|
11063
|
+
RootSchema = object6({
|
|
10232
11064
|
/**
|
|
10233
11065
|
* The URI identifying the root. This *must* start with file:// for now.
|
|
10234
11066
|
*/
|
|
@@ -12969,7 +13801,7 @@ var require_errors = __commonJS({
|
|
|
12969
13801
|
message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`
|
|
12970
13802
|
};
|
|
12971
13803
|
exports.keyword$DataError = {
|
|
12972
|
-
message: ({ keyword, schemaType }) =>
|
|
13804
|
+
message: ({ keyword, schemaType: schemaType2 }) => schemaType2 ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType2} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`
|
|
12973
13805
|
};
|
|
12974
13806
|
function reportError(cxt, error2 = exports.keywordError, errorPaths, overrideAllErrors) {
|
|
12975
13807
|
const { it } = cxt;
|
|
@@ -13628,8 +14460,8 @@ var require_keyword = __commonJS({
|
|
|
13628
14460
|
throw new Error(`keyword "${keyword}" failed to compile`);
|
|
13629
14461
|
return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
|
|
13630
14462
|
}
|
|
13631
|
-
function validSchemaType(schema,
|
|
13632
|
-
return !
|
|
14463
|
+
function validSchemaType(schema, schemaType2, allowUndefined = false) {
|
|
14464
|
+
return !schemaType2.length || schemaType2.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
|
|
13633
14465
|
}
|
|
13634
14466
|
exports.validSchemaType = validSchemaType;
|
|
13635
14467
|
function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
|
|
@@ -14407,11 +15239,11 @@ var require_validate = __commonJS({
|
|
|
14407
15239
|
check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
|
|
14408
15240
|
if (!this.$data)
|
|
14409
15241
|
return;
|
|
14410
|
-
const { gen, schemaCode, schemaType, def } = this;
|
|
15242
|
+
const { gen, schemaCode, schemaType: schemaType2, def } = this;
|
|
14411
15243
|
gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
|
|
14412
15244
|
if (valid !== codegen_1.nil)
|
|
14413
15245
|
gen.assign(valid, true);
|
|
14414
|
-
if (
|
|
15246
|
+
if (schemaType2.length || def.validateSchema) {
|
|
14415
15247
|
gen.elseIf(this.invalid$data());
|
|
14416
15248
|
this.$dataError();
|
|
14417
15249
|
if (valid !== codegen_1.nil)
|
|
@@ -14420,13 +15252,13 @@ var require_validate = __commonJS({
|
|
|
14420
15252
|
gen.else();
|
|
14421
15253
|
}
|
|
14422
15254
|
invalid$data() {
|
|
14423
|
-
const { gen, schemaCode, schemaType, def, it } = this;
|
|
15255
|
+
const { gen, schemaCode, schemaType: schemaType2, def, it } = this;
|
|
14424
15256
|
return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
|
|
14425
15257
|
function wrong$DataType() {
|
|
14426
|
-
if (
|
|
15258
|
+
if (schemaType2.length) {
|
|
14427
15259
|
if (!(schemaCode instanceof codegen_1.Name))
|
|
14428
15260
|
throw new Error("ajv implementation error");
|
|
14429
|
-
const st = Array.isArray(
|
|
15261
|
+
const st = Array.isArray(schemaType2) ? schemaType2 : [schemaType2];
|
|
14430
15262
|
return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
|
|
14431
15263
|
}
|
|
14432
15264
|
return codegen_1.nil;
|
|
@@ -20107,13 +20939,13 @@ var init_auth = __esm({
|
|
|
20107
20939
|
op_tos_uri: SafeUrlSchema.optional(),
|
|
20108
20940
|
client_id_metadata_document_supported: boolean2().optional()
|
|
20109
20941
|
});
|
|
20110
|
-
OpenIdProviderDiscoveryMetadataSchema =
|
|
20942
|
+
OpenIdProviderDiscoveryMetadataSchema = object6({
|
|
20111
20943
|
...OpenIdProviderMetadataSchema.shape,
|
|
20112
20944
|
...OAuthMetadataSchema.pick({
|
|
20113
20945
|
code_challenge_methods_supported: true
|
|
20114
20946
|
}).shape
|
|
20115
20947
|
});
|
|
20116
|
-
OAuthTokensSchema =
|
|
20948
|
+
OAuthTokensSchema = object6({
|
|
20117
20949
|
access_token: string2(),
|
|
20118
20950
|
id_token: string2().optional(),
|
|
20119
20951
|
// Optional for OAuth 2.1, but necessary in OpenID Connect
|
|
@@ -20127,13 +20959,13 @@ var init_auth = __esm({
|
|
|
20127
20959
|
*/
|
|
20128
20960
|
issuer: string2().optional().catch(void 0)
|
|
20129
20961
|
}).strip();
|
|
20130
|
-
OAuthErrorResponseSchema =
|
|
20962
|
+
OAuthErrorResponseSchema = object6({
|
|
20131
20963
|
error: string2(),
|
|
20132
20964
|
error_description: string2().optional(),
|
|
20133
20965
|
error_uri: string2().optional()
|
|
20134
20966
|
});
|
|
20135
20967
|
OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal2("").transform(() => void 0));
|
|
20136
|
-
OAuthClientMetadataSchema =
|
|
20968
|
+
OAuthClientMetadataSchema = object6({
|
|
20137
20969
|
redirect_uris: array(SafeUrlSchema),
|
|
20138
20970
|
token_endpoint_auth_method: string2().optional(),
|
|
20139
20971
|
grant_types: array(string2()).optional(),
|
|
@@ -20151,7 +20983,7 @@ var init_auth = __esm({
|
|
|
20151
20983
|
software_version: string2().optional(),
|
|
20152
20984
|
software_statement: string2().optional()
|
|
20153
20985
|
}).strip();
|
|
20154
|
-
OAuthClientInformationSchema =
|
|
20986
|
+
OAuthClientInformationSchema = object6({
|
|
20155
20987
|
client_id: string2(),
|
|
20156
20988
|
client_secret: string2().optional(),
|
|
20157
20989
|
client_id_issued_at: number2().optional(),
|
|
@@ -20163,11 +20995,11 @@ var init_auth = __esm({
|
|
|
20163
20995
|
issuer: string2().optional().catch(void 0)
|
|
20164
20996
|
}).strip();
|
|
20165
20997
|
OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
|
|
20166
|
-
OAuthClientRegistrationErrorSchema =
|
|
20998
|
+
OAuthClientRegistrationErrorSchema = object6({
|
|
20167
20999
|
error: string2(),
|
|
20168
21000
|
error_description: string2().optional()
|
|
20169
21001
|
}).strip();
|
|
20170
|
-
OAuthTokenRevocationRequestSchema =
|
|
21002
|
+
OAuthTokenRevocationRequestSchema = object6({
|
|
20171
21003
|
token: string2(),
|
|
20172
21004
|
token_type_hint: string2().optional()
|
|
20173
21005
|
}).strip();
|
|
@@ -20823,11 +21655,11 @@ async function refreshAuthorization(authorizationServerUrl, { metadata, clientIn
|
|
|
20823
21655
|
async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
|
|
20824
21656
|
const readClientInformation = async () => {
|
|
20825
21657
|
const storedClientInformation = await provider.clientInformation();
|
|
20826
|
-
const
|
|
20827
|
-
if (storedClientInformation && !
|
|
21658
|
+
const checked2 = discardIfIssuerMismatch(storedClientInformation, String(authorizationServerUrl));
|
|
21659
|
+
if (storedClientInformation && !checked2) {
|
|
20828
21660
|
throw boundElsewhereError(storedClientInformation, String(authorizationServerUrl));
|
|
20829
21661
|
}
|
|
20830
|
-
return
|
|
21662
|
+
return checked2;
|
|
20831
21663
|
};
|
|
20832
21664
|
let clientInformation = await readClientInformation();
|
|
20833
21665
|
const scope = provider.clientMetadata.scope;
|
|
@@ -22276,29 +23108,23 @@ function createCodingMcpServer(options = {}) {
|
|
|
22276
23108
|
throw new McpError(ErrorCode.InvalidRequest, signIn);
|
|
22277
23109
|
}
|
|
22278
23110
|
};
|
|
22279
|
-
const
|
|
22280
|
-
const grantOf = (config2) => config2
|
|
23111
|
+
const uuid9 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
23112
|
+
const grantOf = (config2) => storedGrant(config2, endpoint2.href);
|
|
22281
23113
|
async function renew() {
|
|
22282
|
-
|
|
22283
|
-
const
|
|
22284
|
-
if (!
|
|
22285
|
-
|
|
22286
|
-
|
|
22287
|
-
|
|
22288
|
-
|
|
22289
|
-
return renewed.access;
|
|
22290
|
-
} catch (error2) {
|
|
22291
|
-
if (error2 instanceof McpGrantRejected && attempt === 0 && grantOf(readConfig())?.refreshToken !== current.refreshToken) continue;
|
|
22292
|
-
if (error2 instanceof McpGrantRejected) throw new McpError(ErrorCode.InvalidRequest, "The Backify MCP connection expired or was disconnected. " + signIn);
|
|
22293
|
-
throw error2;
|
|
22294
|
-
}
|
|
23114
|
+
try {
|
|
23115
|
+
const renewed = await renewStoredGrant({ read: readConfig, save: (config2) => saveUserConfig(configPath2, config2) }, endpoint2.href, options.transport);
|
|
23116
|
+
if (!renewed) throw new McpError(ErrorCode.InvalidRequest, signIn);
|
|
23117
|
+
return renewed.access;
|
|
23118
|
+
} catch (error2) {
|
|
23119
|
+
if (error2 instanceof McpGrantRejected) throw new McpError(ErrorCode.InvalidRequest, "The Backify MCP connection expired or was disconnected. " + signIn);
|
|
23120
|
+
throw error2;
|
|
22295
23121
|
}
|
|
22296
23122
|
}
|
|
22297
23123
|
async function remote(action) {
|
|
22298
23124
|
const config2 = readConfig();
|
|
22299
23125
|
const grant = grantOf(config2);
|
|
22300
23126
|
const organizationIds = grant ? grant.organizationIds : config2.organizationId ? [config2.organizationId] : [];
|
|
22301
|
-
if (!grant && (!config2.organizationId || !
|
|
23127
|
+
if (!grant && (!config2.organizationId || !uuid9.test(config2.organizationId) || !config2.token || /[\r\n]/.test(config2.token) || /^bf(?:cli|agent|mcp)_/i.test(config2.token)))
|
|
22302
23128
|
throw new McpError(ErrorCode.InvalidRequest, signIn);
|
|
22303
23129
|
if (boundOrganizationId && !organizationIds.some((id) => id.toLowerCase() === boundOrganizationId.toLowerCase()))
|
|
22304
23130
|
throw new McpError(ErrorCode.InvalidRequest, "Organization changed. Restart the Backify MCP connection to explicitly select the new organization.");
|
|
@@ -22357,6 +23183,752 @@ var init_mcp = __esm({
|
|
|
22357
23183
|
}
|
|
22358
23184
|
});
|
|
22359
23185
|
|
|
23186
|
+
// src/ops.ts
|
|
23187
|
+
var ops_exports = {};
|
|
23188
|
+
__export(ops_exports, {
|
|
23189
|
+
OpsError: () => OpsError,
|
|
23190
|
+
approvalMessage: () => approvalMessage,
|
|
23191
|
+
forbiddenError: () => forbiddenError,
|
|
23192
|
+
operationInput: () => operationInput,
|
|
23193
|
+
opsArguments: () => opsArguments,
|
|
23194
|
+
opsHelp: () => opsHelp,
|
|
23195
|
+
organizationCall: () => organizationCall,
|
|
23196
|
+
runOps: () => runOps,
|
|
23197
|
+
terminalConfirm: () => terminalConfirm
|
|
23198
|
+
});
|
|
23199
|
+
import { readFileSync as readFileSync10, writeFileSync as writeFileSync7 } from "node:fs";
|
|
23200
|
+
import { basename as basename2, extname } from "node:path";
|
|
23201
|
+
import { createInterface } from "node:readline/promises";
|
|
23202
|
+
function opsArguments(args2) {
|
|
23203
|
+
const [subcommand, ...rest] = args2;
|
|
23204
|
+
if (!subcommand || ["help", "--help", "-h"].includes(subcommand) || rest.includes("--help")) return "help";
|
|
23205
|
+
if (!["search", "describe", "get", "run"].includes(subcommand)) throw new Error("Unknown ops command: " + subcommand + "\n\n" + opsHelp);
|
|
23206
|
+
const command2 = subcommand;
|
|
23207
|
+
const parsed = { subcommand: command2, offset: 0, limit: 25, params: {}, yes: false, json: false };
|
|
23208
|
+
const positional = [];
|
|
23209
|
+
for (let index = 0; index < rest.length; index++) {
|
|
23210
|
+
const flag = rest[index];
|
|
23211
|
+
if (!flag.startsWith("--")) {
|
|
23212
|
+
positional.push(flag);
|
|
23213
|
+
continue;
|
|
23214
|
+
}
|
|
23215
|
+
if (booleanFlags[flag]) {
|
|
23216
|
+
if (!booleanFlags[flag].includes(command2)) throw new Error(`${flag} does not apply to ops ${command2}.`);
|
|
23217
|
+
if (flag === "--yes") parsed.yes = true;
|
|
23218
|
+
else parsed.json = true;
|
|
23219
|
+
continue;
|
|
23220
|
+
}
|
|
23221
|
+
if (!valueFlags[flag]) throw new Error("Unknown option for ops " + command2 + ": " + flag);
|
|
23222
|
+
if (!valueFlags[flag].includes(command2)) throw new Error(`${flag} does not apply to ops ${command2}.`);
|
|
23223
|
+
const value = rest[++index];
|
|
23224
|
+
if (value === void 0 || flag !== "--param" && value.startsWith("--")) throw new Error(flag + " needs a value.");
|
|
23225
|
+
switch (flag) {
|
|
23226
|
+
case "--organization":
|
|
23227
|
+
if (!uuid8.test(value)) throw new Error("--organization must be an organization ID (UUID).");
|
|
23228
|
+
parsed.organizationId = value;
|
|
23229
|
+
break;
|
|
23230
|
+
case "--group":
|
|
23231
|
+
parsed.group = value;
|
|
23232
|
+
break;
|
|
23233
|
+
case "--offset":
|
|
23234
|
+
case "--limit": {
|
|
23235
|
+
if (!/^\d{1,6}$/.test(value)) throw new Error(flag + " must be a non-negative integer.");
|
|
23236
|
+
const number4 = Number(value);
|
|
23237
|
+
if (flag === "--limit" && (number4 < 1 || number4 > 100)) throw new Error("--limit must be from 1 to 100.");
|
|
23238
|
+
if (flag === "--offset") parsed.offset = number4;
|
|
23239
|
+
else parsed.limit = number4;
|
|
23240
|
+
break;
|
|
23241
|
+
}
|
|
23242
|
+
case "--param": {
|
|
23243
|
+
const separator = value.indexOf("=");
|
|
23244
|
+
const name2 = separator > 0 ? value.substring(0, separator) : "";
|
|
23245
|
+
if (!/^[A-Za-z0-9_.-]{1,100}$/.test(name2)) throw new Error("Use --param <name>=<value>.");
|
|
23246
|
+
const item = value.substring(separator + 1), existing = parsed.params[name2];
|
|
23247
|
+
parsed.params[name2] = existing === void 0 ? item : [...Array.isArray(existing) ? existing : [existing], item];
|
|
23248
|
+
break;
|
|
23249
|
+
}
|
|
23250
|
+
case "--body":
|
|
23251
|
+
parsed.body = value;
|
|
23252
|
+
break;
|
|
23253
|
+
case "--output":
|
|
23254
|
+
parsed.output = value;
|
|
23255
|
+
break;
|
|
23256
|
+
}
|
|
23257
|
+
}
|
|
23258
|
+
if (command2 === "search") parsed.query = positional.join(" ").trim() || void 0;
|
|
23259
|
+
else {
|
|
23260
|
+
if (positional.length !== 1) throw new Error(`Use backify ops ${command2} <operationId>. Find IDs with backify ops search <query>.`);
|
|
23261
|
+
if (!/^[A-Za-z0-9_.:-]{1,256}$/.test(positional[0])) throw new Error("Invalid operation ID.");
|
|
23262
|
+
parsed.operationId = positional[0];
|
|
23263
|
+
}
|
|
23264
|
+
return parsed;
|
|
23265
|
+
}
|
|
23266
|
+
function signInRequired(organizationId) {
|
|
23267
|
+
return new OpsError(`Organization access is required. Run ${reconnect(organizationId ?? "<organization-id>")} and approve the scopes you need in the browser.`, "organization_sign_in_required", { reauthenticationCommand: reconnect(organizationId ?? "<organization-id>") });
|
|
23268
|
+
}
|
|
23269
|
+
async function signIn2(context2, organizationId) {
|
|
23270
|
+
const read = () => {
|
|
23271
|
+
try {
|
|
23272
|
+
return JSON.parse(readFileSync10(context2.configPath, "utf8"));
|
|
23273
|
+
} catch {
|
|
23274
|
+
throw signInRequired(organizationId);
|
|
23275
|
+
}
|
|
23276
|
+
};
|
|
23277
|
+
const config2 = read();
|
|
23278
|
+
const grant = storedGrant(config2, context2.mcpEndpoint);
|
|
23279
|
+
if (!grant) throw signInRequired(organizationId ?? config2.organizationId);
|
|
23280
|
+
const same = (left) => (right) => left.toLowerCase() === right.toLowerCase();
|
|
23281
|
+
const organization = organizationId ?? (config2.organizationId && grant.organizationIds.some(same(config2.organizationId)) ? config2.organizationId : grant.organizationIds[0]);
|
|
23282
|
+
if (!grant.organizationIds.some(same(organization)))
|
|
23283
|
+
throw new OpsError(`Your CLI organization access does not cover organization ${organization}. Run ${reconnect(organization)} and approve access to it.`, "organization_not_granted", { organizationId: organization, reauthenticationCommand: reconnect(organization) });
|
|
23284
|
+
try {
|
|
23285
|
+
const renewed = await renewStoredGrant({ read, save: (next) => saveUserConfig(context2.configPath, next) }, context2.mcpEndpoint, context2.transport);
|
|
23286
|
+
if (!renewed) throw signInRequired(organization);
|
|
23287
|
+
return { token: renewed.access.token, scopes: renewed.access.scope.split(" ").filter(Boolean), organizationId: organization, apiUrl: apiAddress(context2.apiUrl) };
|
|
23288
|
+
} catch (error2) {
|
|
23289
|
+
if (error2 instanceof McpGrantRejected) throw new OpsError(`Your CLI organization access expired or was revoked. Run ${reconnect(organization)}.`, "organization_access_expired", { reauthenticationCommand: reconnect(organization) });
|
|
23290
|
+
throw error2;
|
|
23291
|
+
}
|
|
23292
|
+
}
|
|
23293
|
+
async function problemOf(response) {
|
|
23294
|
+
try {
|
|
23295
|
+
const raw = await response.text();
|
|
23296
|
+
const body = raw.length <= 65536 ? JSON.parse(raw) : void 0;
|
|
23297
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return {};
|
|
23298
|
+
const text2 = (value) => typeof value === "string" ? value.substring(0, 500) : void 0;
|
|
23299
|
+
const errors = body.errors && typeof body.errors === "object" && !Array.isArray(body.errors) ? Object.fromEntries(Object.entries(body.errors).slice(0, 20).map(([field, messages]) => [field.substring(0, 100), (Array.isArray(messages) ? messages : [messages]).filter((message) => typeof message === "string").slice(0, 5)])) : void 0;
|
|
23300
|
+
const kind2 = typeof body.kind === "string" && /^[a-z][a-z._]{1,63}$/.test(body.kind) ? body.kind : void 0;
|
|
23301
|
+
const draft = body.draft && typeof body.draft === "object" && !Array.isArray(body.draft) ? Object.fromEntries(Object.entries(body.draft).filter(([key, value]) => /^[A-Za-z]{1,64}$/.test(key) && typeof value === "string" && value.length <= 200).slice(0, 10)) : void 0;
|
|
23302
|
+
return { title: text2(body.title), detail: text2(body.detail), code: text2(body.code), requiredScopes: Array.isArray(body.requiredScopes) ? body.requiredScopes.filter((scope) => typeof scope === "string").slice(0, 5) : void 0, errors, kind: kind2, draft };
|
|
23303
|
+
} catch {
|
|
23304
|
+
return {};
|
|
23305
|
+
}
|
|
23306
|
+
}
|
|
23307
|
+
function forbiddenError(problem, organizationId, operationId) {
|
|
23308
|
+
const command2 = reconnect(organizationId), operation = operationId ? ` ${operationId}` : " this operation";
|
|
23309
|
+
const details = { status: 403, ...problem, organizationId, reauthenticationCommand: command2 };
|
|
23310
|
+
switch (problem.code) {
|
|
23311
|
+
case "insufficient_scope": {
|
|
23312
|
+
const scopes2 = problem.requiredScopes?.length ? problem.requiredScopes.join(" ") : void 0;
|
|
23313
|
+
return new OpsError(scopes2 ? `Your CLI organization access does not include ${scopes2}, which${operation} needs. Run ${command2} and grant ${scopes2} in the browser.` : `Backify has no reviewed delegation policy for${operation}, so CLI organization access cannot run it. Use the portal, or update the CLI and run ${command2} if a newer Backify allows it.`, "insufficient_scope", details);
|
|
23314
|
+
}
|
|
23315
|
+
case "operation_not_delegable":
|
|
23316
|
+
return new OpsError(`${operationId ?? "This operation"} is not a catalog operation that CLI organization access may run. Use backify ops search to find a delegable operation; if the catalog changed, run ${command2} and grant the scope it needs.`, "operation_not_delegable", details);
|
|
23317
|
+
case "organization_not_granted":
|
|
23318
|
+
return new OpsError(`Your CLI organization access does not cover organization ${organizationId}. Run ${command2} and approve access to it.`, "organization_not_granted", details);
|
|
23319
|
+
default:
|
|
23320
|
+
return new OpsError("Backify denied this operation. Your organization roles apply as well as the CLI's granted scopes." + (problem.title ? " " + problem.title : "") + (problem.detail ? " " + problem.detail : ""), "forbidden", details);
|
|
23321
|
+
}
|
|
23322
|
+
}
|
|
23323
|
+
async function send(session, context2, path, init = {}, operationId) {
|
|
23324
|
+
let response;
|
|
23325
|
+
try {
|
|
23326
|
+
response = await (context2.transport ?? fetch)(session.apiUrl + path, {
|
|
23327
|
+
...init,
|
|
23328
|
+
redirect: "error",
|
|
23329
|
+
signal: AbortSignal.timeout(6e4),
|
|
23330
|
+
headers: { ...init.headers, "user-agent": cliUserAgent, authorization: "Bearer " + session.token, "X-Organization-ID": session.organizationId }
|
|
23331
|
+
});
|
|
23332
|
+
} catch {
|
|
23333
|
+
throw new OpsError("Cannot reach the Backify API. Check connectivity.", "unreachable");
|
|
23334
|
+
}
|
|
23335
|
+
if (!response.ok) {
|
|
23336
|
+
if (response.status === 401) throw new OpsError(`Your CLI organization access expired or was revoked. Run ${reconnect(session.organizationId)}.`, "organization_access_expired", { status: 401, reauthenticationCommand: reconnect(session.organizationId) });
|
|
23337
|
+
if (response.status === 403) throw forbiddenError(await problemOf(response), session.organizationId, operationId);
|
|
23338
|
+
if ([400, 404, 409, 422].includes(response.status)) {
|
|
23339
|
+
const problem = await problemOf(response);
|
|
23340
|
+
const fields = problem.errors ? Object.entries(problem.errors).map(([field, messages]) => `${field}: ${messages.join(" ")}`) : [];
|
|
23341
|
+
throw new OpsError([`Backify rejected the request (HTTP ${response.status}).`, problem.title, problem.detail, ...fields].filter(Boolean).join(" "), problem.code ?? "request_rejected", { status: response.status, ...problem });
|
|
23342
|
+
}
|
|
23343
|
+
throw new OpsError(`Backify API request failed (HTTP ${response.status}). Inspect the portal for details.`, "request_failed", { status: response.status });
|
|
23344
|
+
}
|
|
23345
|
+
return { status: response.status, contentType: response.headers.get("content-type") ?? "", bytes: Buffer.from(await response.arrayBuffer()) };
|
|
23346
|
+
}
|
|
23347
|
+
async function catalogOf(session, context2) {
|
|
23348
|
+
const response = await send(session, context2, "/mcp/catalog");
|
|
23349
|
+
let catalog;
|
|
23350
|
+
try {
|
|
23351
|
+
catalog = JSON.parse(response.bytes.toString("utf8"));
|
|
23352
|
+
} catch {
|
|
23353
|
+
catalog = void 0;
|
|
23354
|
+
}
|
|
23355
|
+
if (!catalog || typeof catalog.organizationId !== "string" || catalog.organizationId.toLowerCase() !== session.organizationId.toLowerCase() || !Array.isArray(catalog.operations))
|
|
23356
|
+
throw new OpsError("Backify returned an invalid organization catalog.", "invalid_catalog");
|
|
23357
|
+
return catalog;
|
|
23358
|
+
}
|
|
23359
|
+
function find(catalog, operationId) {
|
|
23360
|
+
const operation = catalog.operations.find((item) => item.id === operationId) ?? catalog.operations.find((item) => item.id.toLowerCase() === operationId.toLowerCase());
|
|
23361
|
+
if (operation) return operation;
|
|
23362
|
+
const suggestions = searchOperations(catalog.operations, operationId).slice(0, 3).map((item) => item.id);
|
|
23363
|
+
throw new OpsError(`Unknown operation ${operationId}.` + (suggestions.length ? " Did you mean " + suggestions.join(", ") + "?" : "") + " Find operations with backify ops search <query>.", "unknown_operation", { suggestions });
|
|
23364
|
+
}
|
|
23365
|
+
function requireScopes(operation, session) {
|
|
23366
|
+
const missing = missingOperationScopes(operation.requiredScopes, session.scopes);
|
|
23367
|
+
if (missing === null || missing.length) throw forbiddenError({ code: "insufficient_scope", requiredScopes: missing === null ? void 0 : missing }, session.organizationId, operation.id);
|
|
23368
|
+
}
|
|
23369
|
+
function readInput(path, context2, what) {
|
|
23370
|
+
if (path === "-") return (context2.readStdin ?? (() => readFileSync10(0)))();
|
|
23371
|
+
try {
|
|
23372
|
+
return readFileSync10(path);
|
|
23373
|
+
} catch {
|
|
23374
|
+
throw new OpsError(`Cannot read ${what} ${path}.`, "invalid_input");
|
|
23375
|
+
}
|
|
23376
|
+
}
|
|
23377
|
+
function operationInput(operation, options, organizationId, context2 = {}) {
|
|
23378
|
+
const input = { organizationId };
|
|
23379
|
+
const parameters = {};
|
|
23380
|
+
const formFile = operation.parameters.find((parameter) => parameter.location === "formfile");
|
|
23381
|
+
for (const [name2, value] of Object.entries(options.params)) {
|
|
23382
|
+
if (formFile && name2 === formFile.name) {
|
|
23383
|
+
if (Array.isArray(value) || !value.startsWith("@") || value.length < 2) throw new OpsError(`Pass the file as --param ${name2}=@<path>.`, "invalid_input");
|
|
23384
|
+
const path = value.substring(1);
|
|
23385
|
+
input.file = { name: basename2(path), contentType: contentTypes[extname(path).toLowerCase()] ?? "application/octet-stream", contentBase64: readInput(path, context2, "file").toString("base64") };
|
|
23386
|
+
} else parameters[name2] = value;
|
|
23387
|
+
}
|
|
23388
|
+
if (Object.keys(parameters).length) input.parameters = parameters;
|
|
23389
|
+
if (options.body !== void 0) {
|
|
23390
|
+
const source = options.body.startsWith("@") && options.body.length > 1 ? options.body.substring(1) : options.body;
|
|
23391
|
+
const bytes = readInput(source, context2, "body file");
|
|
23392
|
+
if (operation.rawBodyContentType) input.rawBodyBase64 = bytes.toString("base64");
|
|
23393
|
+
else {
|
|
23394
|
+
try {
|
|
23395
|
+
input.body = JSON.parse(bytes.toString("utf8").replace(/^/, ""));
|
|
23396
|
+
} catch {
|
|
23397
|
+
throw new OpsError(`The body in ${options.body === "-" ? "standard input" : source} is not valid JSON.`, "invalid_input");
|
|
23398
|
+
}
|
|
23399
|
+
}
|
|
23400
|
+
}
|
|
23401
|
+
return input;
|
|
23402
|
+
}
|
|
23403
|
+
function redact(value) {
|
|
23404
|
+
if (Array.isArray(value)) return value.map(redact);
|
|
23405
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sensitiveKey.test(key) ? "[hidden]" : redact(item)]));
|
|
23406
|
+
return value;
|
|
23407
|
+
}
|
|
23408
|
+
function describeBody(body) {
|
|
23409
|
+
if (!body) return void 0;
|
|
23410
|
+
if (body.kind === "json") return redact(body.value);
|
|
23411
|
+
const bytes = Math.floor(body.contentBase64.length * 3 / 4);
|
|
23412
|
+
return body.kind === "raw" ? { contentType: body.contentType, bytes } : { file: body.name, field: body.field, contentType: body.contentType, bytes };
|
|
23413
|
+
}
|
|
23414
|
+
function approvalMessage(operation, organizationId, url2, body) {
|
|
23415
|
+
const lines = [`Run ${operation.id}${operation.summary ? ` (${operation.summary})` : ""} in organization ${organizationId}?`, `${operation.method} ${url2}`];
|
|
23416
|
+
const shown = describeBody(body);
|
|
23417
|
+
if (shown !== void 0) lines.push("Body:", JSON.stringify(shown, null, 2));
|
|
23418
|
+
return lines.join("\n");
|
|
23419
|
+
}
|
|
23420
|
+
function terminalConfirm() {
|
|
23421
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY) return void 0;
|
|
23422
|
+
return async (message) => {
|
|
23423
|
+
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
23424
|
+
try {
|
|
23425
|
+
return /^(y|yes)$/i.test((await prompt.question(message + "\nProceed? [y/N] ")).trim());
|
|
23426
|
+
} finally {
|
|
23427
|
+
prompt.close();
|
|
23428
|
+
}
|
|
23429
|
+
};
|
|
23430
|
+
}
|
|
23431
|
+
function toFetchBody(body) {
|
|
23432
|
+
if (!body) return {};
|
|
23433
|
+
if (body.kind === "json") return { body: JSON.stringify(body.value), headers: { "content-type": "application/json" } };
|
|
23434
|
+
if (body.kind === "raw") return { body: new Uint8Array(Buffer.from(body.contentBase64, "base64")), headers: { "content-type": body.contentType } };
|
|
23435
|
+
const form = new FormData();
|
|
23436
|
+
form.append(body.field, new Blob([new Uint8Array(Buffer.from(body.contentBase64, "base64"))], { type: body.contentType }), body.name);
|
|
23437
|
+
return { body: form };
|
|
23438
|
+
}
|
|
23439
|
+
function present(response, output) {
|
|
23440
|
+
if (output) {
|
|
23441
|
+
writeFileSync7(output, response.bytes);
|
|
23442
|
+
const value2 = { output, bytes: response.bytes.length, contentType: response.contentType || null };
|
|
23443
|
+
return { value: value2, text: `Saved ${response.bytes.length} bytes to ${output}.` };
|
|
23444
|
+
}
|
|
23445
|
+
if (response.status === 204 || !response.bytes.length) return { value: { status: response.status }, text: `Done (HTTP ${response.status}).` };
|
|
23446
|
+
if (/json/i.test(response.contentType)) {
|
|
23447
|
+
const value2 = JSON.parse(response.bytes.toString("utf8"));
|
|
23448
|
+
return { value: value2, text: JSON.stringify(value2, null, 2) };
|
|
23449
|
+
}
|
|
23450
|
+
if (/^text\//i.test(response.contentType)) {
|
|
23451
|
+
const value2 = response.bytes.toString("utf8");
|
|
23452
|
+
return { value: value2, text: value2 };
|
|
23453
|
+
}
|
|
23454
|
+
const value = { contentType: response.contentType || "application/octet-stream", bytes: response.bytes.length, note: "Binary response. Pass --output <file> to save it." };
|
|
23455
|
+
return { value, text: JSON.stringify(value, null, 2) };
|
|
23456
|
+
}
|
|
23457
|
+
function schemaType(schema) {
|
|
23458
|
+
if (!schema || typeof schema !== "object") return "any";
|
|
23459
|
+
const value = schema;
|
|
23460
|
+
if (Array.isArray(value.enum)) return value.enum.map(String).join(" | ");
|
|
23461
|
+
const type = Array.isArray(value.type) ? value.type.join(" | ") : typeof value.type === "string" ? value.type : "object";
|
|
23462
|
+
return type === "array" ? schemaType(value.items) + "[]" : value.format ? `${type} (${value.format})` : type;
|
|
23463
|
+
}
|
|
23464
|
+
function searchResult(catalog, session, options) {
|
|
23465
|
+
const matches = searchOperations(catalog.operations, options.query, options.group);
|
|
23466
|
+
const groups = !matches.length || !(options.query || options.group) ? [...new Set(catalog.operations.map((operation) => operation.group))].sort() : void 0;
|
|
23467
|
+
const page = matches.slice(options.offset, options.offset + options.limit).map(({ parameters: _parameters, returns: _returns, ...operation }) => ({ ...operation, missingScopes: missingOperationScopes(operation.requiredScopes, session.scopes) }));
|
|
23468
|
+
const value = { organizationId: catalog.organizationId, grantedScopes: session.scopes, total: matches.length, offset: options.offset, limit: options.limit, groups, operations: page };
|
|
23469
|
+
const lines = [matches.length ? `${matches.length} operation${matches.length === 1 ? "" : "s"}${options.query ? ` match "${options.query}"` : ""}${options.group ? ` in group ${options.group}` : ""}` + (page.length < matches.length ? ` (showing ${options.offset + 1}-${options.offset + page.length})` : "") + ":" : `No operations match${options.query ? ` "${options.query}"` : ""}${options.group ? ` in group ${options.group}` : ""}.`];
|
|
23470
|
+
const idWidth = Math.min(48, Math.max(0, ...page.map((operation) => operation.id.length)) + 2);
|
|
23471
|
+
const routeWidth = Math.min(64, Math.max(0, ...page.map((operation) => operation.method.length + operation.path.length + 1)) + 2);
|
|
23472
|
+
for (const operation of page) {
|
|
23473
|
+
const access = operation.missingScopes === null ? " [not delegable]" : operation.missingScopes.length ? ` [needs ${operation.missingScopes.join(" ")}]` : "";
|
|
23474
|
+
lines.push(" " + pad(operation.id, idWidth) + pad(`${operation.method} ${operation.path}`, routeWidth) + (operation.summary ?? "") + access);
|
|
23475
|
+
}
|
|
23476
|
+
if (groups) lines.push("", "Groups: " + groups.join(", "));
|
|
23477
|
+
if (page.length) lines.push("", "Next: backify ops describe <operationId>");
|
|
23478
|
+
return { value, text: lines.join("\n") };
|
|
23479
|
+
}
|
|
23480
|
+
function describeResult(operation, session) {
|
|
23481
|
+
const missing = missingOperationScopes(operation.requiredScopes, session.scopes);
|
|
23482
|
+
const value = { ...operation, missingScopes: missing };
|
|
23483
|
+
const changes = operation.method !== "GET";
|
|
23484
|
+
const lines = [
|
|
23485
|
+
operation.id + (operation.summary ? " - " + operation.summary : ""),
|
|
23486
|
+
`${operation.method} ${operation.path}`,
|
|
23487
|
+
"Scopes: " + (missing === null ? "not delegable; use the portal" : (operation.requiredScopes?.length ? operation.requiredScopes.join(" ") : "none") + (missing.length ? ` (missing: ${missing.join(" ")}; run ${reconnect(session.organizationId)} to grant them)` : " (granted)"))
|
|
23488
|
+
];
|
|
23489
|
+
const routed = operation.parameters.filter((parameter) => ["path", "query"].includes(parameter.location) && !["org", "organizationId", "orgId"].includes(parameter.name));
|
|
23490
|
+
if (routed.length) {
|
|
23491
|
+
lines.push("", "Parameters:");
|
|
23492
|
+
for (const parameter of routed) lines.push(` ${parameter.name} (${parameter.location}${parameter.required ? ", required" : ""}): ${schemaType(parameter.schema)}`);
|
|
23493
|
+
}
|
|
23494
|
+
const body = operation.parameters.find((parameter) => parameter.location === "body");
|
|
23495
|
+
const file = operation.parameters.find((parameter) => parameter.location === "formfile");
|
|
23496
|
+
if (operation.rawBodyContentType) lines.push("", `Body: raw ${operation.rawBodyContentType} package; pass --body <file>.`);
|
|
23497
|
+
else if (file) lines.push("", `File: pass --param ${file.name}=@<path>.`);
|
|
23498
|
+
else if (body) lines.push("", `Body${body.required ? " (required)" : ""}: JSON file via --body <file>, schema:`, JSON.stringify(body.schema, null, 2));
|
|
23499
|
+
if (operation.returns !== void 0 && operation.returns !== null) lines.push("", "Returns:", typeof operation.returns === "string" ? operation.returns : JSON.stringify(operation.returns, null, 2));
|
|
23500
|
+
const example = [
|
|
23501
|
+
"backify ops",
|
|
23502
|
+
changes ? "run" : "get",
|
|
23503
|
+
operation.id,
|
|
23504
|
+
...routed.filter((parameter) => parameter.required).map((parameter) => `--param ${parameter.name}=<${parameter.name}>`),
|
|
23505
|
+
...operation.rawBodyContentType || body ? ["--body <file>"] : [],
|
|
23506
|
+
...file ? [`--param ${file.name}=@<path>`] : []
|
|
23507
|
+
].join(" ");
|
|
23508
|
+
lines.push("", "Example: " + example);
|
|
23509
|
+
return { value, text: lines.join("\n") };
|
|
23510
|
+
}
|
|
23511
|
+
async function runOps(options, context2) {
|
|
23512
|
+
const session = await signIn2(context2, options.organizationId);
|
|
23513
|
+
const catalog = await catalogOf(session, context2);
|
|
23514
|
+
if (options.subcommand === "search") return searchResult(catalog, session, options);
|
|
23515
|
+
const operation = find(catalog, options.operationId);
|
|
23516
|
+
if (options.subcommand === "describe") return describeResult(operation, session);
|
|
23517
|
+
if (options.subcommand === "get" && operation.method !== "GET")
|
|
23518
|
+
throw new OpsError(`${operation.id} is a ${operation.method} operation that changes data. Use backify ops run ${operation.id}.`, "write_operation");
|
|
23519
|
+
if (options.subcommand === "run" && operation.method === "GET")
|
|
23520
|
+
throw new OpsError(`${operation.id} only reads data. Use backify ops get ${operation.id}.`, "read_operation");
|
|
23521
|
+
const humanOnly = typeof operation.humanTask === "string";
|
|
23522
|
+
if (!humanOnly) requireScopes(operation, session);
|
|
23523
|
+
let request;
|
|
23524
|
+
const requestOperation = humanOnly ? { ...operation, parameters: operation.parameters.map((parameter) => parameter.location === "body" ? { ...parameter, required: false } : parameter) } : operation;
|
|
23525
|
+
try {
|
|
23526
|
+
request = buildOperationRequest(requestOperation, operationInput(requestOperation, options, session.organizationId, context2));
|
|
23527
|
+
} catch (error2) {
|
|
23528
|
+
if (error2 instanceof OperationRequestError) throw new OpsError(error2.message + ` See backify ops describe ${operation.id}.`, "invalid_input");
|
|
23529
|
+
throw error2;
|
|
23530
|
+
}
|
|
23531
|
+
if (options.subcommand === "run" && !options.yes && !humanOnly) {
|
|
23532
|
+
const message = approvalMessage(operation, session.organizationId, session.apiUrl + request.path, request.body);
|
|
23533
|
+
if (!context2.confirm) throw new OpsError(`Refusing to change data without confirmation. Review this request and re-run with --yes:
|
|
23534
|
+
${message}`, "confirmation_required", { method: request.method, url: session.apiUrl + request.path, body: describeBody(request.body) });
|
|
23535
|
+
if (!await context2.confirm(message)) throw new OpsError("Not confirmed. Nothing was executed.", "not_confirmed");
|
|
23536
|
+
}
|
|
23537
|
+
let response;
|
|
23538
|
+
try {
|
|
23539
|
+
response = await send(session, context2, request.path, { method: request.method, ...toFetchBody(request.body) }, operation.id);
|
|
23540
|
+
} catch (error2) {
|
|
23541
|
+
const details = error2 instanceof OpsError ? error2.details : void 0;
|
|
23542
|
+
if (!(error2 instanceof OpsError) || error2.code !== "human_task_required" || !details?.kind) throw error2;
|
|
23543
|
+
const draft = details.draft ?? {};
|
|
23544
|
+
if (!context2.humanTask)
|
|
23545
|
+
throw new OpsError(`Only a person may run ${operation.id}. Request the task and complete it in the browser: backify task start ${details.kind} --draft '${JSON.stringify(draft)}'`, "human_task_required", { kind: details.kind, draft });
|
|
23546
|
+
return context2.humanTask({ kind: details.kind, draft, organizationId: session.organizationId, call: sessionCall(session, context2), operationId: operation.id });
|
|
23547
|
+
}
|
|
23548
|
+
return present(response, options.output);
|
|
23549
|
+
}
|
|
23550
|
+
function sessionCall(session, context2) {
|
|
23551
|
+
return async (path, init = {}) => {
|
|
23552
|
+
const response = await send(session, context2, path, init);
|
|
23553
|
+
return response.bytes.length ? JSON.parse(response.bytes.toString("utf8")) : void 0;
|
|
23554
|
+
};
|
|
23555
|
+
}
|
|
23556
|
+
async function organizationCall(context2, organizationId) {
|
|
23557
|
+
const session = await signIn2(context2, organizationId);
|
|
23558
|
+
return { call: sessionCall(session, context2), organizationId: session.organizationId };
|
|
23559
|
+
}
|
|
23560
|
+
var opsHelp, OpsError, uuid8, valueFlags, booleanFlags, reconnect, contentTypes, sensitiveKey, pad;
|
|
23561
|
+
var init_ops = __esm({
|
|
23562
|
+
"src/ops.ts"() {
|
|
23563
|
+
"use strict";
|
|
23564
|
+
init_dist();
|
|
23565
|
+
init_cli_session();
|
|
23566
|
+
init_development();
|
|
23567
|
+
init_mcp_grant();
|
|
23568
|
+
opsHelp = [
|
|
23569
|
+
"Usage: backify ops <search|describe|get|run> [options]",
|
|
23570
|
+
"",
|
|
23571
|
+
" ops search [<query>] [--group <group>] [--offset <n>] [--limit <n>] Find operations (ranked; synonyms and typos match)",
|
|
23572
|
+
" ops describe <operationId> Route, parameters, body schema and required scopes",
|
|
23573
|
+
" ops get <operationId> [--param <name>=<value> ...] [--output <file>] Run a read (GET) operation",
|
|
23574
|
+
" ops run <operationId> [--param <name>=<value> ...] [--body <file>] [--yes] [--output <file>]",
|
|
23575
|
+
" Run a change; asks y/N on a terminal, otherwise needs --yes",
|
|
23576
|
+
"",
|
|
23577
|
+
"Options: --organization <id> (default: the signed-in organization) --json (machine-readable output and errors)",
|
|
23578
|
+
" --param repeats; a repeated name sends a list. File parameters take --param <name>=@<path>.",
|
|
23579
|
+
" --body <file> is a JSON file (or the raw package for upload operations); --body - reads standard input.",
|
|
23580
|
+
"",
|
|
23581
|
+
"Sign in first: backify login --organization <organization-id> --organization-access"
|
|
23582
|
+
].join("\n");
|
|
23583
|
+
OpsError = class extends Error {
|
|
23584
|
+
constructor(message, code, details = {}) {
|
|
23585
|
+
super(message);
|
|
23586
|
+
this.code = code;
|
|
23587
|
+
this.details = details;
|
|
23588
|
+
}
|
|
23589
|
+
};
|
|
23590
|
+
uuid8 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
23591
|
+
valueFlags = {
|
|
23592
|
+
"--organization": ["search", "describe", "get", "run"],
|
|
23593
|
+
"--group": ["search"],
|
|
23594
|
+
"--offset": ["search"],
|
|
23595
|
+
"--limit": ["search"],
|
|
23596
|
+
"--param": ["get", "run"],
|
|
23597
|
+
"--body": ["get", "run"],
|
|
23598
|
+
"--output": ["get", "run"]
|
|
23599
|
+
};
|
|
23600
|
+
booleanFlags = { "--json": ["search", "describe", "get", "run"], "--yes": ["run"] };
|
|
23601
|
+
reconnect = (organizationId) => `backify login --organization ${organizationId} --organization-access`;
|
|
23602
|
+
contentTypes = {
|
|
23603
|
+
".json": "application/json",
|
|
23604
|
+
".txt": "text/plain",
|
|
23605
|
+
".csv": "text/csv",
|
|
23606
|
+
".md": "text/markdown",
|
|
23607
|
+
".html": "text/html",
|
|
23608
|
+
".xml": "application/xml",
|
|
23609
|
+
".png": "image/png",
|
|
23610
|
+
".jpg": "image/jpeg",
|
|
23611
|
+
".jpeg": "image/jpeg",
|
|
23612
|
+
".gif": "image/gif",
|
|
23613
|
+
".webp": "image/webp",
|
|
23614
|
+
".svg": "image/svg+xml",
|
|
23615
|
+
".ico": "image/x-icon",
|
|
23616
|
+
".pdf": "application/pdf",
|
|
23617
|
+
".zip": "application/zip",
|
|
23618
|
+
".gz": "application/gzip",
|
|
23619
|
+
".tgz": "application/gzip"
|
|
23620
|
+
};
|
|
23621
|
+
sensitiveKey = /secret|password|passphrase|token|credential|private|api[-_]?key|connection[-_]?string/i;
|
|
23622
|
+
pad = (value, width) => value.length >= width ? value + " " : value + " ".repeat(width - value.length);
|
|
23623
|
+
}
|
|
23624
|
+
});
|
|
23625
|
+
|
|
23626
|
+
// src/tasks.ts
|
|
23627
|
+
var tasks_exports = {};
|
|
23628
|
+
__export(tasks_exports, {
|
|
23629
|
+
opsHumanTaskHandler: () => opsHumanTaskHandler,
|
|
23630
|
+
runTaskCommand: () => runTaskCommand,
|
|
23631
|
+
startTask: () => startTask,
|
|
23632
|
+
taskArguments: () => taskArguments,
|
|
23633
|
+
taskDraft: () => taskDraft,
|
|
23634
|
+
taskHelp: () => taskHelp
|
|
23635
|
+
});
|
|
23636
|
+
import { readFileSync as readFileSync11 } from "node:fs";
|
|
23637
|
+
function taskArguments(args2) {
|
|
23638
|
+
const options = { noBrowser: false, noWait: false, json: false, yes: false };
|
|
23639
|
+
const positional = [], values = {};
|
|
23640
|
+
for (let index = 0; index < args2.length; index++) {
|
|
23641
|
+
const flag = args2[index];
|
|
23642
|
+
if (!flag.startsWith("--")) {
|
|
23643
|
+
positional.push(flag);
|
|
23644
|
+
continue;
|
|
23645
|
+
}
|
|
23646
|
+
if (flag === "--no-browser") {
|
|
23647
|
+
options.noBrowser = true;
|
|
23648
|
+
continue;
|
|
23649
|
+
}
|
|
23650
|
+
if (flag === "--no-wait") {
|
|
23651
|
+
options.noWait = true;
|
|
23652
|
+
continue;
|
|
23653
|
+
}
|
|
23654
|
+
if (flag === "--json") {
|
|
23655
|
+
options.json = true;
|
|
23656
|
+
continue;
|
|
23657
|
+
}
|
|
23658
|
+
if (flag === "--yes") {
|
|
23659
|
+
options.yes = true;
|
|
23660
|
+
continue;
|
|
23661
|
+
}
|
|
23662
|
+
const value = args2[++index];
|
|
23663
|
+
if (value === void 0 || value.startsWith("--")) throw new Error(flag + " needs a value.");
|
|
23664
|
+
if (flag === "--organization") {
|
|
23665
|
+
if (!isUuid(value)) throw new Error("--organization must be an organization ID (UUID).");
|
|
23666
|
+
options.organizationId = value;
|
|
23667
|
+
continue;
|
|
23668
|
+
}
|
|
23669
|
+
if (flag === "--timeout") {
|
|
23670
|
+
if (!/^\d{1,4}$/.test(value)) throw new Error("--timeout is in seconds.");
|
|
23671
|
+
options.timeoutMs = Number(value) * 1e3;
|
|
23672
|
+
continue;
|
|
23673
|
+
}
|
|
23674
|
+
(values[flag.slice(2)] ??= []).push(value);
|
|
23675
|
+
}
|
|
23676
|
+
return { options, positional, values };
|
|
23677
|
+
}
|
|
23678
|
+
function taskDraft(values, read = (path) => readFileSync11(path, "utf8")) {
|
|
23679
|
+
let draft = {};
|
|
23680
|
+
for (const source of values.draft ?? []) {
|
|
23681
|
+
const parsed = JSON.parse(source.startsWith("@") ? read(source.slice(1)) : source);
|
|
23682
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("--draft must be a JSON object.");
|
|
23683
|
+
draft = { ...draft, ...parsed };
|
|
23684
|
+
}
|
|
23685
|
+
for (const pair of values.set ?? []) {
|
|
23686
|
+
const index = pair.indexOf("=");
|
|
23687
|
+
if (index < 1) throw new Error("--set takes <name>=<value>.");
|
|
23688
|
+
const raw = pair.slice(index + 1);
|
|
23689
|
+
let value = raw;
|
|
23690
|
+
try {
|
|
23691
|
+
if (/^(true|false|null|-?\d+(\.\d+)?|\[.*\]|\{.*\})$/s.test(raw)) value = JSON.parse(raw);
|
|
23692
|
+
} catch {
|
|
23693
|
+
value = raw;
|
|
23694
|
+
}
|
|
23695
|
+
draft[pair.slice(0, index)] = value;
|
|
23696
|
+
}
|
|
23697
|
+
return draft;
|
|
23698
|
+
}
|
|
23699
|
+
async function startTask(call2, kind2, draft, options, context2) {
|
|
23700
|
+
const created = validateHumanTask(await requestHumanTask(call2, kind2, draft), kind2);
|
|
23701
|
+
return follow(call2, created, options, context2);
|
|
23702
|
+
}
|
|
23703
|
+
async function follow(call2, initial, options, context2) {
|
|
23704
|
+
const { status, link, reason } = await waitForHumanTask(initial, async () => validateHumanTask(await readHumanTask(call2, initial.id), initial.kind), {
|
|
23705
|
+
portalUrl: context2.portalUrl,
|
|
23706
|
+
noBrowser: options.noBrowser,
|
|
23707
|
+
noWait: options.noWait,
|
|
23708
|
+
timeoutMs: options.timeoutMs,
|
|
23709
|
+
signal: context2.signal,
|
|
23710
|
+
openBrowser: context2.openBrowser,
|
|
23711
|
+
progress: context2.progress,
|
|
23712
|
+
sleep: context2.sleep,
|
|
23713
|
+
now: context2.now,
|
|
23714
|
+
intervalMs: context2.intervalMs
|
|
23715
|
+
}, purposes[initial.kind] ?? "complete the request");
|
|
23716
|
+
const value = { taskId: status.id, kind: status.kind, state: status.state, url: link, nextAction: status.nextAction, result: status.result, ...reason ? { waiting: reason } : {} };
|
|
23717
|
+
const exitCode = status.state === "completed" ? 0 : status.state === "pending" ? 2 : 1;
|
|
23718
|
+
const text2 = status.state === "pending" ? `The task is waiting for a person: ${link}` + (reason === "timed_out" ? "\nStopped waiting. Resume with backify task wait " + status.id : "") : `${status.state}: ${status.nextAction}` + (status.result ? "\n" + JSON.stringify(status.result, null, 2) : "");
|
|
23719
|
+
return { value, text: text2, exitCode };
|
|
23720
|
+
}
|
|
23721
|
+
function opsHumanTaskHandler(options, context2) {
|
|
23722
|
+
return async (request) => {
|
|
23723
|
+
context2.progress?.(`Only a person may run ${request.operationId ?? "this operation"}. Requesting a ${request.kind} task instead.`);
|
|
23724
|
+
const result = await startTask(request.call, request.kind, request.draft, options, context2);
|
|
23725
|
+
if (result.exitCode === 1) throw new OpsError(result.text, "human_task_" + String(result.value.state), result.value);
|
|
23726
|
+
return result;
|
|
23727
|
+
};
|
|
23728
|
+
}
|
|
23729
|
+
function scopedGrants(entries, scopeType, flag) {
|
|
23730
|
+
return (entries ?? []).map((entry) => {
|
|
23731
|
+
const at = entry.indexOf("="), scopeId = entry.slice(0, at), role = entry.slice(at + 1).trim();
|
|
23732
|
+
if (at < 1 || !isUuid(scopeId) || !role) throw new Error(`${flag} takes <id>=<role>, for example ${flag} 3f2c\u2026=Developer.`);
|
|
23733
|
+
return { scopeType, scopeId, role };
|
|
23734
|
+
});
|
|
23735
|
+
}
|
|
23736
|
+
async function runTaskCommand(command2, args2, context2) {
|
|
23737
|
+
const { options, positional, values } = taskArguments(args2);
|
|
23738
|
+
const { call: call2, organizationId } = await organizationCall(context2, options.organizationId);
|
|
23739
|
+
const [sub, target] = positional;
|
|
23740
|
+
const start = (kind2, draft) => startTask(call2, kind2, draft, options, context2);
|
|
23741
|
+
switch (`${command2} ${sub ?? ""}`.trim()) {
|
|
23742
|
+
case "task start": {
|
|
23743
|
+
if (!target || !/^[a-z][a-z._]{1,63}$/.test(target)) throw new Error("Name the task kind, e.g. backify task start azure.connect.");
|
|
23744
|
+
return { result: await start(target, taskDraft(values)), json: options.json };
|
|
23745
|
+
}
|
|
23746
|
+
case "task get":
|
|
23747
|
+
case "task wait":
|
|
23748
|
+
case "task open": {
|
|
23749
|
+
if (!target || !isUuid(target)) throw new Error("Pass the task ID.");
|
|
23750
|
+
const status = await readHumanTask(call2, target);
|
|
23751
|
+
if (sub === "get") return { result: { value: status, text: `${status.state}: ${status.nextAction}`, exitCode: status.state === "completed" ? 0 : status.state === "pending" ? 2 : 1 }, json: options.json };
|
|
23752
|
+
if (sub === "open") {
|
|
23753
|
+
const link = humanTaskUrl(portalOrigin2(context2.portalUrl), status);
|
|
23754
|
+
context2.openBrowser(link);
|
|
23755
|
+
return { result: { value: { url: link }, text: link }, json: options.json };
|
|
23756
|
+
}
|
|
23757
|
+
return { result: await follow(call2, status, { ...options, noBrowser: true }, context2), json: options.json };
|
|
23758
|
+
}
|
|
23759
|
+
case "github connect":
|
|
23760
|
+
return { result: await start("github.install", {}), json: options.json };
|
|
23761
|
+
case "azure connect":
|
|
23762
|
+
return { result: await start("azure.connect", { ...values.subscription ? { subscriptionId: values.subscription[0] } : {}, ...values.region ? { region: values.region[0] } : {} }), json: options.json };
|
|
23763
|
+
case "azure reconnect":
|
|
23764
|
+
return { result: await start("azure.elevate", { connectionId: connection(values) }), json: options.json };
|
|
23765
|
+
case "azure update-agent":
|
|
23766
|
+
return { result: await start("azure.agent_update", { connectionId: connection(values) }), json: options.json };
|
|
23767
|
+
case "azure uninstall":
|
|
23768
|
+
return { result: await start("azure.uninstall", { connectionId: connection(values) }), json: options.json };
|
|
23769
|
+
case "azure remove":
|
|
23770
|
+
return { result: await start("azure.remove", { connectionId: connection(values) }), json: options.json };
|
|
23771
|
+
case "org":
|
|
23772
|
+
case "org show": {
|
|
23773
|
+
const summary = await call2("/organizations/" + organizationId + "/summary");
|
|
23774
|
+
return { result: { value: summary, text: JSON.stringify(summary, null, 2) }, json: options.json };
|
|
23775
|
+
}
|
|
23776
|
+
case "billing":
|
|
23777
|
+
case "billing show": {
|
|
23778
|
+
const billing = await call2("/organizations/" + organizationId + "/billing");
|
|
23779
|
+
return { result: { value: billing, text: JSON.stringify(billing, null, 2) + "\nUse backify billing checkout or backify billing change-plan to request browser review." }, json: options.json };
|
|
23780
|
+
}
|
|
23781
|
+
case "billing checkout":
|
|
23782
|
+
case "billing change-plan": {
|
|
23783
|
+
const [plan] = values.plan ?? [], [interval] = values.interval ?? [], [currency] = values.currency ?? [];
|
|
23784
|
+
return { result: await start(sub === "checkout" ? "billing.checkout" : "billing.change_plan", { plan, interval, currency }), json: options.json };
|
|
23785
|
+
}
|
|
23786
|
+
case "members add": {
|
|
23787
|
+
const emails = positional.slice(1);
|
|
23788
|
+
if (!emails.length || emails.some((email2) => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email2))) throw new Error("Pass one or more email addresses to add.");
|
|
23789
|
+
const grants = [...scopedGrants(values.app, "application", "--app"), ...scopedGrants(values.workspace, "workspace", "--workspace")];
|
|
23790
|
+
const teamIds = values.team ?? [];
|
|
23791
|
+
if (teamIds.some((id) => !isUuid(id))) throw new Error("--team takes a team ID (UUID).");
|
|
23792
|
+
const role = values.role?.[0] ?? "Member";
|
|
23793
|
+
const access = grants.length ? grants.map((grant) => grant.role + " on " + grant.scopeType + " " + grant.scopeId).join(", ") : "no workspace or application access";
|
|
23794
|
+
if (!options.yes) {
|
|
23795
|
+
if (!context2.confirm) throw new OpsError(`Refusing to add people without confirmation. Re-run with --yes to add ${emails.length} with ${access}.`, "confirmation_required");
|
|
23796
|
+
if (!await context2.confirm(`Add ${emails.join(", ")} to organization ${organizationId} (new people as ${role}) with ${access}?`)) throw new OpsError("Not confirmed. Nothing was sent.", "not_confirmed");
|
|
23797
|
+
}
|
|
23798
|
+
const added = await call2(
|
|
23799
|
+
"/organizations/" + organizationId + "/people",
|
|
23800
|
+
{ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ emails, role, grants, teamIds }) }
|
|
23801
|
+
);
|
|
23802
|
+
const lines = added.people.map((person) => `${person.email}: ${person.outcome.replace(/_/g, " ")}${person.detail ? " (" + person.detail + ")" : ""}`);
|
|
23803
|
+
return { result: { value: added, text: [`${added.invited} invited, ${added.updated} given access, ${added.skipped} skipped.`, ...lines].join("\n"), exitCode: added.skipped && !added.invited && !added.updated ? 1 : 0 }, json: options.json };
|
|
23804
|
+
}
|
|
23805
|
+
case "members list": {
|
|
23806
|
+
const status = values.status?.[0];
|
|
23807
|
+
if (status && !["active", "invited", "suspended"].includes(status)) throw new Error("--status is active, invited or suspended.");
|
|
23808
|
+
const people = await call2("/organizations/" + organizationId + "/access/people?pageSize=100" + (status ? "&status=" + status : ""));
|
|
23809
|
+
return { result: { value: people, text: people.items.map((person) => `${person.email} ${person.status ?? "active"} ${person.organizationRole ?? "Member"}`).join("\n") + (people.totalCount > people.items.length ? `
|
|
23810
|
+
\u2026 ${people.totalCount - people.items.length} more` : "") }, json: options.json };
|
|
23811
|
+
}
|
|
23812
|
+
case "members invitations": {
|
|
23813
|
+
const access = await call2("/organizations/" + organizationId + "/access");
|
|
23814
|
+
const invitations = access.invitations ?? [];
|
|
23815
|
+
return { result: { value: invitations, text: invitations.length ? invitations.map((invitation) => `${invitation.email} ${invitation.role} expires ${invitation.expiresAt} ${(invitation.grants ?? []).map((grant) => grant.role + " on " + grant.scopeType + " " + grant.scopeId).join(", ") || "no scoped access"}`).join("\n") : "No pending invitations." }, json: options.json };
|
|
23816
|
+
}
|
|
23817
|
+
case "members join-links": {
|
|
23818
|
+
if (target === "revoke") {
|
|
23819
|
+
const id = positional[2];
|
|
23820
|
+
if (!id || !isUuid(id)) throw new Error("Pass the join link ID to revoke.");
|
|
23821
|
+
if (!options.yes) {
|
|
23822
|
+
if (!context2.confirm) throw new OpsError("Refusing to revoke without confirmation. Re-run with --yes.", "confirmation_required");
|
|
23823
|
+
if (!await context2.confirm(`Revoke join link ${id}? Nobody else can join with it.`)) throw new OpsError("Not confirmed. Nothing was changed.", "not_confirmed");
|
|
23824
|
+
}
|
|
23825
|
+
await call2("/organizations/" + organizationId + "/join-links/" + id, { method: "DELETE" });
|
|
23826
|
+
return { result: { value: { id, revoked: true }, text: "Join link revoked." }, json: options.json };
|
|
23827
|
+
}
|
|
23828
|
+
if (target) throw new Error("Use backify members join-links, or backify members join-links revoke <id>. Create join links in the portal under People & access.");
|
|
23829
|
+
const links = await call2("/organizations/" + organizationId + "/join-links");
|
|
23830
|
+
return { result: { value: links, text: links.length ? links.map((link) => `${link.id} ${link.name} joins as ${link.role} ${link.useCount}${link.maxUses != null ? "/" + link.maxUses : ""} joined expires ${link.expiresAt}`).join("\n") : "No join links. Create one in the portal under People & access." }, json: options.json };
|
|
23831
|
+
}
|
|
23832
|
+
case "members domains": {
|
|
23833
|
+
const domains = await call2("/organizations/" + organizationId + "/join-domains");
|
|
23834
|
+
return { result: { value: domains, text: domains.length ? domains.map((domain) => `${domain.domain} ${domain.verifiedAt ? "verified" : "unverified (TXT " + domain.record + " = " + domain.value + ")"} automatic joining ${domain.autoJoinRole ? "on as " + domain.autoJoinRole : "off"}`).join("\n") : "No company email domains." }, json: options.json };
|
|
23835
|
+
}
|
|
23836
|
+
case "members invite": {
|
|
23837
|
+
if (!target || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(target)) throw new Error("Pass the email address to invite.");
|
|
23838
|
+
const body = { email: target, role: values.role?.[0] ?? "Member", ...values.workspace ? { workspaceId: values.workspace[0] } : {} };
|
|
23839
|
+
if (!options.yes) {
|
|
23840
|
+
if (!context2.confirm) throw new OpsError(`Refusing to invite without confirmation. Re-run with --yes to invite ${target} as ${body.role}.`, "confirmation_required");
|
|
23841
|
+
if (!await context2.confirm(`Invite ${target} to organization ${organizationId} as ${body.role}?`)) throw new OpsError("Not confirmed. Nothing was sent.", "not_confirmed");
|
|
23842
|
+
}
|
|
23843
|
+
const created = await call2("/organizations/" + organizationId + "/invitations", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
23844
|
+
const shown = { id: created?.invitation?.id, email: created?.invitation?.email, role: created?.invitation?.role, expiresAt: created?.invitation?.expiresAt };
|
|
23845
|
+
return { result: { value: shown, text: `Invited ${target} as ${body.role}. They receive an email to accept.` }, json: options.json };
|
|
23846
|
+
}
|
|
23847
|
+
default:
|
|
23848
|
+
throw new Error("Unknown command.\n\n" + taskHelp);
|
|
23849
|
+
}
|
|
23850
|
+
}
|
|
23851
|
+
var taskHelp, purposes, connection;
|
|
23852
|
+
var init_tasks = __esm({
|
|
23853
|
+
"src/tasks.ts"() {
|
|
23854
|
+
"use strict";
|
|
23855
|
+
init_human_task();
|
|
23856
|
+
init_ops();
|
|
23857
|
+
taskHelp = [
|
|
23858
|
+
"Usage:",
|
|
23859
|
+
" backify task start <kind> [--draft <json>|@<file>] [--set <name>=<value> ...] Request a step only a person may perform and wait",
|
|
23860
|
+
" backify task get <taskId> Read a task's state and result",
|
|
23861
|
+
" backify task wait <taskId> Wait until the person finishes it",
|
|
23862
|
+
" backify task open <taskId> Open the task page in the browser",
|
|
23863
|
+
"",
|
|
23864
|
+
" backify github connect Install or choose the Backify GitHub App (github.install)",
|
|
23865
|
+
" backify azure connect [--subscription <id>] [--region <name>] Connect an Azure subscription (azure.connect)",
|
|
23866
|
+
" backify azure reconnect|update-agent|uninstall|remove --connection <id>",
|
|
23867
|
+
" Renew authorization, approve an agent update, uninstall the agent,",
|
|
23868
|
+
" or remove everything Backify created (azure.elevate, azure.agent_update,",
|
|
23869
|
+
" azure.uninstall, azure.remove)",
|
|
23870
|
+
" backify org Organization summary",
|
|
23871
|
+
" backify billing Subscription status",
|
|
23872
|
+
" backify billing checkout|change-plan [--plan <plan>] [--interval <interval>] [--currency <currency>]",
|
|
23873
|
+
" Review a subscription or plan change in the browser",
|
|
23874
|
+
" backify members add <email...> [--role <role>] [--app <id>=<role>] [--workspace <id>=<role>] [--team <id>] [--yes]",
|
|
23875
|
+
" Add up to 200 people: members get the access now, new people are invited",
|
|
23876
|
+
" by email and get it when they accept",
|
|
23877
|
+
" backify members invite <email> [--role <role>] [--workspace <id>] [--yes]",
|
|
23878
|
+
" backify members list [--status active|invited|suspended] People in the organization, including pending invitations",
|
|
23879
|
+
" backify members invitations Pending invitations and the access they carry",
|
|
23880
|
+
" backify members join-links [revoke <id> --yes] Reusable join links (create them in the portal: the link is a secret)",
|
|
23881
|
+
" backify members domains Company email domains and automatic joining",
|
|
23882
|
+
"",
|
|
23883
|
+
"Options: --organization <id> --no-browser --no-wait --timeout <seconds> --json",
|
|
23884
|
+
"Kinds: " + [
|
|
23885
|
+
"github.install",
|
|
23886
|
+
"azure.connect",
|
|
23887
|
+
"azure.elevate",
|
|
23888
|
+
"azure.agent_update",
|
|
23889
|
+
"azure.uninstall",
|
|
23890
|
+
"azure.remove",
|
|
23891
|
+
"approval",
|
|
23892
|
+
"sso.test_signin",
|
|
23893
|
+
"entra.app_setup",
|
|
23894
|
+
"entra.shared_consent",
|
|
23895
|
+
"integration.adopt",
|
|
23896
|
+
"integration.account",
|
|
23897
|
+
"auth.setup",
|
|
23898
|
+
"confirm.destructive",
|
|
23899
|
+
"domain.confirm",
|
|
23900
|
+
"billing.checkout",
|
|
23901
|
+
"billing.change_plan"
|
|
23902
|
+
].join(", "),
|
|
23903
|
+
"Sign in first: backify login --organization <organization-id> --organization-access"
|
|
23904
|
+
].join("\n");
|
|
23905
|
+
purposes = {
|
|
23906
|
+
"github.install": "connect GitHub",
|
|
23907
|
+
"azure.connect": "connect Azure",
|
|
23908
|
+
"azure.elevate": "renew Backify's Azure authorization",
|
|
23909
|
+
"azure.agent_update": "approve the Backify Cloud Agent update",
|
|
23910
|
+
"azure.uninstall": "uninstall the Backify Cloud Agent",
|
|
23911
|
+
"azure.remove": "remove everything Backify created in Azure",
|
|
23912
|
+
"approval": "approve or reject the request",
|
|
23913
|
+
"sso.test_signin": "test single sign-on",
|
|
23914
|
+
"entra.app_setup": "set up Microsoft Entra sign-in",
|
|
23915
|
+
"entra.shared_consent": "grant Microsoft Entra consent",
|
|
23916
|
+
"integration.adopt": "review the integration",
|
|
23917
|
+
"integration.account": "connect the integration's account",
|
|
23918
|
+
"auth.setup": "set up sign-in",
|
|
23919
|
+
"confirm.destructive": "confirm the deletion",
|
|
23920
|
+
"domain.confirm": "confirm the custom domain",
|
|
23921
|
+
"billing.checkout": "review the subscription and complete Stripe Checkout",
|
|
23922
|
+
"billing.change_plan": "review the plan change"
|
|
23923
|
+
};
|
|
23924
|
+
connection = (values) => {
|
|
23925
|
+
const id = values.connection?.[0];
|
|
23926
|
+
if (!id || !isUuid(id)) throw new Error("Pass --connection <cloud-connection-id>.");
|
|
23927
|
+
return id;
|
|
23928
|
+
};
|
|
23929
|
+
}
|
|
23930
|
+
});
|
|
23931
|
+
|
|
22360
23932
|
// src/coding-tools.ts
|
|
22361
23933
|
var coding_tools_exports = {};
|
|
22362
23934
|
__export(coding_tools_exports, {
|
|
@@ -22364,10 +23936,10 @@ __export(coding_tools_exports, {
|
|
|
22364
23936
|
codingTools: () => codingTools,
|
|
22365
23937
|
configureCodingTool: () => configureCodingTool
|
|
22366
23938
|
});
|
|
22367
|
-
import { existsSync as existsSync8, lstatSync as lstatSync4, mkdirSync as mkdirSync2, readFileSync as
|
|
22368
|
-
import { basename as
|
|
23939
|
+
import { existsSync as existsSync8, lstatSync as lstatSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync12, renameSync as renameSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync8 } from "node:fs";
|
|
23940
|
+
import { basename as basename3, dirname as dirname4, join as join10, resolve as resolve4 } from "node:path";
|
|
22369
23941
|
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
22370
|
-
function
|
|
23942
|
+
function object7(value) {
|
|
22371
23943
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22372
23944
|
}
|
|
22373
23945
|
function codingToolEntry(agent, transport) {
|
|
@@ -22389,17 +23961,17 @@ function configureCodingTool(options) {
|
|
|
22389
23961
|
if (dirname4(current) === current) break;
|
|
22390
23962
|
}
|
|
22391
23963
|
if (options.dryRun) return { agent, transport, path, entry: codingToolEntry(agent, transport), changed: void 0 };
|
|
22392
|
-
const previous = existsSync8(path) ?
|
|
23964
|
+
const previous = existsSync8(path) ? readFileSync12(path, "utf8") : void 0;
|
|
22393
23965
|
let config2;
|
|
22394
23966
|
try {
|
|
22395
23967
|
config2 = previous === void 0 ? {} : JSON.parse(previous);
|
|
22396
23968
|
} catch {
|
|
22397
23969
|
throw new Error("MCP configuration must be valid JSON. Existing JSONC/comments or invalid files are left unchanged; use --dry-run to obtain the entry for manual setup.");
|
|
22398
23970
|
}
|
|
22399
|
-
if (!
|
|
22400
|
-
const key = agent === "copilot" &&
|
|
23971
|
+
if (!object7(config2)) throw new Error("MCP configuration must be a JSON object; the file is unchanged.");
|
|
23972
|
+
const key = agent === "copilot" && basename3(path) !== ".mcp.json" ? "servers" : "mcpServers";
|
|
22401
23973
|
const servers = config2[key] ?? {};
|
|
22402
|
-
if (!
|
|
23974
|
+
if (!object7(servers)) throw new Error("MCP server configuration must be a JSON object; the file is unchanged.");
|
|
22403
23975
|
const entry = codingToolEntry(agent, transport);
|
|
22404
23976
|
const changed = JSON.stringify(servers.backify) !== JSON.stringify(entry);
|
|
22405
23977
|
if (servers.backify !== void 0 && changed && !options.dryRun) throw new Error("An existing Backify MCP configuration differs. It is unchanged; inspect --dry-run and update it manually.");
|
|
@@ -22408,8 +23980,8 @@ function configureCodingTool(options) {
|
|
|
22408
23980
|
mkdirSync2(dirname4(path), { recursive: true });
|
|
22409
23981
|
const temporary = path + "." + randomUUID5() + ".tmp";
|
|
22410
23982
|
try {
|
|
22411
|
-
|
|
22412
|
-
if ((existsSync8(path) ?
|
|
23983
|
+
writeFileSync8(temporary, JSON.stringify({ ...config2, [key]: { ...servers, backify: entry } }, null, 2) + "\n", { flag: "wx", mode: existsSync8(path) ? lstatSync4(path).mode & 511 : 384 });
|
|
23984
|
+
if ((existsSync8(path) ? readFileSync12(path, "utf8") : void 0) !== previous) throw new Error("MCP configuration changed during setup. Retry after reviewing it.");
|
|
22413
23985
|
renameSync2(temporary, path);
|
|
22414
23986
|
} finally {
|
|
22415
23987
|
if (existsSync8(temporary)) unlinkSync2(temporary);
|
|
@@ -22442,7 +24014,7 @@ __export(project_exports, {
|
|
|
22442
24014
|
sdkRunner: () => sdkRunner
|
|
22443
24015
|
});
|
|
22444
24016
|
import { spawn } from "node:child_process";
|
|
22445
|
-
import { existsSync as existsSync9, mkdirSync as mkdirSync3, readFileSync as
|
|
24017
|
+
import { existsSync as existsSync9, mkdirSync as mkdirSync3, readFileSync as readFileSync13 } from "node:fs";
|
|
22446
24018
|
import { createRequire } from "node:module";
|
|
22447
24019
|
import { dirname as dirname5, join as join11, relative as relative2, resolve as resolve5 } from "node:path";
|
|
22448
24020
|
import { pathToFileURL } from "node:url";
|
|
@@ -22464,7 +24036,7 @@ function sdkRunner(root) {
|
|
|
22464
24036
|
const lookup = createRequire(join11(root, "package.json")).resolve.paths("@backifydev/sdk") ?? [];
|
|
22465
24037
|
const manifest = lookup.map((directory) => join11(directory, "@backifydev", "sdk", "package.json")).find((path) => existsSync9(path));
|
|
22466
24038
|
if (!manifest) throw new ProjectError("@backifydev/sdk is not installed. Run npm install.");
|
|
22467
|
-
const version2 = JSON.parse(
|
|
24039
|
+
const version2 = JSON.parse(readFileSync13(manifest, "utf8")).version;
|
|
22468
24040
|
const runner = join11(dirname5(manifest), "dist", "app", "run.js");
|
|
22469
24041
|
if (!existsSync9(runner)) throw new ProjectError(`The installed @backifydev/sdk ${version2} does not include backify-run. Update it with npm install @backifydev/sdk@latest.`);
|
|
22470
24042
|
return { runner, version: version2 };
|
|
@@ -22536,6 +24108,103 @@ var init_project = __esm({
|
|
|
22536
24108
|
}
|
|
22537
24109
|
});
|
|
22538
24110
|
|
|
24111
|
+
// src/signup.ts
|
|
24112
|
+
var signup_exports = {};
|
|
24113
|
+
__export(signup_exports, {
|
|
24114
|
+
signup: () => signup,
|
|
24115
|
+
signupArguments: () => signupArguments,
|
|
24116
|
+
signupHelp: () => signupHelp
|
|
24117
|
+
});
|
|
24118
|
+
import { readFileSync as readFileSync14 } from "node:fs";
|
|
24119
|
+
function signupArguments(args2) {
|
|
24120
|
+
const values = {}, flags = /* @__PURE__ */ new Set();
|
|
24121
|
+
for (let i = 0; i < args2.length; i++) {
|
|
24122
|
+
const value = args2[i];
|
|
24123
|
+
if (["--json", "--no-browser", "--no-wait", "--resume"].includes(value)) {
|
|
24124
|
+
if (flags.has(value)) throw new Error("Duplicate signup option: " + value);
|
|
24125
|
+
flags.add(value);
|
|
24126
|
+
} else if (["--name", "--company", "--plan", "--interval", "--currency", "--scopes", "--timeout"].includes(value)) {
|
|
24127
|
+
if (value in values || !args2[i + 1] || args2[i + 1].startsWith("--")) throw new Error("Specify one value for " + value);
|
|
24128
|
+
values[value] = args2[++i];
|
|
24129
|
+
} else throw new Error("Unknown signup argument: " + value);
|
|
24130
|
+
}
|
|
24131
|
+
if (flags.has("--resume") && Object.keys(values).some((key) => key !== "--timeout")) throw new Error("Resume with --resume only; the suggested details cannot change.");
|
|
24132
|
+
const scopes2 = values["--scopes"]?.split(",").map((scope) => scope.trim()).filter(Boolean);
|
|
24133
|
+
if (scopes2?.some((scope) => !allScopes.includes(scope))) throw new Error("Use --scopes with " + allScopes.join(", ") + ".");
|
|
24134
|
+
if (values["--plan"] && !["starter", "team", "business"].includes(values["--plan"])) throw new Error("Use --plan starter, team or business.");
|
|
24135
|
+
if (values["--interval"] && !["month", "year"].includes(values["--interval"])) throw new Error("Use --interval month or year.");
|
|
24136
|
+
if (values["--currency"] && !["eur", "usd"].includes(values["--currency"])) throw new Error("Use --currency eur or usd.");
|
|
24137
|
+
const company = values["--company"] ? JSON.parse(readFileSync14(values["--company"], "utf8")) : void 0;
|
|
24138
|
+
if (company !== void 0 && (typeof company !== "object" || company === null || Array.isArray(company))) throw new Error("--company must be a JSON file holding one object of company details.");
|
|
24139
|
+
const draft = Object.fromEntries(Object.entries({ organizationName: values["--name"], company, plan: values["--plan"], interval: values["--interval"], currency: values["--currency"], scopes: scopes2 ? [.../* @__PURE__ */ new Set(["organization:read", ...scopes2])] : void 0 }).filter(([, value]) => value !== void 0));
|
|
24140
|
+
return { draft, resume: flags.has("--resume"), noBrowser: flags.has("--no-browser"), noWait: flags.has("--no-wait"), timeoutMs: values["--timeout"] === void 0 ? void 0 : Number(values["--timeout"]) * 1e3 };
|
|
24141
|
+
}
|
|
24142
|
+
async function signup(options) {
|
|
24143
|
+
const transport = options.transport ?? fetch, api = apiAddress(options.resume?.apiUrl ?? options.apiUrl), endpoint2 = resourceOf(options.resume?.mcpEndpoint ?? options.mcpEndpoint);
|
|
24144
|
+
const send2 = async (path, init = {}) => {
|
|
24145
|
+
const { secret, ...rest } = init;
|
|
24146
|
+
const response = await transport(api + path, { ...rest, redirect: "error", signal: AbortSignal.timeout(3e4), headers: { "content-type": "application/json", "user-agent": cliUserAgent, ...secret ? { "X-Task-Secret": secret } : {} } });
|
|
24147
|
+
const body2 = await response.json().catch(() => void 0);
|
|
24148
|
+
if (!response.ok && !(path.endsWith("/exchange") && response.status === 400)) throw new Error(body2?.detail ?? body2?.title ?? "Backify could not process the signup (HTTP " + response.status + ").");
|
|
24149
|
+
return body2;
|
|
24150
|
+
};
|
|
24151
|
+
let pending = options.resume, initial;
|
|
24152
|
+
if (pending) {
|
|
24153
|
+
if (!isUuid(pending.taskId)) throw new Error("The saved signup is invalid. Run backify signup again.");
|
|
24154
|
+
initial = await send2("/tasks/" + pending.taskId + "/status", { secret: pending.secret });
|
|
24155
|
+
} else {
|
|
24156
|
+
const proof = pkce();
|
|
24157
|
+
const requested = await send2("/tasks/anonymous", { method: "POST", body: JSON.stringify({ kind: "signup", draft: options.draft ?? {}, codeChallenge: proof.challenge, ...humanTaskClient }) });
|
|
24158
|
+
if (!requested?.task || typeof requested.pollSecret !== "string" || !requested.pollSecret.startsWith("bftask_")) throw new Error("The server returned an invalid signup request.");
|
|
24159
|
+
initial = requested.task;
|
|
24160
|
+
pending = { taskId: initial.id, secret: requested.pollSecret, verifier: proof.verifier, apiUrl: api, mcpEndpoint: endpoint2 };
|
|
24161
|
+
options.savePending(pending);
|
|
24162
|
+
}
|
|
24163
|
+
validateHumanTask(initial, "signup");
|
|
24164
|
+
const saved = pending;
|
|
24165
|
+
const { status, link, reason } = await waitForHumanTask(initial, async () => validateHumanTask(await send2("/tasks/" + saved.taskId + "/status", { secret: saved.secret }), "signup"), options, "sign up for Backify and connect the CLI");
|
|
24166
|
+
const result = {
|
|
24167
|
+
state: status.state,
|
|
24168
|
+
connected: false,
|
|
24169
|
+
taskId: status.id,
|
|
24170
|
+
setupUrl: link,
|
|
24171
|
+
matchCode: initial.matchCode ?? null,
|
|
24172
|
+
organizationId: status.organizationId,
|
|
24173
|
+
organizationName: status.result?.organizationName ?? null,
|
|
24174
|
+
billingStatus: status.result?.billingStatus ?? null,
|
|
24175
|
+
scope: null,
|
|
24176
|
+
nextAction: status.nextAction,
|
|
24177
|
+
...reason ? { reason } : {}
|
|
24178
|
+
};
|
|
24179
|
+
if (status.state === "pending") return result;
|
|
24180
|
+
options.savePending(void 0);
|
|
24181
|
+
if (status.state !== "completed" || !status.organizationId) return result;
|
|
24182
|
+
if (!status.credentialAvailable) return { ...result, nextAction: "The organization is ready, but no CLI access is waiting. Sign in with backify login --organization " + status.organizationId + " --organization-access." };
|
|
24183
|
+
const body = await send2("/tasks/" + saved.taskId + "/exchange", { method: "POST", secret: saved.secret, body: JSON.stringify({ codeVerifier: saved.verifier, clientId: cliClientId, resource: endpoint2 }) });
|
|
24184
|
+
if (body && "error" in body) throw new Error("Backify could not hand over CLI access (" + String(body.error) + "). Sign in with backify login --organization " + status.organizationId + " --organization-access.");
|
|
24185
|
+
const { access, refreshToken } = grantTokens(body);
|
|
24186
|
+
options.saveGrant({ endpoint: endpoint2, refreshToken, scope: access.scope, organizationIds: [status.organizationId] }, status.organizationId);
|
|
24187
|
+
return { ...result, connected: true, scope: access.scope, nextAction: "The CLI is connected to " + (result.organizationName ?? "the organization") + ". Use backify ops or backify mcp to manage it." };
|
|
24188
|
+
}
|
|
24189
|
+
var signupHelp, allScopes;
|
|
24190
|
+
var init_signup = __esm({
|
|
24191
|
+
"src/signup.ts"() {
|
|
24192
|
+
"use strict";
|
|
24193
|
+
init_development();
|
|
24194
|
+
init_cli_session();
|
|
24195
|
+
init_human_task();
|
|
24196
|
+
init_mcp_grant();
|
|
24197
|
+
signupHelp = `backify signup [--name <organization>] [--company <json-file>] [--plan starter|team|business] [--interval month|year] [--currency eur|usd]
|
|
24198
|
+
backify signup --resume
|
|
24199
|
+
Options: --scopes <comma-separated> --no-browser --no-wait --timeout <seconds, 1-3600> --json
|
|
24200
|
+
Opens a Backify page where you sign in (creating your account if needed), check the code the CLI prints, set up your
|
|
24201
|
+
organization, choose a plan and pay in Stripe Checkout, and approve what the CLI may change. The CLI suggests the details;
|
|
24202
|
+
you decide. Payment details are entered only on Stripe's page. Exit code 0 means the organization is ready and the CLI is
|
|
24203
|
+
connected; 2 means it is still waiting for you, or you declined. Resume a waiting signup with --resume.`;
|
|
24204
|
+
allScopes = ["organization:read", "organization:write", "deployment:manage", "billing:manage", "access:manage"];
|
|
24205
|
+
}
|
|
24206
|
+
});
|
|
24207
|
+
|
|
22539
24208
|
// src/app/new.ts
|
|
22540
24209
|
var new_exports = {};
|
|
22541
24210
|
__export(new_exports, {
|
|
@@ -22543,7 +24212,7 @@ __export(new_exports, {
|
|
|
22543
24212
|
createApp: () => createApp,
|
|
22544
24213
|
templatesDirectory: () => templatesDirectory
|
|
22545
24214
|
});
|
|
22546
|
-
import { cpSync as cpSync2, existsSync as existsSync10, mkdirSync as mkdirSync4, readdirSync as readdirSync3, readFileSync as
|
|
24215
|
+
import { cpSync as cpSync2, existsSync as existsSync10, mkdirSync as mkdirSync4, readdirSync as readdirSync3, readFileSync as readFileSync15, renameSync as renameSync3, statSync, writeFileSync as writeFileSync9 } from "node:fs";
|
|
22547
24216
|
import { dirname as dirname6, join as join12, resolve as resolve6 } from "node:path";
|
|
22548
24217
|
import { fileURLToPath } from "node:url";
|
|
22549
24218
|
function templatesDirectory() {
|
|
@@ -22569,9 +24238,9 @@ function createApp(options) {
|
|
|
22569
24238
|
for (const hidden of ["_gitignore", "_dockerignore"]) if (existsSync10(join12(target, hidden))) renameSync3(join12(target, hidden), join12(target, "." + hidden.slice(1)));
|
|
22570
24239
|
const files = walk(target);
|
|
22571
24240
|
for (const file of files) {
|
|
22572
|
-
const text2 =
|
|
24241
|
+
const text2 = readFileSync15(file, "utf8");
|
|
22573
24242
|
const rendered = text2.replaceAll("{{name}}", options.name).replaceAll("{{sdkVersion}}", options.sdkVersion).replaceAll("{{cliVersion}}", options.cliVersion);
|
|
22574
|
-
if (rendered !== text2)
|
|
24243
|
+
if (rendered !== text2) writeFileSync9(file, rendered);
|
|
22575
24244
|
}
|
|
22576
24245
|
return files.map((file) => file.slice(target.length + 1).replace(/\\/g, "/")).sort();
|
|
22577
24246
|
}
|
|
@@ -22728,7 +24397,7 @@ var init_command = __esm({
|
|
|
22728
24397
|
|
|
22729
24398
|
// ../analyzer/dist/index.js
|
|
22730
24399
|
import ts3 from "typescript";
|
|
22731
|
-
import { join as join13, extname, posix } from "node:path";
|
|
24400
|
+
import { join as join13, extname as extname2, posix } from "node:path";
|
|
22732
24401
|
function analyzeSources(files, options = {}) {
|
|
22733
24402
|
const used = /* @__PURE__ */ new Set(), diagnostics = [];
|
|
22734
24403
|
const sources = files.filter((file) => !isTestSource(file.path)), wrappers = sdkWrappers(sources);
|
|
@@ -22987,23 +24656,24 @@ __export(lock_exports, {
|
|
|
22987
24656
|
generateLockfile: () => generateLockfile,
|
|
22988
24657
|
lockCommand: () => lockCommand,
|
|
22989
24658
|
migrationDigests: () => migrationDigests,
|
|
24659
|
+
personalDataWarnings: () => personalDataWarnings,
|
|
22990
24660
|
printWarnings: () => printWarnings,
|
|
22991
24661
|
usedCapabilities: () => usedCapabilities
|
|
22992
24662
|
});
|
|
22993
24663
|
import { createHash as createHash4 } from "node:crypto";
|
|
22994
|
-
import { existsSync as existsSync11, readdirSync as readdirSync4, readFileSync as
|
|
24664
|
+
import { existsSync as existsSync11, readdirSync as readdirSync4, readFileSync as readFileSync16, writeFileSync as writeFileSync10 } from "node:fs";
|
|
22995
24665
|
import { join as join14 } from "node:path";
|
|
22996
24666
|
function usedCapabilities(root, files) {
|
|
22997
|
-
const sources = files.filter((file) => /\.[cm]?[jt]sx?$/.test(file)).map((file) => ({ path: file, content:
|
|
24667
|
+
const sources = files.filter((file) => /\.[cm]?[jt]sx?$/.test(file)).map((file) => ({ path: file, content: readFileSync16(join14(root, file), "utf8") }));
|
|
22998
24668
|
return new Set(Object.keys(analyzeSources(sources).capabilities));
|
|
22999
24669
|
}
|
|
23000
24670
|
function migrationDigests(root, config2) {
|
|
23001
24671
|
const directory = join14(root, config2.database?.migrations ?? "db/migrations");
|
|
23002
24672
|
if (!existsSync11(directory)) return [];
|
|
23003
|
-
return readdirSync4(directory).filter((f) => f.endsWith(".sql")).sort().map((file) => ({ file, sha256: createHash4("sha256").update(
|
|
24673
|
+
return readdirSync4(directory).filter((f) => f.endsWith(".sql")).sort().map((file) => ({ file, sha256: createHash4("sha256").update(readFileSync16(join14(directory, file))).digest("hex") }));
|
|
23004
24674
|
}
|
|
23005
24675
|
function declarationDiagnostics(root, files) {
|
|
23006
|
-
const sources = files.filter((file) => /\.[cm]?[jt]sx?$/.test(file)).map((file) => ({ path: file, content:
|
|
24676
|
+
const sources = files.filter((file) => /\.[cm]?[jt]sx?$/.test(file)).map((file) => ({ path: file, content: readFileSync16(join14(root, file), "utf8") }));
|
|
23007
24677
|
const problems = [], warnings = [];
|
|
23008
24678
|
for (const d of analyzeSources(sources).diagnostics) (d.severity === "error" ? problems : warnings).push(`${d.file}:${d.line}: ${d.message}`);
|
|
23009
24679
|
return { problems, warnings };
|
|
@@ -23055,9 +24725,14 @@ async function generateLockfile(root) {
|
|
|
23055
24725
|
frontend: config2.frontend ? { output: config2.frontend.output, spa: config2.frontend.spa ?? true } : void 0,
|
|
23056
24726
|
jobs: catalog.jobs,
|
|
23057
24727
|
schedules: catalog.schedules,
|
|
23058
|
-
events: { subscriptions: catalog.subscriptions },
|
|
23059
|
-
storage: config2.storage ? { buckets: config2.storage.buckets.map((b) => ({ name: b.name, public: b.public ?? false })).sort((a, b) => a.name.localeCompare(b.name)) } : void 0,
|
|
23060
|
-
database: capabilities.has("database") ? {
|
|
24728
|
+
events: { subscriptions: catalog.subscriptions, declarations: catalog.events?.length ? catalog.events : void 0 },
|
|
24729
|
+
storage: config2.storage ? { buckets: config2.storage.buckets.map((b) => ({ name: b.name, public: b.public ?? false, personalData: b.personalData ? normalizeBucketPersonalData(b.personalData) : void 0 })).sort((a, b) => a.name.localeCompare(b.name)) } : void 0,
|
|
24730
|
+
database: capabilities.has("database") ? {
|
|
24731
|
+
migrations: migrationDigests(root, config2),
|
|
24732
|
+
sensitiveColumns: [...config2.database?.sensitiveColumns ?? []].sort(),
|
|
24733
|
+
extensions: config2.database?.extensions?.length ? [...config2.database.extensions].sort() : void 0,
|
|
24734
|
+
personalData: config2.database?.personalData ? normalizePersonalData(config2.database.personalData) : void 0
|
|
24735
|
+
} : void 0,
|
|
23061
24736
|
auth: config2.auth ? { providers: [...config2.auth.providers], roles: [...config2.auth.roles ?? []].sort() } : void 0,
|
|
23062
24737
|
config: config2.config,
|
|
23063
24738
|
ai: config2.ai,
|
|
@@ -23065,17 +24740,40 @@ async function generateLockfile(root) {
|
|
|
23065
24740
|
mail: config2.mail,
|
|
23066
24741
|
integrations: config2.integrations,
|
|
23067
24742
|
protection: config2.protection ? normalizeProtectionConfig(config2.protection) : void 0,
|
|
24743
|
+
retention: config2.retention && { events: config2.retention.events && { ...config2.retention.events }, jobs: config2.retention.jobs && { ...config2.retention.jobs } },
|
|
23068
24744
|
secrets: [...config2.secrets ?? []].sort()
|
|
23069
24745
|
};
|
|
23070
24746
|
if (used.has("protection") && !config2.protection?.dynamicRules) {
|
|
23071
24747
|
for (const file of serverFiles) {
|
|
23072
|
-
if (/protection\.(block|allow|remove)\s*\(/.test(
|
|
24748
|
+
if (/protection\.(block|allow|remove)\s*\(/.test(readFileSync16(join14(root, file), "utf8"))) problems.push(`${file}: dynamic protection rules require protection.dynamicRules in backify.config.ts`);
|
|
23073
24749
|
}
|
|
23074
24750
|
}
|
|
23075
24751
|
for (const route of catalog.backend?.routes ?? []) if (config2.protection?.access && route.auth.kind === "public" && route.method === "POST" && !config2.protection.access.exempt?.includes(route.path)) warnings.push(`${route.path}: public POST route is behind the IP allowlist; consider adding an exempt path for webhooks`);
|
|
24752
|
+
if (lockfile.database?.personalData) warnings.push(...personalDataWarnings(root, config2, lockfile.database.personalData));
|
|
23076
24753
|
problems.push(...validateLockfile(lockfile));
|
|
23077
24754
|
return { lockfile, text: serializeLockfile(lockfile), problems, warnings };
|
|
23078
24755
|
}
|
|
24756
|
+
function personalDataWarnings(root, config2, declared) {
|
|
24757
|
+
const directory = join14(root, config2.database?.migrations ?? "db/migrations");
|
|
24758
|
+
const files = existsSync11(directory) ? readdirSync4(directory).filter((f) => f.endsWith(".sql")).sort().map((file) => ({ file: (config2.database?.migrations ?? "db/migrations") + "/" + file, sql: readFileSync16(join14(directory, file), "utf8") })) : [];
|
|
24759
|
+
const schema = scanMigrations(files);
|
|
24760
|
+
const drift = personalDataDrift(declared, new Map([...schema.tables].map(([table, columns]) => [table, columns.map((column) => column.name)])));
|
|
24761
|
+
const unsure = (name2) => schema.uncertain.has(name2.split(".")[0]) ? " (the migrations change it in ways the scan cannot follow; check it)" : "";
|
|
24762
|
+
const warnings = [
|
|
24763
|
+
...drift.missingTables.map((table) => `personalData.${table}: no migration creates this table${unsure(table)}`),
|
|
24764
|
+
...drift.missingColumns.map((column) => `personalData: ${column} is declared but no migration creates it${unsure(column)}`)
|
|
24765
|
+
];
|
|
24766
|
+
const byTable = /* @__PURE__ */ new Map();
|
|
24767
|
+
for (const candidate of drift.undeclaredCandidates) {
|
|
24768
|
+
const [table, column] = candidate.split(".");
|
|
24769
|
+
byTable.set(table, [...byTable.get(table) ?? [], column]);
|
|
24770
|
+
}
|
|
24771
|
+
for (const [table, columns] of byTable) {
|
|
24772
|
+
const where = schema.tables.get(table)?.find((c) => c.name === columns[0]);
|
|
24773
|
+
warnings.push(`${where ? `${where.file}:${where.line}: ` : ""}${columns.map((c) => table + "." + c).join(", ")} may hold personal data but ${columns.length === 1 ? "is" : "are"} not declared. If so, add to database.personalData: ${declared.some((t) => t.table === table) ? `the column${columns.length === 1 ? "" : "s"} under ${table}.columns` : personalDataSnippet(table, columns)}`);
|
|
24774
|
+
}
|
|
24775
|
+
return warnings;
|
|
24776
|
+
}
|
|
23079
24777
|
async function lockCommand(root, options = {}) {
|
|
23080
24778
|
const { text: text2, problems, warnings } = await generateLockfile(root);
|
|
23081
24779
|
printWarnings(warnings);
|
|
@@ -23084,7 +24782,7 @@ async function lockCommand(root, options = {}) {
|
|
|
23084
24782
|
return 1;
|
|
23085
24783
|
}
|
|
23086
24784
|
const path = join14(root, LOCKFILE_NAME);
|
|
23087
|
-
const current = existsSync11(path) ?
|
|
24785
|
+
const current = existsSync11(path) ? readFileSync16(path, "utf8").replace(/\r\n/g, "\n") : void 0;
|
|
23088
24786
|
if (options.check) {
|
|
23089
24787
|
if (current !== text2) {
|
|
23090
24788
|
console.error(`${LOCKFILE_NAME} is out of date. Run \`backify lock\` and commit the result.`);
|
|
@@ -23095,7 +24793,7 @@ async function lockCommand(root, options = {}) {
|
|
|
23095
24793
|
}
|
|
23096
24794
|
if (current === text2) console.log(`${LOCKFILE_NAME} is up to date.`);
|
|
23097
24795
|
else {
|
|
23098
|
-
|
|
24796
|
+
writeFileSync10(path, text2);
|
|
23099
24797
|
console.log(`Wrote ${LOCKFILE_NAME}.`);
|
|
23100
24798
|
}
|
|
23101
24799
|
return 0;
|
|
@@ -23118,7 +24816,7 @@ __export(check_exports, {
|
|
|
23118
24816
|
checkCommand: () => checkCommand
|
|
23119
24817
|
});
|
|
23120
24818
|
import { spawn as spawn2 } from "node:child_process";
|
|
23121
|
-
import { existsSync as existsSync12, readFileSync as
|
|
24819
|
+
import { existsSync as existsSync12, readFileSync as readFileSync17 } from "node:fs";
|
|
23122
24820
|
import { join as join15 } from "node:path";
|
|
23123
24821
|
function runScript(root, script) {
|
|
23124
24822
|
return new Promise((resolve9) => {
|
|
@@ -23128,7 +24826,7 @@ function runScript(root, script) {
|
|
|
23128
24826
|
});
|
|
23129
24827
|
}
|
|
23130
24828
|
async function checkCommand(root, options = {}) {
|
|
23131
|
-
const scripts = JSON.parse(
|
|
24829
|
+
const scripts = JSON.parse(readFileSync17(join15(root, "package.json"), "utf8")).scripts ?? {};
|
|
23132
24830
|
if (!options.skipScripts) {
|
|
23133
24831
|
for (const script of ["typecheck", "lint", "test", "build"]) {
|
|
23134
24832
|
if (!scripts[script]) continue;
|
|
@@ -23149,7 +24847,7 @@ backify check failed: npm run ${script} exited with ${code}`);
|
|
|
23149
24847
|
return 1;
|
|
23150
24848
|
}
|
|
23151
24849
|
const path = join15(root, LOCKFILE_NAME);
|
|
23152
|
-
const current = existsSync12(path) ?
|
|
24850
|
+
const current = existsSync12(path) ? readFileSync17(path, "utf8").replace(/\r\n/g, "\n") : void 0;
|
|
23153
24851
|
if (current !== text2) {
|
|
23154
24852
|
console.error(`
|
|
23155
24853
|
backify check failed: ${LOCKFILE_NAME} is ${current === void 0 ? "missing" : "out of date"}. Run \`backify lock\` and commit it.`);
|
|
@@ -23736,7 +25434,7 @@ var require_pg_int8 = __commonJS({
|
|
|
23736
25434
|
var carry;
|
|
23737
25435
|
var t;
|
|
23738
25436
|
var digits;
|
|
23739
|
-
var
|
|
25437
|
+
var pad2;
|
|
23740
25438
|
var l;
|
|
23741
25439
|
var i;
|
|
23742
25440
|
{
|
|
@@ -23748,12 +25446,12 @@ var require_pg_int8 = __commonJS({
|
|
|
23748
25446
|
if (low === 0 && high === 0) {
|
|
23749
25447
|
return sign + digits + result;
|
|
23750
25448
|
}
|
|
23751
|
-
|
|
25449
|
+
pad2 = "";
|
|
23752
25450
|
l = 6 - digits.length;
|
|
23753
25451
|
for (i = 0; i < l; i++) {
|
|
23754
|
-
|
|
25452
|
+
pad2 += "0";
|
|
23755
25453
|
}
|
|
23756
|
-
result =
|
|
25454
|
+
result = pad2 + digits + result;
|
|
23757
25455
|
}
|
|
23758
25456
|
{
|
|
23759
25457
|
carry = high % BASE;
|
|
@@ -23764,12 +25462,12 @@ var require_pg_int8 = __commonJS({
|
|
|
23764
25462
|
if (low === 0 && high === 0) {
|
|
23765
25463
|
return sign + digits + result;
|
|
23766
25464
|
}
|
|
23767
|
-
|
|
25465
|
+
pad2 = "";
|
|
23768
25466
|
l = 6 - digits.length;
|
|
23769
25467
|
for (i = 0; i < l; i++) {
|
|
23770
|
-
|
|
25468
|
+
pad2 += "0";
|
|
23771
25469
|
}
|
|
23772
|
-
result =
|
|
25470
|
+
result = pad2 + digits + result;
|
|
23773
25471
|
}
|
|
23774
25472
|
{
|
|
23775
25473
|
carry = high % BASE;
|
|
@@ -23780,12 +25478,12 @@ var require_pg_int8 = __commonJS({
|
|
|
23780
25478
|
if (low === 0 && high === 0) {
|
|
23781
25479
|
return sign + digits + result;
|
|
23782
25480
|
}
|
|
23783
|
-
|
|
25481
|
+
pad2 = "";
|
|
23784
25482
|
l = 6 - digits.length;
|
|
23785
25483
|
for (i = 0; i < l; i++) {
|
|
23786
|
-
|
|
25484
|
+
pad2 += "0";
|
|
23787
25485
|
}
|
|
23788
|
-
result =
|
|
25486
|
+
result = pad2 + digits + result;
|
|
23789
25487
|
}
|
|
23790
25488
|
{
|
|
23791
25489
|
carry = high % BASE;
|
|
@@ -24761,11 +26459,11 @@ var require_pg_connection_string = __commonJS({
|
|
|
24761
26459
|
config2.client_encoding = result.searchParams.get("encoding");
|
|
24762
26460
|
return config2;
|
|
24763
26461
|
}
|
|
24764
|
-
const
|
|
26462
|
+
const hostname3 = (dummyHost ? "" : result.hostname).replace(/^\[(.+)\]$/, "$1");
|
|
24765
26463
|
if (!config2.host) {
|
|
24766
|
-
config2.host = decodeURIComponent(
|
|
24767
|
-
} else if (
|
|
24768
|
-
result.pathname =
|
|
26464
|
+
config2.host = decodeURIComponent(hostname3);
|
|
26465
|
+
} else if (hostname3 && /^%2f/i.test(hostname3)) {
|
|
26466
|
+
result.pathname = hostname3 + result.pathname;
|
|
24769
26467
|
}
|
|
24770
26468
|
if (!config2.port) {
|
|
24771
26469
|
config2.port = result.port;
|
|
@@ -25233,23 +26931,23 @@ var require_query = __commonJS({
|
|
|
25233
26931
|
this._result.addRow(row);
|
|
25234
26932
|
}
|
|
25235
26933
|
}
|
|
25236
|
-
handleCommandComplete(msg,
|
|
26934
|
+
handleCommandComplete(msg, connection2) {
|
|
25237
26935
|
this._checkForMultirow();
|
|
25238
26936
|
this._result.addCommandComplete(msg);
|
|
25239
26937
|
if (this.rows) {
|
|
25240
|
-
|
|
26938
|
+
connection2.sync();
|
|
25241
26939
|
}
|
|
25242
26940
|
}
|
|
25243
26941
|
// if a named prepared statement is created with empty query text
|
|
25244
26942
|
// the backend will send an emptyQuery message but *not* a command complete message
|
|
25245
26943
|
// since we pipeline sync immediately after execute we don't need to do anything here
|
|
25246
26944
|
// unless we have rows specified, in which case we did not pipeline the initial sync call
|
|
25247
|
-
handleEmptyQuery(
|
|
26945
|
+
handleEmptyQuery(connection2) {
|
|
25248
26946
|
if (this.rows) {
|
|
25249
|
-
|
|
26947
|
+
connection2.sync();
|
|
25250
26948
|
}
|
|
25251
26949
|
}
|
|
25252
|
-
handleError(err,
|
|
26950
|
+
handleError(err, connection2) {
|
|
25253
26951
|
if (this._canceledDueToError) {
|
|
25254
26952
|
err = this._canceledDueToError;
|
|
25255
26953
|
this._canceledDueToError = false;
|
|
@@ -25274,11 +26972,11 @@ var require_query = __commonJS({
|
|
|
25274
26972
|
}
|
|
25275
26973
|
this.emit("end", this._results);
|
|
25276
26974
|
}
|
|
25277
|
-
submit(
|
|
26975
|
+
submit(connection2) {
|
|
25278
26976
|
if (typeof this.text !== "string" && typeof this.name !== "string") {
|
|
25279
26977
|
return new Error("A query must have either text or a name. Supplying neither is unsupported.");
|
|
25280
26978
|
}
|
|
25281
|
-
const previous =
|
|
26979
|
+
const previous = connection2.parsedStatements[this.name] || connection2.submittedNamedStatements[this.name];
|
|
25282
26980
|
if (this.text && previous && this.text !== previous) {
|
|
25283
26981
|
return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);
|
|
25284
26982
|
}
|
|
@@ -25286,48 +26984,48 @@ var require_query = __commonJS({
|
|
|
25286
26984
|
return new Error("Query values must be an array");
|
|
25287
26985
|
}
|
|
25288
26986
|
if (this.requiresPreparation()) {
|
|
25289
|
-
|
|
26987
|
+
connection2.stream.cork && connection2.stream.cork();
|
|
25290
26988
|
try {
|
|
25291
|
-
this.prepare(
|
|
26989
|
+
this.prepare(connection2);
|
|
25292
26990
|
} finally {
|
|
25293
|
-
|
|
26991
|
+
connection2.stream.uncork && connection2.stream.uncork();
|
|
25294
26992
|
}
|
|
25295
26993
|
} else {
|
|
25296
|
-
|
|
26994
|
+
connection2.query(this.text);
|
|
25297
26995
|
}
|
|
25298
26996
|
return null;
|
|
25299
26997
|
}
|
|
25300
|
-
hasBeenParsed(
|
|
25301
|
-
return this.name && (
|
|
26998
|
+
hasBeenParsed(connection2) {
|
|
26999
|
+
return this.name && (connection2.parsedStatements[this.name] !== void 0 || connection2.submittedNamedStatements[this.name] !== void 0);
|
|
25302
27000
|
}
|
|
25303
|
-
handlePortalSuspended(
|
|
25304
|
-
this._getRows(
|
|
27001
|
+
handlePortalSuspended(connection2) {
|
|
27002
|
+
this._getRows(connection2, this.rows);
|
|
25305
27003
|
}
|
|
25306
|
-
_getRows(
|
|
25307
|
-
|
|
27004
|
+
_getRows(connection2, rows) {
|
|
27005
|
+
connection2.execute({
|
|
25308
27006
|
portal: this.portal,
|
|
25309
27007
|
rows
|
|
25310
27008
|
});
|
|
25311
27009
|
if (!rows) {
|
|
25312
|
-
|
|
27010
|
+
connection2.sync();
|
|
25313
27011
|
} else {
|
|
25314
|
-
|
|
27012
|
+
connection2.flush();
|
|
25315
27013
|
}
|
|
25316
27014
|
}
|
|
25317
27015
|
// http://developer.postgresql.org/pgdocs/postgres/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY
|
|
25318
|
-
prepare(
|
|
25319
|
-
if (!this.hasBeenParsed(
|
|
25320
|
-
|
|
27016
|
+
prepare(connection2) {
|
|
27017
|
+
if (!this.hasBeenParsed(connection2)) {
|
|
27018
|
+
connection2.parse({
|
|
25321
27019
|
text: this.text,
|
|
25322
27020
|
name: this.name,
|
|
25323
27021
|
types: this.types
|
|
25324
27022
|
});
|
|
25325
27023
|
if (this.name) {
|
|
25326
|
-
|
|
27024
|
+
connection2.submittedNamedStatements[this.name] = this.text;
|
|
25327
27025
|
}
|
|
25328
27026
|
}
|
|
25329
27027
|
try {
|
|
25330
|
-
|
|
27028
|
+
connection2.bind({
|
|
25331
27029
|
portal: this.portal,
|
|
25332
27030
|
statement: this.name,
|
|
25333
27031
|
values: this.values,
|
|
@@ -25335,21 +27033,21 @@ var require_query = __commonJS({
|
|
|
25335
27033
|
valueMapper: utils.prepareValue
|
|
25336
27034
|
});
|
|
25337
27035
|
} catch (err) {
|
|
25338
|
-
|
|
25339
|
-
|
|
25340
|
-
this.handleError(err,
|
|
27036
|
+
connection2.close({ type: "S", name: this.name });
|
|
27037
|
+
connection2.sync();
|
|
27038
|
+
this.handleError(err, connection2);
|
|
25341
27039
|
return;
|
|
25342
27040
|
}
|
|
25343
|
-
|
|
27041
|
+
connection2.describe({
|
|
25344
27042
|
type: "P",
|
|
25345
27043
|
name: this.portal || ""
|
|
25346
27044
|
});
|
|
25347
|
-
this._getRows(
|
|
27045
|
+
this._getRows(connection2, this.rows);
|
|
25348
27046
|
}
|
|
25349
|
-
handleCopyInResponse(
|
|
25350
|
-
|
|
27047
|
+
handleCopyInResponse(connection2) {
|
|
27048
|
+
connection2.sendCopyFail("No source stream defined");
|
|
25351
27049
|
}
|
|
25352
|
-
handleCopyData(msg,
|
|
27050
|
+
handleCopyData(msg, connection2) {
|
|
25353
27051
|
}
|
|
25354
27052
|
};
|
|
25355
27053
|
module.exports = Query2;
|
|
@@ -28509,7 +30207,7 @@ var init_esm2 = __esm({
|
|
|
28509
30207
|
// src/app/local-postgres.ts
|
|
28510
30208
|
import { spawn as spawn3, spawnSync as spawnSync5 } from "node:child_process";
|
|
28511
30209
|
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
28512
|
-
import { existsSync as existsSync13, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as
|
|
30210
|
+
import { existsSync as existsSync13, mkdirSync as mkdirSync5, readdirSync as readdirSync5, readFileSync as readFileSync18, rmSync as rmSync2, writeFileSync as writeFileSync11 } from "node:fs";
|
|
28513
30211
|
import { createServer as createServer3 } from "node:net";
|
|
28514
30212
|
import { join as join16 } from "node:path";
|
|
28515
30213
|
function findPostgresBin() {
|
|
@@ -28542,28 +30240,30 @@ function run(bin, tool, args2) {
|
|
|
28542
30240
|
const result = spawnSync5(join16(bin, exe(tool)), args2, { encoding: "utf8", windowsHide: true });
|
|
28543
30241
|
if (result.status !== 0) throw new Error(`${tool} failed: ${(result.stderr || result.stdout || "").trim()}`);
|
|
28544
30242
|
}
|
|
28545
|
-
async function startLocalDatabase(root) {
|
|
30243
|
+
async function startLocalDatabase(root, extensions = []) {
|
|
30244
|
+
const requested = [...extensions];
|
|
30245
|
+
if (!validDatabaseExtensions(requested)) throw new Error(databaseExtensionsError);
|
|
28546
30246
|
const bin = findPostgresBin();
|
|
28547
30247
|
const home = join16(root, ".backify", "dev", "postgres");
|
|
28548
30248
|
const data = join16(home, "data");
|
|
28549
30249
|
const statePath = join16(home, "state.json");
|
|
28550
30250
|
mkdirSync5(home, { recursive: true });
|
|
28551
|
-
let state = existsSync13(statePath) ? JSON.parse(
|
|
30251
|
+
let state = existsSync13(statePath) ? JSON.parse(readFileSync18(statePath, "utf8")) : void 0;
|
|
28552
30252
|
if (!state || !existsSync13(join16(data, "PG_VERSION"))) {
|
|
28553
30253
|
rmSync2(data, { recursive: true, force: true });
|
|
28554
30254
|
state = { password: randomBytes3(24).toString("base64url"), port: await freePort(55432) };
|
|
28555
30255
|
const pwfile = join16(home, "pw.tmp");
|
|
28556
|
-
|
|
30256
|
+
writeFileSync11(pwfile, state.password, { mode: 384 });
|
|
28557
30257
|
try {
|
|
28558
30258
|
run(bin, "initdb", ["-D", data, "-U", "backify_admin", "--auth-host=scram-sha-256", "--auth-local=scram-sha-256", "--pwfile=" + pwfile, "--no-locale", "--encoding=UTF8"]);
|
|
28559
30259
|
} finally {
|
|
28560
30260
|
rmSync2(pwfile, { force: true });
|
|
28561
30261
|
}
|
|
28562
|
-
|
|
30262
|
+
writeFileSync11(statePath, JSON.stringify(state), { mode: 384 });
|
|
28563
30263
|
}
|
|
28564
30264
|
const running = spawnSync5(join16(bin, exe("pg_ctl")), ["-D", data, "status"], { stdio: "ignore", windowsHide: true }).status === 0;
|
|
28565
30265
|
const port = state.port = running ? state.port : await freePort(state.port);
|
|
28566
|
-
|
|
30266
|
+
writeFileSync11(statePath, JSON.stringify(state), { mode: 384 });
|
|
28567
30267
|
if (!running) {
|
|
28568
30268
|
await new Promise((resolve9, reject) => {
|
|
28569
30269
|
const child = spawn3(join16(bin, exe("pg_ctl")), ["-D", data, "-l", join16(home, "postgres.log"), "-o", `-h 127.0.0.1 -p ${port}`, "-w", "start"], { stdio: "ignore", windowsHide: true, detached: process.platform !== "win32" });
|
|
@@ -28573,46 +30273,100 @@ async function startLocalDatabase(root) {
|
|
|
28573
30273
|
}
|
|
28574
30274
|
const url2 = (user, password, database) => `postgres://${user}:${encodeURIComponent(password)}@127.0.0.1:${port}/${database}`;
|
|
28575
30275
|
const admin = url2("backify_admin", state.password, "postgres");
|
|
28576
|
-
const
|
|
28577
|
-
|
|
30276
|
+
const adminApp = url2("backify_admin", state.password, "app");
|
|
30277
|
+
const stop = async () => {
|
|
30278
|
+
spawnSync5(join16(bin, exe("pg_ctl")), ["-D", data, "-m", "fast", "-w", "stop"], { stdio: "ignore", windowsHide: true });
|
|
30279
|
+
};
|
|
28578
30280
|
try {
|
|
28579
|
-
|
|
28580
|
-
|
|
28581
|
-
|
|
28582
|
-
|
|
28583
|
-
|
|
28584
|
-
|
|
28585
|
-
|
|
28586
|
-
|
|
28587
|
-
await client.query("
|
|
28588
|
-
|
|
28589
|
-
|
|
28590
|
-
await
|
|
30281
|
+
const client = new esm_default.Client({ connectionString: admin });
|
|
30282
|
+
await client.connect();
|
|
30283
|
+
try {
|
|
30284
|
+
for (const [role, limit] of roles) {
|
|
30285
|
+
const exists = await client.query("SELECT 1 FROM pg_roles WHERE rolname = $1", [role]);
|
|
30286
|
+
const password = state.password.replace(/[^A-Za-z0-9]/g, "") + role;
|
|
30287
|
+
if (!exists.rowCount) await client.query(`CREATE ROLE ${role} LOGIN PASSWORD '${password}' CONNECTION LIMIT ${limit}`);
|
|
30288
|
+
}
|
|
30289
|
+
if (!(await client.query("SELECT 1 FROM pg_database WHERE datname = 'app'")).rowCount)
|
|
30290
|
+
await client.query("CREATE DATABASE app OWNER app_migrate");
|
|
30291
|
+
} finally {
|
|
30292
|
+
await client.end();
|
|
28591
30293
|
}
|
|
28592
|
-
|
|
28593
|
-
|
|
30294
|
+
await configureAppDatabase(adminApp, requested);
|
|
30295
|
+
} catch (error2) {
|
|
30296
|
+
if (!running) await stop();
|
|
30297
|
+
throw error2;
|
|
28594
30298
|
}
|
|
28595
30299
|
const rolePassword = (role) => state.password.replace(/[^A-Za-z0-9]/g, "") + role;
|
|
28596
30300
|
return {
|
|
28597
30301
|
port,
|
|
28598
30302
|
urls: { admin, migrate: url2("app_migrate", rolePassword("app_migrate"), "app"), runtime: url2("app_runtime", rolePassword("app_runtime"), "app"), inspect: url2("app_inspect", rolePassword("app_inspect"), "app") },
|
|
28599
|
-
stop
|
|
28600
|
-
spawnSync5(join16(bin, exe("pg_ctl")), ["-D", data, "-m", "fast", "-w", "stop"], { stdio: "ignore", windowsHide: true });
|
|
28601
|
-
}
|
|
30303
|
+
stop
|
|
28602
30304
|
};
|
|
28603
30305
|
}
|
|
28604
|
-
|
|
30306
|
+
async function configureAppDatabase(url2, extensions) {
|
|
30307
|
+
const client = new esm_default.Client({ connectionString: url2 });
|
|
30308
|
+
await client.connect();
|
|
30309
|
+
try {
|
|
30310
|
+
await client.query(`
|
|
30311
|
+
BEGIN;
|
|
30312
|
+
SET LOCAL search_path = pg_catalog;
|
|
30313
|
+
SELECT pg_advisory_xact_lock(173540, 2);
|
|
30314
|
+
`);
|
|
30315
|
+
if (extensions.length) await client.query("ALTER DATABASE app OWNER TO backify_admin");
|
|
30316
|
+
await client.query(`
|
|
30317
|
+
REVOKE ALL ON DATABASE app FROM PUBLIC;
|
|
30318
|
+
GRANT CONNECT ON DATABASE app TO app_migrate, app_runtime, app_inspect;
|
|
30319
|
+
GRANT TEMPORARY ON DATABASE app TO app_migrate;
|
|
30320
|
+
REVOKE ALL ON SCHEMA public FROM PUBLIC;
|
|
30321
|
+
ALTER SCHEMA public OWNER TO app_migrate;
|
|
30322
|
+
CREATE SCHEMA IF NOT EXISTS backify_runtime AUTHORIZATION app_migrate;
|
|
30323
|
+
`);
|
|
30324
|
+
if (extensions.length) {
|
|
30325
|
+
await client.query("CREATE SCHEMA IF NOT EXISTS backify_extensions");
|
|
30326
|
+
const schema = await client.query(`
|
|
30327
|
+
SELECT nspowner = current_user::regrole AND NOT EXISTS (
|
|
30328
|
+
SELECT FROM aclexplode(nspacl) WHERE privilege_type = 'CREATE' AND grantee <> nspowner
|
|
30329
|
+
) AS protected
|
|
30330
|
+
FROM pg_namespace WHERE nspname = 'backify_extensions'
|
|
30331
|
+
`);
|
|
30332
|
+
if (!schema.rows[0]?.protected) throw new Error("The backify_extensions schema must be owned by the local provisioning role and writable only by that role.");
|
|
30333
|
+
for (const extension of [...extensions].sort()) {
|
|
30334
|
+
const installed = await client.query(`
|
|
30335
|
+
SELECT n.nspname = 'backify_extensions' AND e.extowner = current_user::regrole AS managed
|
|
30336
|
+
FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = $1
|
|
30337
|
+
`, [extension]);
|
|
30338
|
+
if (installed.rows[0]?.managed === false)
|
|
30339
|
+
throw new Error(`PostgreSQL extension '${extension}' is already installed outside Backify's managed schema or ownership. Review it before starting the app.`);
|
|
30340
|
+
if (installed.rowCount) continue;
|
|
30341
|
+
try {
|
|
30342
|
+
await client.query(`CREATE EXTENSION ${esm_default.escapeIdentifier(extension)} WITH SCHEMA backify_extensions`);
|
|
30343
|
+
} catch (error2) {
|
|
30344
|
+
throw new Error(`Could not install PostgreSQL extension '${extension}'. Verify that its supporting files are installed for the PostgreSQL server used by backify dev.`, { cause: error2 });
|
|
30345
|
+
}
|
|
30346
|
+
}
|
|
30347
|
+
await client.query("GRANT USAGE ON SCHEMA backify_extensions TO app_migrate, app_runtime, app_inspect");
|
|
30348
|
+
for (const [role] of roles)
|
|
30349
|
+
await client.query(`ALTER ROLE ${role} IN DATABASE app SET search_path TO public, backify_extensions`);
|
|
30350
|
+
}
|
|
30351
|
+
await client.query("COMMIT");
|
|
30352
|
+
} finally {
|
|
30353
|
+
await client.end();
|
|
30354
|
+
}
|
|
30355
|
+
}
|
|
30356
|
+
var exe, roles;
|
|
28605
30357
|
var init_local_postgres = __esm({
|
|
28606
30358
|
"src/app/local-postgres.ts"() {
|
|
28607
30359
|
"use strict";
|
|
30360
|
+
init_dist();
|
|
28608
30361
|
init_esm2();
|
|
28609
30362
|
exe = (name2) => process.platform === "win32" ? name2 + ".exe" : name2;
|
|
30363
|
+
roles = [["app_migrate", 2], ["app_runtime", 10], ["app_inspect", 3]];
|
|
28610
30364
|
}
|
|
28611
30365
|
});
|
|
28612
30366
|
|
|
28613
30367
|
// src/app/local-gateway.ts
|
|
28614
30368
|
import { createHmac, generateKeyPairSync, randomBytes as randomBytes4, sign as rsaSign, timingSafeEqual } from "node:crypto";
|
|
28615
|
-
import { createReadStream, existsSync as existsSync14, mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as
|
|
30369
|
+
import { createReadStream, existsSync as existsSync14, mkdirSync as mkdirSync6, readdirSync as readdirSync6, readFileSync as readFileSync19, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync12 } from "node:fs";
|
|
28616
30370
|
import { createServer as createServer4, request as httpRequest } from "node:http";
|
|
28617
30371
|
import { connect } from "node:net";
|
|
28618
30372
|
import { dirname as dirname7, join as join17, relative as relative3, resolve as resolve7, sep } from "node:path";
|
|
@@ -28779,7 +30533,7 @@ function startGateway(options) {
|
|
|
28779
30533
|
}
|
|
28780
30534
|
function sendFile(res, path, contentType2) {
|
|
28781
30535
|
if (!existsSync14(path) || !statSync2(path).isFile()) return json(res, 404, { error: { code: "not_found", message: "Not found" } });
|
|
28782
|
-
const meta2 = existsSync14(path + ".meta.json") ? JSON.parse(
|
|
30536
|
+
const meta2 = existsSync14(path + ".meta.json") ? JSON.parse(readFileSync19(path + ".meta.json", "utf8")) : {};
|
|
28783
30537
|
res.writeHead(200, { "content-type": contentType2 ?? meta2.contentType ?? "application/octet-stream" });
|
|
28784
30538
|
createReadStream(path).pipe(res);
|
|
28785
30539
|
}
|
|
@@ -28804,7 +30558,7 @@ function startGateway(options) {
|
|
|
28804
30558
|
return res.end();
|
|
28805
30559
|
}
|
|
28806
30560
|
if (action === "login") {
|
|
28807
|
-
const
|
|
30561
|
+
const roles2 = (config2.auth?.roles ?? []).join(", ");
|
|
28808
30562
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
28809
30563
|
return res.end(`<!doctype html><meta name="viewport" content="width=device-width"><title>Sign in (local)</title>
|
|
28810
30564
|
<body style="font-family:system-ui;max-width:420px;margin:4rem auto;padding:0 16px">
|
|
@@ -28812,7 +30566,7 @@ function startGateway(options) {
|
|
|
28812
30566
|
<form method="post"><input type="hidden" name="returnTo" value="${returnTo.replace(/"/g, """)}">
|
|
28813
30567
|
<p><label>Email<br><input name="email" type="email" required autofocus style="width:100%"></label></p>
|
|
28814
30568
|
<p><label>Name<br><input name="name" style="width:100%"></label></p>
|
|
28815
|
-
<p><label>Roles (comma separated)${
|
|
30569
|
+
<p><label>Roles (comma separated)${roles2 ? ` \u2014 declared: ${roles2}` : ""}<br><input name="roles" style="width:100%"></label></p>
|
|
28816
30570
|
<p><label>Permissions (comma separated)<br><input name="permissions" style="width:100%"></label></p>
|
|
28817
30571
|
<button>Sign in</button></form></body>`);
|
|
28818
30572
|
}
|
|
@@ -28856,14 +30610,13 @@ function startGateway(options) {
|
|
|
28856
30610
|
}
|
|
28857
30611
|
if (path === "/v1/mail/send") {
|
|
28858
30612
|
const id = "mail_" + randomBytes4(6).toString("hex");
|
|
28859
|
-
|
|
30613
|
+
writeFileSync12(join17(mailDir, id + ".json"), JSON.stringify(body, null, 2));
|
|
28860
30614
|
options.log(`mail to ${JSON.stringify(body.to)}: "${String(body.subject)}" (saved in .backify/dev/mail/${id}.json)`);
|
|
28861
30615
|
return json(res, 200, { id, status: "sent", from: "noreply@localhost" });
|
|
28862
30616
|
}
|
|
28863
30617
|
if (path === "/v1/http/fetch") {
|
|
28864
30618
|
const target = new URL(String(body.url));
|
|
28865
|
-
|
|
28866
|
-
if (!allowed || target.protocol !== "https:") return brokerError(res, 403, "host_not_allowed", `${target.hostname} is not in backify.config.ts http.allow (https only)`);
|
|
30619
|
+
if (target.protocol !== "https:") return brokerError(res, 403, "https_required", `Outbound HTTP to ${target.hostname} must use https`);
|
|
28867
30620
|
const response = await fetch(target, { method: String(body.method ?? "GET"), headers: body.headers, body: body.body, signal: AbortSignal.timeout(Number(body.timeoutSeconds ?? 30) * 1e3) });
|
|
28868
30621
|
const bytes = Buffer.from(await response.arrayBuffer());
|
|
28869
30622
|
return json(res, 200, { status: response.status, headers: Object.fromEntries(response.headers), body: bytes.toString("base64"), encoding: "base64" });
|
|
@@ -28891,8 +30644,8 @@ function startGateway(options) {
|
|
|
28891
30644
|
const path = objectPath(bucket, key.join("/"));
|
|
28892
30645
|
if (req.method === "PUT") {
|
|
28893
30646
|
mkdirSync6(dirname7(path), { recursive: true });
|
|
28894
|
-
|
|
28895
|
-
|
|
30647
|
+
writeFileSync12(path, await readBody(req));
|
|
30648
|
+
writeFileSync12(path + ".meta.json", JSON.stringify({ contentType: req.headers["content-type"] }));
|
|
28896
30649
|
res.writeHead(201);
|
|
28897
30650
|
return res.end();
|
|
28898
30651
|
}
|
|
@@ -28910,8 +30663,8 @@ function startGateway(options) {
|
|
|
28910
30663
|
const path = objectPath(grant.bucket, grant.key);
|
|
28911
30664
|
if (grant.operation === "upload" && req.method === "PUT") {
|
|
28912
30665
|
mkdirSync6(dirname7(path), { recursive: true });
|
|
28913
|
-
|
|
28914
|
-
|
|
30666
|
+
writeFileSync12(path, await readBody(req));
|
|
30667
|
+
writeFileSync12(path + ".meta.json", JSON.stringify({ contentType: grant.contentType ?? req.headers["content-type"] }));
|
|
28915
30668
|
res.writeHead(201);
|
|
28916
30669
|
return res.end();
|
|
28917
30670
|
}
|
|
@@ -28946,7 +30699,7 @@ __export(dev_exports, {
|
|
|
28946
30699
|
});
|
|
28947
30700
|
import { spawn as spawn4 } from "node:child_process";
|
|
28948
30701
|
import { randomBytes as randomBytes5 } from "node:crypto";
|
|
28949
|
-
import { existsSync as existsSync15, readFileSync as
|
|
30702
|
+
import { existsSync as existsSync15, readFileSync as readFileSync20, watch } from "node:fs";
|
|
28950
30703
|
import { join as join18, resolve as resolve8 } from "node:path";
|
|
28951
30704
|
import { context } from "esbuild";
|
|
28952
30705
|
function prefixOutput(child, label, code) {
|
|
@@ -28974,7 +30727,7 @@ function prettyLog(line) {
|
|
|
28974
30727
|
function localSecrets(root) {
|
|
28975
30728
|
const path = join18(root, ".backify", "secrets.local.json");
|
|
28976
30729
|
if (!existsSync15(path)) return {};
|
|
28977
|
-
const values = JSON.parse(
|
|
30730
|
+
const values = JSON.parse(readFileSync20(path, "utf8"));
|
|
28978
30731
|
return Object.fromEntries(Object.entries(values).map(([k, v]) => ["BACKIFY_SECRET_" + k, String(v)]));
|
|
28979
30732
|
}
|
|
28980
30733
|
async function devCommand(rootArg, options = {}) {
|
|
@@ -28984,7 +30737,7 @@ async function devCommand(rootArg, options = {}) {
|
|
|
28984
30737
|
const capabilities = configuredCapabilities(config2);
|
|
28985
30738
|
const needsDatabase = Boolean(config2.server);
|
|
28986
30739
|
say("backify", `Starting ${config2.app.name} (${config2.kind})`, 35);
|
|
28987
|
-
const database = needsDatabase ? await startLocalDatabase(root) : void 0;
|
|
30740
|
+
const database = needsDatabase ? await startLocalDatabase(root, config2.database?.extensions) : void 0;
|
|
28988
30741
|
if (database) say("db", `PostgreSQL on 127.0.0.1:${database.port} (data in .backify/dev/postgres)`, 34);
|
|
28989
30742
|
const gatewayPort = options.port ?? await freePort(3e3);
|
|
28990
30743
|
const identity = createDevIdentity("local", "local");
|
|
@@ -29307,32 +31060,32 @@ async function diagnoseEnvironment(root = process.cwd(), options = {}, probes =
|
|
|
29307
31060
|
|
|
29308
31061
|
// src/integrations.ts
|
|
29309
31062
|
function integrationDiscoveryPath(command2, options) {
|
|
29310
|
-
const
|
|
29311
|
-
if (!
|
|
31063
|
+
const uuid9 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
31064
|
+
if (!uuid9.test(options.applicationId)) throw new Error("An application UUID is required");
|
|
29312
31065
|
const base = "/apps/" + options.applicationId + "/integrations/connectors";
|
|
29313
31066
|
if (command2 === "list") return base;
|
|
29314
31067
|
if (command2 === "catalog") return "/apps/" + options.applicationId + "/integrations/catalog";
|
|
29315
31068
|
if (command2 === "discover") return "/apps/" + options.applicationId + "/integrations/discover?" + new URLSearchParams({ query: options.query ?? "" });
|
|
29316
31069
|
if (command2 === "prepare") return "/apps/" + options.applicationId + "/integrations/prepare";
|
|
29317
31070
|
if (command2 === "contract" && options.revisionId) {
|
|
29318
|
-
if (!
|
|
31071
|
+
if (!uuid9.test(options.revisionId)) throw new Error("Use --revision with a discovered revision UUID");
|
|
29319
31072
|
return "/apps/" + options.applicationId + "/integrations/definitions/" + options.revisionId;
|
|
29320
31073
|
}
|
|
29321
31074
|
if (command2 === "status") {
|
|
29322
|
-
if (!options.adoptionId || !
|
|
31075
|
+
if (!options.adoptionId || !uuid9.test(options.adoptionId)) throw new Error("Use --adoption with an adoption request UUID");
|
|
29323
31076
|
return "/apps/" + options.applicationId + "/integrations/adoptions/" + options.adoptionId;
|
|
29324
31077
|
}
|
|
29325
|
-
if (!options.connectionId || !
|
|
29326
|
-
const
|
|
29327
|
-
if (command2 === "contract" || command2 === "types") return
|
|
31078
|
+
if (!options.connectionId || !uuid9.test(options.connectionId)) throw new Error("Use --connection with an integration connection UUID");
|
|
31079
|
+
const connection2 = base + "/" + options.connectionId;
|
|
31080
|
+
if (command2 === "contract" || command2 === "types") return connection2 + "/" + command2;
|
|
29328
31081
|
if (command2 === "describe") {
|
|
29329
31082
|
if (!options.operationId) throw new Error("Use --operation to select an operation");
|
|
29330
|
-
return
|
|
31083
|
+
return connection2 + "/operations/" + encodeURIComponent(options.operationId);
|
|
29331
31084
|
}
|
|
29332
31085
|
if (command2 === "search") {
|
|
29333
31086
|
if (!Number.isInteger(options.offset ?? 0) || (options.offset ?? 0) < 0 || (options.offset ?? 0) > 500) throw new Error("Offset must be between 0 and 500");
|
|
29334
31087
|
const query = new URLSearchParams({ query: options.query ?? "", offset: String(options.offset ?? 0), limit: "50" });
|
|
29335
|
-
return
|
|
31088
|
+
return connection2 + "/operations?" + query;
|
|
29336
31089
|
}
|
|
29337
31090
|
throw new Error("Use backify integrations discover|prepare|status|list|catalog|search|describe|contract|types");
|
|
29338
31091
|
}
|
|
@@ -29362,7 +31115,7 @@ function portalOrigin(value) {
|
|
|
29362
31115
|
}
|
|
29363
31116
|
function reviewUrl(origin, app, status) {
|
|
29364
31117
|
const url2 = new URL(status.reviewPath, origin);
|
|
29365
|
-
if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/
|
|
31118
|
+
if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/setup/integrations/" + 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 integration review link.");
|
|
29366
31119
|
return url2.href;
|
|
29367
31120
|
}
|
|
29368
31121
|
async function connectIntegration(call2, options) {
|
|
@@ -29475,100 +31228,66 @@ function integrationConnectArguments(args2) {
|
|
|
29475
31228
|
}
|
|
29476
31229
|
|
|
29477
31230
|
// src/domain-connect.ts
|
|
31231
|
+
init_human_task();
|
|
29478
31232
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
29479
|
-
import { setTimeout as delay2 } from "node:timers/promises";
|
|
29480
31233
|
import { domainToASCII } from "node:url";
|
|
29481
31234
|
var domainConnectHelp = `backify domains connect [hostname] [--app <application>] [--environment preview|production]
|
|
29482
31235
|
backify domains connect --request <UUID> [--app <application>]
|
|
29483
31236
|
Options: --hostname <hostname> --no-browser --no-wait --timeout <seconds, 1-3600> --json
|
|
29484
|
-
|
|
29485
|
-
as the domain is confirmed. It does not wait for DNS: Backify verifies the DNS records, issues managed HTTPS and starts
|
|
31237
|
+
Requests a Backify task and opens its page, where an authorized user signs in
|
|
31238
|
+
and confirms the hostname and environment. Returns as soon as the domain is confirmed. It does not wait for DNS: Backify verifies the DNS records, issues managed HTTPS and starts
|
|
29486
31239
|
routing automatically once the user adds them. Exit code 0 means confirmed; 2 means not yet confirmed or blocked.
|
|
29487
|
-
Re-run with --request to read the current status without reopening the browser.`;
|
|
29488
|
-
var
|
|
31240
|
+
Re-run with --request <task-id> to read the current status without reopening the browser.`;
|
|
31241
|
+
var kind = "domain.confirm";
|
|
31242
|
+
var uuid4 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
|
29489
31243
|
var confirmedStates = ["dns_required", "certificate_pending", "ready"];
|
|
29490
31244
|
function customHostname(input) {
|
|
29491
|
-
const
|
|
29492
|
-
if (/[\s:/\\@?#%*]/.test(input.trim()) ||
|
|
29493
|
-
return
|
|
29494
|
-
}
|
|
29495
|
-
function portalOrigin2(input) {
|
|
29496
|
-
const url2 = new URL(input);
|
|
29497
|
-
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.");
|
|
29498
|
-
return url2.origin;
|
|
31245
|
+
const hostname3 = domainToASCII(input.trim().replace(/\.$/, "")).toLowerCase(), labels = hostname3.split(".");
|
|
31246
|
+
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.");
|
|
31247
|
+
return hostname3;
|
|
29499
31248
|
}
|
|
29500
31249
|
function validate(status, app) {
|
|
29501
|
-
if (!
|
|
31250
|
+
if (!uuid4.test(status.id) || status.applicationId !== app || !["review_required", "dns_required", "certificate_pending", "ready", "blocked"].includes(status.state) || status.domainId !== null && !uuid4.test(status.domainId)) throw new Error("The server returned invalid domain setup metadata.");
|
|
29502
31251
|
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.");
|
|
29503
31252
|
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.");
|
|
29504
31253
|
}
|
|
29505
|
-
function
|
|
29506
|
-
|
|
29507
|
-
if (
|
|
29508
|
-
|
|
31254
|
+
function checked(task, app) {
|
|
31255
|
+
validateHumanTask(task, kind, app);
|
|
31256
|
+
if (task.result) validate(task.result, app);
|
|
31257
|
+
else if (task.state === "pending" || task.state === "completed") throw new Error("The server returned invalid domain setup metadata.");
|
|
31258
|
+
return task;
|
|
29509
31259
|
}
|
|
29510
31260
|
async function connectDomain(call2, options) {
|
|
29511
|
-
const app = options.applicationId.toLowerCase()
|
|
29512
|
-
if (!
|
|
31261
|
+
const app = options.applicationId.toLowerCase();
|
|
31262
|
+
if (!uuid4.test(app) || options.requestId && !uuid4.test(options.requestId)) throw new Error("Use valid application and domain setup request IDs.");
|
|
29513
31263
|
if (options.environment && !["preview", "production"].includes(options.environment)) throw new Error("Use --environment preview|production, or choose in the browser.");
|
|
29514
|
-
|
|
29515
|
-
const
|
|
29516
|
-
const
|
|
29517
|
-
|
|
29518
|
-
|
|
29519
|
-
|
|
29520
|
-
|
|
29521
|
-
|
|
29522
|
-
|
|
29523
|
-
requestId: status.id,
|
|
31264
|
+
const hostname3 = options.hostname === void 0 ? void 0 : customHostname(options.hostname);
|
|
31265
|
+
const initial = checked(options.requestId ? await readHumanTask(call2, options.requestId) : await requestHumanTask(call2, kind, { applicationId: app, hostname: hostname3 ?? null, environment: options.environment ?? null, requestKey: randomUUID2() }), app);
|
|
31266
|
+
const { status: task, link, reason } = await waitForHumanTask(initial, async () => checked(await readHumanTask(call2, initial.id), app), options, "sign in and confirm the custom domain");
|
|
31267
|
+
const status = task.result;
|
|
31268
|
+
return {
|
|
31269
|
+
state: status?.state ?? task.state,
|
|
31270
|
+
taskState: task.state,
|
|
31271
|
+
confirmed: task.state === "completed" && confirmedStates.includes(status?.state ?? ""),
|
|
31272
|
+
requestId: task.id,
|
|
29524
31273
|
applicationId: app,
|
|
29525
|
-
domainId: status
|
|
29526
|
-
hostname: status
|
|
29527
|
-
environment: status
|
|
29528
|
-
verificationStatus: status
|
|
29529
|
-
certificateStatus: status
|
|
29530
|
-
bindingStatus: status
|
|
31274
|
+
domainId: status?.domainId ?? null,
|
|
31275
|
+
hostname: status?.hostname ?? null,
|
|
31276
|
+
environment: status?.environment ?? null,
|
|
31277
|
+
verificationStatus: status?.verificationStatus ?? null,
|
|
31278
|
+
certificateStatus: status?.certificateStatus ?? null,
|
|
31279
|
+
bindingStatus: status?.bindingStatus ?? null,
|
|
29531
31280
|
setupUrl: link,
|
|
29532
|
-
nextAction:
|
|
31281
|
+
nextAction: task.nextAction,
|
|
29533
31282
|
// The address the domain will serve once DNS is verified; `url` is set only when it already does.
|
|
29534
|
-
expectedUrl: status
|
|
29535
|
-
url: status
|
|
31283
|
+
expectedUrl: status?.hostname ? "https://" + status.hostname : null,
|
|
31284
|
+
url: status?.state === "ready" ? status.url : null,
|
|
29536
31285
|
...reason ? { reason } : {}
|
|
29537
|
-
}
|
|
29538
|
-
if (status.state !== "review_required") return result();
|
|
29539
|
-
if (options.signal?.aborted) return result("cancelled");
|
|
29540
|
-
options.progress?.("Open this page to sign in and confirm the custom domain:\n" + link);
|
|
29541
|
-
if (!options.noBrowser) {
|
|
29542
|
-
try {
|
|
29543
|
-
options.openBrowser(link);
|
|
29544
|
-
} catch {
|
|
29545
|
-
options.progress?.("Automatic browser launch failed. Open the setup URL manually.");
|
|
29546
|
-
}
|
|
29547
|
-
}
|
|
29548
|
-
if (options.noWait) return result("waiting_in_browser");
|
|
29549
|
-
options.progress?.("Waiting for confirmation in the browser\u2026");
|
|
29550
|
-
while (true) {
|
|
29551
|
-
if (status.state !== "review_required") {
|
|
29552
|
-
options.progress?.(status.nextAction);
|
|
29553
|
-
return result();
|
|
29554
|
-
}
|
|
29555
|
-
if (options.signal?.aborted) return result("cancelled");
|
|
29556
|
-
if (now() >= deadline) return result("timed_out");
|
|
29557
|
-
try {
|
|
29558
|
-
await (options.sleep ?? ((ms) => delay2(ms, void 0, { signal: options.signal })))(Math.min(3e3, deadline - now()));
|
|
29559
|
-
} catch (error2) {
|
|
29560
|
-
if (options.signal?.aborted) return result("cancelled");
|
|
29561
|
-
throw error2;
|
|
29562
|
-
}
|
|
29563
|
-
if (options.signal?.aborted) return result("cancelled");
|
|
29564
|
-
status = await call2(base + "/" + status.id);
|
|
29565
|
-
validate(status, app);
|
|
29566
|
-
if (reviewUrl2(origin, app, status) !== link) throw new Error("The domain setup request changed while waiting.");
|
|
29567
|
-
}
|
|
31286
|
+
};
|
|
29568
31287
|
}
|
|
29569
31288
|
function domainConnectArguments(args2) {
|
|
29570
31289
|
const values = {}, flags = /* @__PURE__ */ new Set();
|
|
29571
|
-
let
|
|
31290
|
+
let hostname3;
|
|
29572
31291
|
for (let i = 0; i < args2.length; i++) {
|
|
29573
31292
|
const value = args2[i];
|
|
29574
31293
|
if (["--json", "--no-browser", "--no-wait"].includes(value)) {
|
|
@@ -29577,13 +31296,13 @@ function domainConnectArguments(args2) {
|
|
|
29577
31296
|
} else if (["--app", "--hostname", "--environment", "--request", "--timeout"].includes(value)) {
|
|
29578
31297
|
if (value in values || !args2[i + 1] || args2[i + 1].startsWith("--")) throw new Error("Specify one value for " + value);
|
|
29579
31298
|
values[value] = args2[++i];
|
|
29580
|
-
} else if (value.startsWith("--") ||
|
|
29581
|
-
else
|
|
31299
|
+
} else if (value.startsWith("--") || hostname3) throw new Error("Unknown domains connect argument: " + value);
|
|
31300
|
+
else hostname3 = value;
|
|
29582
31301
|
}
|
|
29583
|
-
if (
|
|
29584
|
-
|
|
29585
|
-
if (values["--request"] && (
|
|
29586
|
-
return { hostname:
|
|
31302
|
+
if (hostname3 && values["--hostname"]) throw new Error("Specify the hostname once.");
|
|
31303
|
+
hostname3 ??= values["--hostname"];
|
|
31304
|
+
if (values["--request"] && (hostname3 || values["--environment"])) throw new Error("Resume with --request; do not change its hostname or environment.");
|
|
31305
|
+
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 };
|
|
29587
31306
|
}
|
|
29588
31307
|
|
|
29589
31308
|
// src/auth-setup.ts
|
|
@@ -29598,7 +31317,7 @@ on the Backify auth host. Client IDs and secrets are entered there, never in the
|
|
|
29598
31317
|
provider has a setting in every environment. Email and passkeys need no configuration, so a request for only those
|
|
29599
31318
|
completes at once. Exit code 0 means completed; 2 means setup is still required or blocked. Re-run with --request
|
|
29600
31319
|
to read the status without reopening the browser.`;
|
|
29601
|
-
var
|
|
31320
|
+
var uuid5 = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
|
|
29602
31321
|
function authOrigin(input) {
|
|
29603
31322
|
const url2 = new URL(input);
|
|
29604
31323
|
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 auth origin, or an explicit loopback development origin.");
|
|
@@ -29607,7 +31326,7 @@ function authOrigin(input) {
|
|
|
29607
31326
|
function setupUrl(origin, app, status) {
|
|
29608
31327
|
if (!status.setupPath || !status.id) throw new Error("The server returned no sign-in setup link.");
|
|
29609
31328
|
const url2 = new URL(status.setupPath, origin);
|
|
29610
|
-
if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/setup/auth/" + app + "/" + status.id.toLowerCase() || [...url2.searchParams.keys()].join() !== "organization" || !
|
|
31329
|
+
if (url2.origin !== origin || url2.pathname.toLowerCase() !== "/setup/auth/" + app + "/" + status.id.toLowerCase() || [...url2.searchParams.keys()].join() !== "organization" || !uuid5.test(url2.searchParams.get("organization")) || url2.username || url2.password || url2.hash)
|
|
29611
31330
|
throw new Error("The server returned an invalid sign-in setup link.");
|
|
29612
31331
|
return url2.href;
|
|
29613
31332
|
}
|
|
@@ -29620,7 +31339,7 @@ function configuredProviders(values) {
|
|
|
29620
31339
|
}
|
|
29621
31340
|
async function setupAuth(call2, options) {
|
|
29622
31341
|
const app = options.applicationId.toLowerCase(), timeout = options.timeoutMs ?? 9e5;
|
|
29623
|
-
if (!
|
|
31342
|
+
if (!uuid5.test(app) || options.requestId && !uuid5.test(options.requestId)) throw new Error("Use valid application and sign-in setup request IDs.");
|
|
29624
31343
|
if (!Number.isFinite(timeout) || timeout < 1e3 || timeout > 36e5) throw new Error("Use --timeout between 1 and 3600 seconds.");
|
|
29625
31344
|
const origin = authOrigin(options.authUrl), now = options.now ?? Date.now, deadline = now() + timeout;
|
|
29626
31345
|
const base = "/apps/" + app + "/auth/setup/requests";
|
|
@@ -29695,6 +31414,121 @@ function authSetupArguments(args2) {
|
|
|
29695
31414
|
};
|
|
29696
31415
|
}
|
|
29697
31416
|
|
|
31417
|
+
// src/privacy-requests.ts
|
|
31418
|
+
var privacyRequestsUsage = [
|
|
31419
|
+
"Use backify privacy requests <action> [--app <application-id>]:",
|
|
31420
|
+
" list [--status active|open|in-progress|completed|rejected]",
|
|
31421
|
+
" show <request-id>",
|
|
31422
|
+
" create --type access|portability|rectification|erasure --subject-kind auth-user|email|external-id --subject <value>",
|
|
31423
|
+
" --verified-by account|email|phone|in-person|other [--note <text>] [--received <ISO date>] [--environment <UUID>]",
|
|
31424
|
+
" update <request-id> [--status open|in-progress] [--assignee me|none|<user-id>] [--extend 1|2 --reason <text>]",
|
|
31425
|
+
" close <request-id> --outcome completed|rejected [--note <text>]",
|
|
31426
|
+
" preview <request-id>",
|
|
31427
|
+
"Never put identity documents in notes."
|
|
31428
|
+
].join("\n");
|
|
31429
|
+
var guid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
31430
|
+
function privacyRequestCall(appId, args2) {
|
|
31431
|
+
const option2 = (name2) => {
|
|
31432
|
+
const index = args2.indexOf(name2);
|
|
31433
|
+
return index >= 0 ? args2[index + 1] : void 0;
|
|
31434
|
+
};
|
|
31435
|
+
const [area, action, id] = args2;
|
|
31436
|
+
if (area !== "requests" || !action) throw new Error(privacyRequestsUsage);
|
|
31437
|
+
const base = `/apps/${appId}/compliance/requests`;
|
|
31438
|
+
const request = () => {
|
|
31439
|
+
if (!id || !guid.test(id)) throw new Error(`Give the request ID: backify privacy requests ${action} <request-id>.`);
|
|
31440
|
+
return `${base}/${id}`;
|
|
31441
|
+
};
|
|
31442
|
+
switch (action) {
|
|
31443
|
+
case "list": {
|
|
31444
|
+
const status = option2("--status");
|
|
31445
|
+
return { method: "GET", path: status ? `${base}?status=${encodeURIComponent(status)}` : base };
|
|
31446
|
+
}
|
|
31447
|
+
case "show":
|
|
31448
|
+
return { method: "GET", path: request() };
|
|
31449
|
+
case "preview":
|
|
31450
|
+
return { method: "GET", path: request() + "/preview" };
|
|
31451
|
+
case "create": {
|
|
31452
|
+
const type = option2("--type"), subjectKind = option2("--subject-kind"), subject = option2("--subject"), verificationMethod = option2("--verified-by");
|
|
31453
|
+
if (!type || !subjectKind || !subject || !verificationMethod) throw new Error("Specify --type, --subject-kind, --subject and --verified-by.\n" + privacyRequestsUsage);
|
|
31454
|
+
const environment = option2("--environment");
|
|
31455
|
+
if (environment !== void 0 && !guid.test(environment)) throw new Error("--environment must be an environment UUID.");
|
|
31456
|
+
return { method: "POST", path: base, body: { type, subjectKind, subject, verificationMethod, verificationNote: option2("--note"), receivedAt: option2("--received"), environmentId: environment } };
|
|
31457
|
+
}
|
|
31458
|
+
case "update": {
|
|
31459
|
+
const extend2 = option2("--extend");
|
|
31460
|
+
const body = { status: option2("--status"), assignee: option2("--assignee"), extendMonths: extend2 === void 0 ? void 0 : Number(extend2), extensionReason: option2("--reason") };
|
|
31461
|
+
if (extend2 !== void 0 && !/^[12]$/.test(extend2)) throw new Error("--extend takes 1 or 2 (months).");
|
|
31462
|
+
if (Object.values(body).every((value) => value === void 0)) throw new Error("Specify --status, --assignee or --extend with --reason.");
|
|
31463
|
+
return { method: "PATCH", path: request(), body };
|
|
31464
|
+
}
|
|
31465
|
+
case "close": {
|
|
31466
|
+
const outcome = option2("--outcome");
|
|
31467
|
+
if (outcome !== "completed" && outcome !== "rejected") throw new Error("Specify --outcome completed|rejected. A rejection needs --note with the reason.");
|
|
31468
|
+
return { method: "POST", path: request() + "/close", body: { outcome, note: option2("--note") } };
|
|
31469
|
+
}
|
|
31470
|
+
default:
|
|
31471
|
+
throw new Error(privacyRequestsUsage);
|
|
31472
|
+
}
|
|
31473
|
+
}
|
|
31474
|
+
|
|
31475
|
+
// src/outbound-http.ts
|
|
31476
|
+
var outboundHttpUsage = [
|
|
31477
|
+
"Use backify outbound <action> --environment <UUID> [--app <application-id>]:",
|
|
31478
|
+
" show default action and rules",
|
|
31479
|
+
" default allow|deny what happens to destinations no rule matches (allow is the default)",
|
|
31480
|
+
" allow|block <pattern> allow or block a host (api.example.com), a wildcard ('*.example.com')",
|
|
31481
|
+
" or an HTTPS URL (https://api.example.com/v1/*); a block always wins",
|
|
31482
|
+
" remove <rule-id>",
|
|
31483
|
+
" destinations [--search <text>] URLs requested in the last 30 days with what the rules decide now",
|
|
31484
|
+
" requests [--search <text>] [--outcome allowed|blocked|not-allowed]",
|
|
31485
|
+
"List environments with backify events environments. Quote wildcards so your shell does not expand them."
|
|
31486
|
+
].join("\n");
|
|
31487
|
+
var guid2 = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
|
|
31488
|
+
function outboundHttpCall(appId, args2) {
|
|
31489
|
+
const option2 = (name2) => {
|
|
31490
|
+
const index = args2.indexOf(name2);
|
|
31491
|
+
return index >= 0 ? args2[index + 1] : void 0;
|
|
31492
|
+
};
|
|
31493
|
+
const [action, value] = args2;
|
|
31494
|
+
const environment = option2("--environment");
|
|
31495
|
+
if (!action || !environment || !guid2.test(environment)) throw new Error(outboundHttpUsage);
|
|
31496
|
+
const base = `/apps/${appId}/outbound-http/environments/${environment}`;
|
|
31497
|
+
const query = (names) => {
|
|
31498
|
+
const params = new URLSearchParams();
|
|
31499
|
+
for (const name2 of names) {
|
|
31500
|
+
const item = option2("--" + name2);
|
|
31501
|
+
if (item) params.set(name2, item);
|
|
31502
|
+
}
|
|
31503
|
+
const text2 = params.toString();
|
|
31504
|
+
return text2 ? "?" + text2 : "";
|
|
31505
|
+
};
|
|
31506
|
+
const positional = value !== void 0 && !value.startsWith("--") ? value : void 0;
|
|
31507
|
+
switch (action) {
|
|
31508
|
+
case "show":
|
|
31509
|
+
return { method: "GET", path: base };
|
|
31510
|
+
case "default":
|
|
31511
|
+
if (positional !== "allow" && positional !== "deny") throw new Error("Use backify outbound default allow|deny --environment <UUID>.");
|
|
31512
|
+
return { method: "PUT", path: base + "/default", body: { action: positional } };
|
|
31513
|
+
case "allow":
|
|
31514
|
+
case "block":
|
|
31515
|
+
if (!positional) throw new Error(`Give a host, wildcard or HTTPS URL: backify outbound ${action} <pattern> --environment <UUID>.`);
|
|
31516
|
+
return { method: "POST", path: base + "/rules", body: { pattern: positional, action } };
|
|
31517
|
+
case "remove":
|
|
31518
|
+
if (!positional || !guid2.test(positional)) throw new Error("Give the rule ID from backify outbound show: backify outbound remove <rule-id> --environment <UUID>.");
|
|
31519
|
+
return { method: "DELETE", path: `${base}/rules/${positional}` };
|
|
31520
|
+
case "destinations":
|
|
31521
|
+
return { method: "GET", path: base + "/destinations" + query(["search"]) };
|
|
31522
|
+
case "requests": {
|
|
31523
|
+
const outcome = option2("--outcome");
|
|
31524
|
+
if (outcome !== void 0 && !["allowed", "blocked", "not-allowed"].includes(outcome)) throw new Error("--outcome must be allowed, blocked or not-allowed.");
|
|
31525
|
+
return { method: "GET", path: base + "/requests" + query(["search", "outcome"]) };
|
|
31526
|
+
}
|
|
31527
|
+
default:
|
|
31528
|
+
throw new Error(outboundHttpUsage);
|
|
31529
|
+
}
|
|
31530
|
+
}
|
|
31531
|
+
|
|
29698
31532
|
// src/pairing.ts
|
|
29699
31533
|
async function pairingCode(args2, input) {
|
|
29700
31534
|
const stdinCount = args2.filter((value) => value === "--pair-stdin").length;
|
|
@@ -29731,7 +31565,7 @@ init_mcp_grant();
|
|
|
29731
31565
|
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
29732
31566
|
import { createServer as createServer2 } from "node:http";
|
|
29733
31567
|
async function browserAuthenticate(options) {
|
|
29734
|
-
const auth2 = new URL(apiAddress(options.authUrl));
|
|
31568
|
+
const auth2 = new URL("/cli", apiAddress(options.authUrl));
|
|
29735
31569
|
const state = randomBytes2(32).toString("base64url");
|
|
29736
31570
|
const timeoutMs = options.timeoutMs ?? 5 * 6e4, deadline = Date.now() + timeoutMs;
|
|
29737
31571
|
let resolveSession = () => {
|
|
@@ -29834,7 +31668,7 @@ async function browserAuthenticate(options) {
|
|
|
29834
31668
|
server.closeAllConnections();
|
|
29835
31669
|
}
|
|
29836
31670
|
}
|
|
29837
|
-
function reconnectingApiClient(session,
|
|
31671
|
+
function reconnectingApiClient(session, reconnect2, transport = fetch) {
|
|
29838
31672
|
let current = session;
|
|
29839
31673
|
let pending;
|
|
29840
31674
|
return async (path, init) => {
|
|
@@ -29844,7 +31678,7 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
|
|
|
29844
31678
|
} catch (error2) {
|
|
29845
31679
|
if (!(error2 instanceof CliAuthenticationRequired)) throw error2;
|
|
29846
31680
|
if (current === attempted) {
|
|
29847
|
-
pending ??=
|
|
31681
|
+
pending ??= reconnect2().then((updated) => {
|
|
29848
31682
|
current = updated;
|
|
29849
31683
|
return updated;
|
|
29850
31684
|
}).finally(() => {
|
|
@@ -29861,13 +31695,13 @@ function reconnectingApiClient(session, reconnect, transport = fetch) {
|
|
|
29861
31695
|
init_development();
|
|
29862
31696
|
init_setup();
|
|
29863
31697
|
init_dist();
|
|
29864
|
-
import { readFileSync as
|
|
31698
|
+
import { readFileSync as readFileSync21, existsSync as existsSync16, rmSync as rmSync4 } from "node:fs";
|
|
29865
31699
|
import { homedir as homedir2 } from "node:os";
|
|
29866
31700
|
import { join as join19 } from "node:path";
|
|
29867
31701
|
import { spawn as spawn5 } from "node:child_process";
|
|
29868
31702
|
var [command, ...args] = process.argv.slice(2);
|
|
29869
31703
|
var configPath = join19(homedir2(), ".backify.json");
|
|
29870
|
-
var userConfig = command !== "mcp" && existsSync16(configPath) ? JSON.parse(
|
|
31704
|
+
var userConfig = command !== "mcp" && existsSync16(configPath) ? JSON.parse(readFileSync21(configPath, "utf8")) : {};
|
|
29871
31705
|
async function call(path, init) {
|
|
29872
31706
|
let appId = option("--app");
|
|
29873
31707
|
if (!appId && hasProjectConfig(process.cwd())) appId = projectApplication();
|
|
@@ -29875,6 +31709,7 @@ async function call(path, init) {
|
|
|
29875
31709
|
const credential = session ?? { token: userConfig.token ?? "", organizationId: userConfig.organizationId ?? "", apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api" };
|
|
29876
31710
|
return (appId ? applicationClient(credential, appId) : apiClient(credential))(path, init);
|
|
29877
31711
|
}
|
|
31712
|
+
var authUrl = process.env.BACKIFY_AUTH_URL ?? process.env.BACKIFY_PORTAL_URL ?? userConfig.portalUrl ?? "https://auth.backify.dev";
|
|
29878
31713
|
var option = (name2) => {
|
|
29879
31714
|
const index = args.indexOf(name2);
|
|
29880
31715
|
return index >= 0 ? args[index + 1] : void 0;
|
|
@@ -29890,11 +31725,13 @@ var help = [
|
|
|
29890
31725
|
"",
|
|
29891
31726
|
"Apps: new <name> [--template web|api|worker] [--dir <directory>] | lock [--check] | check [--lockfile-only] | dev [--port <port>]",
|
|
29892
31727
|
"Setup: init | sync | doctor [--environment] | upgrade [--json]",
|
|
29893
|
-
"Account: login | logout | connect | disconnect | status | apps",
|
|
31728
|
+
"Account: signup [--name <organization>] [--plan <plan>] | login | logout | connect | disconnect | status | apps",
|
|
29894
31729
|
"Coding: tools configure --agent <tool> [--transport http|stdio] [--config <path>] [--dry-run] | mcp [--organization <organization-id>]",
|
|
31730
|
+
"Org admin: ops search [<query>] | ops describe <operation-id> | ops get|run <operation-id> [--param <name>=<value>] [--body <file>] [--yes] [--organization <id>] [--json]",
|
|
31731
|
+
"Org tasks: task start <kind> [--draft <json>] | task get|wait|open <id> | github connect | azure connect|reconnect|update-agent|uninstall|remove | org | billing | members add|invite|list|invitations|join-links|domains (backify task --help)",
|
|
29895
31732
|
"Delivery: pull | report [--check] | ship [--production-deploy|--preview-only] [--dry-run] | deploy [<application-id>] [<source-revision>] | request",
|
|
29896
31733
|
" prompt record --stdin --id <UUID>",
|
|
29897
|
-
"Platform: events environments|inspect|test | auth setup [--providers <list>] | domains connect [hostname] | integrations connect <provider>|discover|prepare|status|list|catalog|search|describe|contract|types",
|
|
31734
|
+
"Platform: database extensions|insights --environment <UUID> [--hours <n>] | privacy requests list|show|create|update|close|preview | events environments|inspect|test | outbound show|default|allow|block|remove|destinations|requests --environment <UUID> | auth setup [--providers <list>] | domains connect [hostname] | integrations connect <provider>|discover|prepare|status|list|catalog|search|describe|contract|types",
|
|
29898
31735
|
"",
|
|
29899
31736
|
"Docs: https://docs.backify.dev/"
|
|
29900
31737
|
].join("\n");
|
|
@@ -29910,8 +31747,8 @@ function sessionKey(appId) {
|
|
|
29910
31747
|
async function browserLogin(appId, organizationId, apiUrl) {
|
|
29911
31748
|
if (args.includes("--no-browser")) throw new CliAuthenticationRequired();
|
|
29912
31749
|
const address = apiAddress(apiUrl ?? process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api");
|
|
29913
|
-
return browserAuthenticate({ authUrl
|
|
29914
|
-
console.error("
|
|
31750
|
+
return browserAuthenticate({ authUrl, apiUrl: address, applicationId: appId ? applicationGuid(appId) : void 0, organizationId, mcp: appId ? void 0 : { endpoint: process.env.BACKIFY_MCP_URL ?? "https://mcp.backify.dev" }, openBrowser: (url2) => {
|
|
31751
|
+
console.error("Waiting for browser approval; no reply is needed in chat. Sign in, choose the organization and expiration, and approve Backify CLI access. The CLI continues automatically after approval.\n" + url2 + "\nCoding agents: tell the user this as a status update, not a question or input request, and keep waiting for this command to finish.");
|
|
29915
31752
|
openBrowser(url2);
|
|
29916
31753
|
}, save: (session, mcp) => {
|
|
29917
31754
|
if (appId) {
|
|
@@ -29941,6 +31778,75 @@ async function main() {
|
|
|
29941
31778
|
await runCodingMcpServer2({ organizationId: option("--organization") });
|
|
29942
31779
|
break;
|
|
29943
31780
|
}
|
|
31781
|
+
case "task":
|
|
31782
|
+
case "github":
|
|
31783
|
+
case "azure":
|
|
31784
|
+
case "org":
|
|
31785
|
+
case "billing":
|
|
31786
|
+
case "members": {
|
|
31787
|
+
const { OpsError: OpsError2, terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
|
|
31788
|
+
const { runTaskCommand: runTaskCommand2, taskHelp: taskHelp2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
|
|
31789
|
+
if (args.includes("--help") || command === "task" && !args.length) {
|
|
31790
|
+
console.log(taskHelp2);
|
|
31791
|
+
if (!args.length) process.exitCode = 2;
|
|
31792
|
+
break;
|
|
31793
|
+
}
|
|
31794
|
+
const controller = new AbortController(), stop = () => controller.abort();
|
|
31795
|
+
process.once("SIGINT", stop);
|
|
31796
|
+
process.once("SIGTERM", stop);
|
|
31797
|
+
const json2 = args.includes("--json");
|
|
31798
|
+
try {
|
|
31799
|
+
const { result } = await runTaskCommand2(command, args, {
|
|
31800
|
+
configPath,
|
|
31801
|
+
apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api",
|
|
31802
|
+
mcpEndpoint: process.env.BACKIFY_MCP_URL ?? "https://mcp.backify.dev",
|
|
31803
|
+
confirm: terminalConfirm2(),
|
|
31804
|
+
portalUrl: authUrl,
|
|
31805
|
+
openBrowser,
|
|
31806
|
+
progress: (message) => console.error(message),
|
|
31807
|
+
signal: controller.signal
|
|
31808
|
+
});
|
|
31809
|
+
console.log(json2 ? JSON.stringify(result.value, null, 2) : result.text);
|
|
31810
|
+
if (result.exitCode !== void 0) process.exitCode = result.exitCode;
|
|
31811
|
+
} catch (error2) {
|
|
31812
|
+
if (!(error2 instanceof OpsError2) || !json2) throw error2;
|
|
31813
|
+
console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
|
|
31814
|
+
process.exitCode = 1;
|
|
31815
|
+
} finally {
|
|
31816
|
+
process.removeListener("SIGINT", stop);
|
|
31817
|
+
process.removeListener("SIGTERM", stop);
|
|
31818
|
+
}
|
|
31819
|
+
break;
|
|
31820
|
+
}
|
|
31821
|
+
case "ops": {
|
|
31822
|
+
const { OpsError: OpsError2, opsArguments: opsArguments2, opsHelp: opsHelp2, runOps: runOps2, terminalConfirm: terminalConfirm2 } = await Promise.resolve().then(() => (init_ops(), ops_exports));
|
|
31823
|
+
const options = opsArguments2(args);
|
|
31824
|
+
if (options === "help") {
|
|
31825
|
+
console.log(opsHelp2);
|
|
31826
|
+
if (!args.length) process.exitCode = 2;
|
|
31827
|
+
break;
|
|
31828
|
+
}
|
|
31829
|
+
try {
|
|
31830
|
+
const { opsHumanTaskHandler: opsHumanTaskHandler2 } = await Promise.resolve().then(() => (init_tasks(), tasks_exports));
|
|
31831
|
+
const taskContext = {
|
|
31832
|
+
configPath,
|
|
31833
|
+
apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api",
|
|
31834
|
+
mcpEndpoint: process.env.BACKIFY_MCP_URL ?? "https://mcp.backify.dev",
|
|
31835
|
+
confirm: terminalConfirm2(),
|
|
31836
|
+
portalUrl: authUrl,
|
|
31837
|
+
openBrowser,
|
|
31838
|
+
progress: (message) => console.error(message)
|
|
31839
|
+
};
|
|
31840
|
+
const result = await runOps2(options, { ...taskContext, humanTask: opsHumanTaskHandler2({ noBrowser: false, noWait: false, json: options.json, yes: false }, taskContext) });
|
|
31841
|
+
console.log(options.json ? JSON.stringify(result.value, null, 2) : result.text);
|
|
31842
|
+
if ("exitCode" in result && typeof result.exitCode === "number") process.exitCode = result.exitCode;
|
|
31843
|
+
} catch (error2) {
|
|
31844
|
+
if (!(error2 instanceof OpsError2) || !options.json) throw error2;
|
|
31845
|
+
console.log(JSON.stringify({ schemaVersion: 1, status: "failed", exitCode: 1, error: error2.message, code: error2.code, ...error2.details }, null, 2));
|
|
31846
|
+
process.exitCode = 1;
|
|
31847
|
+
}
|
|
31848
|
+
break;
|
|
31849
|
+
}
|
|
29944
31850
|
case "tools": {
|
|
29945
31851
|
const { configureCodingTool: configureCodingTool2 } = await Promise.resolve().then(() => (init_coding_tools(), coding_tools_exports));
|
|
29946
31852
|
if (args[0] !== "configure") throw new Error("Use backify tools configure --agent copilot|cursor|gemini|cline|windsurf [--transport http|stdio] [--config <path>] [--dry-run].");
|
|
@@ -29969,7 +31875,7 @@ async function main() {
|
|
|
29969
31875
|
process.once("SIGINT", stop);
|
|
29970
31876
|
process.once("SIGTERM", stop);
|
|
29971
31877
|
try {
|
|
29972
|
-
const result = await setupAuth(call, { ...options, providers, applicationId: applicationGuid(option("--app") ?? projectApplication()), authUrl
|
|
31878
|
+
const result = await setupAuth(call, { ...options, providers, applicationId: applicationGuid(option("--app") ?? projectApplication()), authUrl, openBrowser, progress: (message) => console.error(message), signal: controller.signal });
|
|
29973
31879
|
console.log(JSON.stringify(result, null, 2));
|
|
29974
31880
|
if (!result.completed) process.exitCode = 2;
|
|
29975
31881
|
} finally {
|
|
@@ -29978,6 +31884,44 @@ async function main() {
|
|
|
29978
31884
|
}
|
|
29979
31885
|
break;
|
|
29980
31886
|
}
|
|
31887
|
+
case "signup": {
|
|
31888
|
+
const { signup: signup2, signupArguments: signupArguments2, signupHelp: signupHelp2 } = await Promise.resolve().then(() => (init_signup(), signup_exports));
|
|
31889
|
+
if (args.includes("--help")) {
|
|
31890
|
+
console.log(signupHelp2);
|
|
31891
|
+
break;
|
|
31892
|
+
}
|
|
31893
|
+
const options = signupArguments2(args), controller = new AbortController(), stop = () => controller.abort();
|
|
31894
|
+
if (options.resume && !userConfig.pendingSignup) throw new Error("No signup is waiting. Run backify signup to start one.");
|
|
31895
|
+
process.once("SIGINT", stop);
|
|
31896
|
+
process.once("SIGTERM", stop);
|
|
31897
|
+
try {
|
|
31898
|
+
const result = await signup2({
|
|
31899
|
+
...options,
|
|
31900
|
+
resume: options.resume ? userConfig.pendingSignup : void 0,
|
|
31901
|
+
apiUrl: process.env.BACKIFY_API_URL ?? userConfig.apiUrl ?? "https://api.backify.dev/api",
|
|
31902
|
+
mcpEndpoint: process.env.BACKIFY_MCP_URL ?? "https://mcp.backify.dev",
|
|
31903
|
+
portalUrl: authUrl,
|
|
31904
|
+
openBrowser,
|
|
31905
|
+
progress: (message) => console.error(message),
|
|
31906
|
+
signal: controller.signal,
|
|
31907
|
+
savePending: (pending) => {
|
|
31908
|
+
userConfig.pendingSignup = pending;
|
|
31909
|
+
saveUserConfig(configPath, userConfig);
|
|
31910
|
+
},
|
|
31911
|
+
saveGrant: (grant, organizationId) => {
|
|
31912
|
+
userConfig.mcp = grant;
|
|
31913
|
+
userConfig.organizationId = organizationId;
|
|
31914
|
+
saveUserConfig(configPath, userConfig);
|
|
31915
|
+
}
|
|
31916
|
+
});
|
|
31917
|
+
console.log(JSON.stringify(result, null, 2));
|
|
31918
|
+
if (!result.connected) process.exitCode = 2;
|
|
31919
|
+
} finally {
|
|
31920
|
+
process.removeListener("SIGINT", stop);
|
|
31921
|
+
process.removeListener("SIGTERM", stop);
|
|
31922
|
+
}
|
|
31923
|
+
break;
|
|
31924
|
+
}
|
|
29981
31925
|
case "domains": {
|
|
29982
31926
|
if (args[0] !== "connect" || args.includes("--help")) {
|
|
29983
31927
|
console.log(domainConnectHelp);
|
|
@@ -29988,7 +31932,7 @@ async function main() {
|
|
|
29988
31932
|
process.once("SIGINT", stop);
|
|
29989
31933
|
process.once("SIGTERM", stop);
|
|
29990
31934
|
try {
|
|
29991
|
-
const result = await connectDomain(call, { ...options, applicationId: applicationGuid(option("--app") ?? projectApplication()), portalUrl:
|
|
31935
|
+
const result = await connectDomain(call, { ...options, applicationId: applicationGuid(option("--app") ?? projectApplication()), portalUrl: authUrl, openBrowser, progress: (message) => console.error(message), signal: controller.signal });
|
|
29992
31936
|
console.log(JSON.stringify(result, null, 2));
|
|
29993
31937
|
if (!result.confirmed) process.exitCode = 2;
|
|
29994
31938
|
} finally {
|
|
@@ -30008,7 +31952,7 @@ async function main() {
|
|
|
30008
31952
|
process.once("SIGINT", stop);
|
|
30009
31953
|
process.once("SIGTERM", stop);
|
|
30010
31954
|
try {
|
|
30011
|
-
const result = await connectIntegration(call, { ...options, applicationId: applicationGuid(option("--app") ?? projectApplication()), portalUrl:
|
|
31955
|
+
const result = await connectIntegration(call, { ...options, applicationId: applicationGuid(option("--app") ?? projectApplication()), portalUrl: authUrl, openBrowser, progress: (message) => console.error(message), signal: controller.signal });
|
|
30012
31956
|
console.log(JSON.stringify(result, null, 2));
|
|
30013
31957
|
if (result.state !== "ready" && !("userConnectionFlowRequired" in result && result.userConnectionFlowRequired)) process.exitCode = 2;
|
|
30014
31958
|
} finally {
|
|
@@ -30185,10 +32129,44 @@ Next: cd ${directory} && npm install && npm run dev`);
|
|
|
30185
32129
|
case "request": {
|
|
30186
32130
|
const workspaceId = option("--workspace"), name2 = option("--name"), slug = option("--slug"), description = option("--description"), configurationFile = option("--configuration");
|
|
30187
32131
|
if (!workspaceId || !name2 || !slug || !description) throw new Error("Use backify request --workspace <id> --name <name> --slug <slug> --description <purpose> [--configuration <json-file>]");
|
|
30188
|
-
const configuration = configurationFile ? JSON.parse(
|
|
32132
|
+
const configuration = configurationFile ? JSON.parse(readFileSync21(configurationFile, "utf8")) : void 0;
|
|
30189
32133
|
console.log(await call("/apps/requests", { method: "POST", body: JSON.stringify({ workspaceId, name: name2, slug, description, configuration }) }));
|
|
30190
32134
|
break;
|
|
30191
32135
|
}
|
|
32136
|
+
case "database": {
|
|
32137
|
+
const usage = "Use backify database extensions|insights --environment <UUID> [--hours <1-168>] [--app <application-id>]. insights lists slow queries and tables that likely need an index; add indexes with a new SQL migration.";
|
|
32138
|
+
if (args.includes("--help")) {
|
|
32139
|
+
console.log(usage);
|
|
32140
|
+
break;
|
|
32141
|
+
}
|
|
32142
|
+
const environment = option("--environment"), hours = option("--hours");
|
|
32143
|
+
if (!["extensions", "insights"].includes(args[0]) || !environment || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(environment) || hours !== void 0 && (args[0] !== "insights" || !/^\d{1,3}$/.test(hours) || Number(hours) < 1 || Number(hours) > 168))
|
|
32144
|
+
throw new Error(usage);
|
|
32145
|
+
const app = applicationGuid(option("--app") ?? projectApplication());
|
|
32146
|
+
const query = hours ? "?hours=" + hours : "";
|
|
32147
|
+
console.log(JSON.stringify(await call(`/apps/${app}/environments/${environment}/database/${args[0]}${query}`), null, 2));
|
|
32148
|
+
break;
|
|
32149
|
+
}
|
|
32150
|
+
case "privacy": {
|
|
32151
|
+
if (args.includes("--help")) {
|
|
32152
|
+
console.log(privacyRequestsUsage);
|
|
32153
|
+
break;
|
|
32154
|
+
}
|
|
32155
|
+
const request = privacyRequestCall(applicationGuid(option("--app") ?? projectApplication()), args);
|
|
32156
|
+
console.log(JSON.stringify(await call(request.path, { method: request.method, body: request.body ? JSON.stringify(request.body) : void 0 }), null, 2));
|
|
32157
|
+
break;
|
|
32158
|
+
}
|
|
32159
|
+
case "outbound": {
|
|
32160
|
+
if (!args.length || args.includes("--help")) {
|
|
32161
|
+
console.log(outboundHttpUsage);
|
|
32162
|
+
if (!args.length) process.exitCode = 2;
|
|
32163
|
+
break;
|
|
32164
|
+
}
|
|
32165
|
+
const request = outboundHttpCall(applicationGuid(option("--app") ?? projectApplication()), args);
|
|
32166
|
+
const result = await call(request.path, { method: request.method, body: request.body ? JSON.stringify(request.body) : void 0 });
|
|
32167
|
+
console.log(request.method === "DELETE" ? "Removed the rule." : JSON.stringify(result, null, 2));
|
|
32168
|
+
break;
|
|
32169
|
+
}
|
|
30192
32170
|
case "events": {
|
|
30193
32171
|
const appId = applicationGuid(option("--app") ?? projectApplication());
|
|
30194
32172
|
const prefix = "/apps/" + appId + "/events";
|
|
@@ -30203,7 +32181,7 @@ Next: cd ${directory} && npm install && npm run dev`);
|
|
|
30203
32181
|
else if (args[0] === "test") {
|
|
30204
32182
|
const name2 = option("--name"), payload = option("--payload");
|
|
30205
32183
|
if (!name2 || !payload) throw new Error("Specify --name and --payload <json-file>. Never include secrets in event payloads.");
|
|
30206
|
-
console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(
|
|
32184
|
+
console.log(JSON.stringify(await call(path + "/test", { method: "POST", body: JSON.stringify({ name: name2, payload: JSON.parse(readFileSync21(payload, "utf8")), idempotencyKey: option("--idempotency-key") }) }), null, 2));
|
|
30207
32185
|
} else throw new Error("Use backify events environments|inspect|test");
|
|
30208
32186
|
break;
|
|
30209
32187
|
}
|