@agentic-kit/db-tools 0.15.1 → 0.16.0
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 +4 -4
- package/blueprint/blueprint-schema.js +3 -1
- package/context.d.ts +9 -9
- package/context.js +92 -54
- package/db-probe.js +2 -2
- package/esm/blueprint/blueprint-schema.js +3 -1
- package/esm/context.d.ts +9 -9
- package/esm/context.js +91 -54
- package/esm/db-probe.js +2 -2
- package/esm/failure.d.ts +1 -1
- package/esm/failure.js +2 -2
- package/esm/gate.js +1 -1
- package/esm/graphql-http.d.ts +3 -2
- package/esm/graphql-http.js +26 -7
- package/esm/host.d.ts +20 -7
- package/esm/host.js +7 -2
- package/esm/index.d.ts +175 -14
- package/esm/index.js +5 -15
- package/esm/project-file.d.ts +72 -0
- package/esm/project-file.js +161 -0
- package/esm/provision-database/provision.d.ts +8 -3
- package/esm/provision-database/provision.js +63 -94
- package/esm/ready.d.ts +7 -3
- package/esm/ready.js +3 -3
- package/esm/records/rows.d.ts +1 -0
- package/esm/records/rows.js +9 -6
- package/esm/tools/access.js +1 -1
- package/esm/tools/create-api-key.js +2 -2
- package/esm/tools/delete-records.d.ts +1 -1
- package/esm/tools/delete-records.js +7 -7
- package/esm/tools/index.d.ts +195 -2
- package/esm/tools/index.js +25 -15
- package/esm/tools/mutations.js +7 -6
- package/esm/tools/provision-database.js +4 -4
- package/esm/tools/run-codegen.d.ts +2 -2
- package/esm/tools/run-codegen.js +10 -11
- package/esm/tools/update-records.js +1 -1
- package/failure.d.ts +1 -1
- package/failure.js +2 -2
- package/gate.js +1 -1
- package/graphql-http.d.ts +3 -2
- package/graphql-http.js +26 -7
- package/host.d.ts +20 -7
- package/host.js +7 -2
- package/index.d.ts +175 -14
- package/index.js +9 -45
- package/package.json +19 -16
- package/project-file.d.ts +72 -0
- package/project-file.js +178 -0
- package/provision-database/provision.d.ts +8 -3
- package/provision-database/provision.js +66 -96
- package/ready.d.ts +7 -3
- package/ready.js +3 -3
- package/records/rows.d.ts +1 -0
- package/records/rows.js +8 -5
- package/tools/access.js +1 -1
- package/tools/create-api-key.js +2 -2
- package/tools/delete-records.d.ts +1 -1
- package/tools/delete-records.js +8 -8
- package/tools/index.d.ts +195 -2
- package/tools/index.js +53 -43
- package/tools/mutations.js +6 -5
- package/tools/provision-database.js +5 -5
- package/tools/run-codegen.d.ts +2 -2
- package/tools/run-codegen.js +8 -9
- package/tools/update-records.js +1 -1
- package/esm/provision-database/env-file.d.ts +0 -62
- package/esm/provision-database/env-file.js +0 -170
- package/esm/provision-database/pending-ticket.d.ts +0 -33
- package/esm/provision-database/pending-ticket.js +0 -63
- package/provision-database/env-file.d.ts +0 -62
- package/provision-database/env-file.js +0 -179
- package/provision-database/pending-ticket.d.ts +0 -33
- package/provision-database/pending-ticket.js +0 -72
package/README.md
CHANGED
|
@@ -31,12 +31,12 @@ npm install @agentic-kit/db-tools
|
|
|
31
31
|
|
|
32
32
|
The public `extensions.context` of the error that decided goes into `failure.context`: a query over the backend's request limits (`QUERY_TOO_COSTLY`, `QUERY_TOO_DEEP`, `PAGE_SIZE_TOO_LARGE`, `REQUEST_TOO_LARGE`) is `query-too-large` with its numbers there, for example `{ cost, limit }`. An update or delete that answers with no row in its payload changed nothing: that is how row-level security answers for a row this account cannot see, so every tool that updates or deletes fails `no-rows-changed` there instead of reporting success. A create that answers without the new row fails `no-rows-changed` as well: the row may not exist, or a policy lets the account create it but not read it, and the hint names the call that shows whether it exists. `STEP_UP_REQUIRED` is `step-up-required`: the change needs a recent sign-in.
|
|
33
33
|
|
|
34
|
-
`constructiveGateDeps().precondition` runs each tool's own first check and returns the plan's target from what it resolved (`toolPreconditions`, one per tool, provision_database included), and for a change to a table's access the access before and after; a tool the map does not hold is blocked as `unsupported`. For `delete_records` the check resolves the exact rows once, as the person signed in to the app: each table's rows by key, by column values (`where`), its sample rows still there, or all its rows, at most 500 in all, ordered so a row goes before the rows it points at, with what the delete does to the rows it does not select: the rows that point at them, counted on the app API by the foreign keys and followed through each cascade (search chunk tables left out). The target names those rows (`rows`) and the card's preview shows them (`delete-records`). The tool then deletes only the rows the
|
|
34
|
+
`constructiveGateDeps().precondition` runs each tool's own first check and returns the plan's target from what it resolved (`toolPreconditions`, one per tool, provision_database included), and for a change to a table's access the access before and after; a tool the map does not hold is blocked as `unsupported`. For `delete_records` the check resolves the exact rows once, as the person signed in to the app: each table's rows by key, by column values (`where`), its sample rows still there, or all its rows, at most 500 in all, ordered so a row goes before the rows it points at, with what the delete does to the rows it does not select: the rows that point at them, counted on the app API by the foreign keys and followed through each cascade (search chunk tables left out). The target names those rows (`rows`) and the card's preview shows them (`delete-records`). The tool then deletes only the rows of the target `requireApproval` gives it (`approved`), and with no such target it deletes nothing. A host that lets the person untick tables records the approval with the tables they kept (`recordApproval`'s `tables`); when tables are left out, the tool counts the effects of the approved rows again first, and deletes nothing when they would delete, clear or be blocked by rows of a table the person kept, or when it can't count or follow the rows that could reach one (too many related rows, a table with no single-column key, a key it can't read).
|
|
35
35
|
|
|
36
36
|
**Access.** The access of a table is its stored rules, grants and row security (`readTables`), and nothing here says who can or cannot reach a row. `explain_access` gives one plain sentence per stored rule (`explainPolicy`, from the words of the rule's Authz node), the grants, row security and the structural findings (`accessFindings`), each of which says what may happen. It and `describe_schema` return each stored rule through `asWritten`, in the one shape a caller writes (`{ $type, privileges, permissive, policy_role, data, with_check? }`), with every key the node's closed `parameter_schema` marks `readOnly` left out, nested nodes included, so a read carries no part the closed world refuses. A plan's rules use the same keys, with `words` in place of `data`. `set_access` replaces every rule of a table in one change with `owns: ['policies']`; the grants stay, and the Data nodes the rules need add their columns when the table lacks them. `add_policies` adds rules without replacing any. Both take rules only in the registry's blueprint shape (`{ $type, privileges, permissive, policy_role, policy_name, data }`, `AccessPolicyZod`), check each rule's shape against the registry's `BlueprintPolicy`, and check its data with `checkRule` (ajv over the node's closed `parameter_schema`, and the rule shapes these tools do not support) and its role before any plan. Every tool that sends rules, `provision_blueprint` included, sends them through `rulesToSend`: rules of one policy type, role, kind and data become one rule with all their privileges, and a rule the backend would skip (the same policy type and data as another) or refuse (a second policy row of one role, privilege and name) is refused before the plan. The plan holds the rules, grants and row security now and after, one sentence per rule, the findings the change adds and removes, the columns it adds (name, type, required, default) and the ones it reuses as they are. A reused column of another type than its Data node needs is blocked before the change (`conflict`, with `retype_field` and `delete_field`). When the person signed in to the app sees a row, a change that adds a required column with no value for the rows is blocked before anything is sent; otherwise the backend's refused NOT NULL comes back as a `conflict` with the `create_field` call that adds the column as optional first. After the change, the table is read back and compared with the plan by meaning (`policyDifference`); a difference is a `conflict`, and a read that fails is `unverified`. A refusal on the rows of an app table (`add_records`) suggests the read of its rules; a refusal on the control plane does not, because it is about the account's rights on the database.
|
|
37
37
|
|
|
38
38
|
- **Host injection** — credentials, backend endpoints and data-plane tokens come from the host application, not from the package. Call `configureHost()` once at startup; the tools read it lazily per call.
|
|
39
|
-
- **Project context** — `resolveProjectContext` / `resolveDataToken` resolve the database a tool acts on from the cwd's `.
|
|
39
|
+
- **Project context** — `resolveProjectContext` / `resolveDataToken` resolve the database a tool acts on from the cwd's `.constructive/project.json` plus the host's session (`readProjectFile`, `updateProjectFile`, `PROJECT_FILE`), and `deriveSubdomainEndpoint` derives its per-database endpoints. `probeDatabase` says whether that database is still there, and `readSchemaModel` reads its app tables.
|
|
40
40
|
- **Provisioning model** — the pinned `node-type-registry` presets, the provision manifest, and overlay resolution (`resolveProvisionModules`).
|
|
41
41
|
- **`constructiveGateDeps`** — the confirm gate's host capabilities (the effect of a call, the tool's own first check, what tables would a template copy) answered by these tools, so every adapter gates the same tools against the same project state instead of restating it. Each tool runs its check (`toolPreconditions`: the project context on the plane it acts on, an owner, an app sign-in) before it changes anything, and the gate blocks a call whose check fails with that same failure.
|
|
42
42
|
- **`toolSchema`** — a tool's zod parameters as plain JSON Schema, for adapters whose harness wants JSON Schema rather than zod.
|
|
@@ -84,13 +84,13 @@ Tenant APIs answer `ACCESS_SUSPENDED` (a 403 with a JSON body) for a deleted or
|
|
|
84
84
|
|
|
85
85
|
## Provisioning
|
|
86
86
|
|
|
87
|
-
`provision_database` and the host-side `provisionDatabase(input, { cwd })` never create a second database by accident. Calls for one project run one at a time. A binding is
|
|
87
|
+
`provision_database` and the host-side `provisionDatabase(input, { cwd })` never create a second database by accident. Calls for one project run one at a time. A binding is its database id alone: it is probed, then kept (healing the backend and any missing name or owner) or refused. The binding names no endpoint and holds no secret, so a cloned project's file can't send a token anywhere; a binding made on another backend is refused before any request, and a `.constructive` that links outside the project is never written through. Git leaves the file out (`.constructive/.gitignore`). Replace mode (`mode: 'replace', replaces: <the id the caller saw>`) swaps the binding only if it is still that one, and never swaps a suspended database, or a live one on the host path. A provision that outlasts the poll is recorded in the binding file and resumed by the next call. A ticket that can't be read back, or a call that lost track of its ticket, finds an in-flight provision of the same name with `listOwn` before anything is requested; a completed one is only reported. After `MAX_PENDING_ATTEMPTS` waits the call fails `provision-stuck` until the host passes `abandonPending`.
|
|
88
88
|
|
|
89
89
|
Failures carry a `code`: `signed-out`, `backend-unreachable`, `db-missing`, `db-suspended`, `account-mismatch`, `binding-live`, `binding-changed`, `pending-other`, `ticket-lost`, `provision-stuck`, `name-taken` (with `heldBy` when a database of this account holds the name, which the host can bind with `adopt: <id>`), `binding-not-saved`, `env-write-failed`, `reprovision-not-allowed` or `failed`.
|
|
90
90
|
|
|
91
91
|
Host hooks for this, all optional:
|
|
92
92
|
|
|
93
|
-
- `persistBinding(binding)` saves the binding in the host's own store before
|
|
93
|
+
- `persistBinding(binding)` saves the binding in the host's own store before the binding file is written. If it throws, the file is left alone, the ticket stays recorded, and the call fails `binding-not-saved`.
|
|
94
94
|
- `toolReprovision: false` makes `replace_database` fail `reprovision-not-allowed`, for a host that replaces databases only after the user approves.
|
|
95
95
|
- `reprovisionHint` replaces the default advice to bind the directory to a new database in failure messages.
|
|
96
96
|
- `prewarmApp: false` stops the tools from preparing packages/app, for a host that prepares the app itself or not at all: `provision_database` clones and installs nothing while the backend provisions, and `run_codegen` creates, rewrites and installs nothing. It generates into the app that is there, and answers `app-missing`, with `appEndpoint` (the app data plane endpoint) in `failure.context` and `details`, when there is no app or a composed app has no installed packages.
|
|
@@ -57,8 +57,10 @@ function ruleShapeProblems(rule, { withCheck = false } = {}) {
|
|
|
57
57
|
if (!withCheck && envelope.with_check !== undefined)
|
|
58
58
|
problems.push({ path: 'with_check', code: 'not-supported', message: `"with_check" ${exports.RULE_KEY_HINTS.with_check}` });
|
|
59
59
|
const validate = (0, rule_check_1.blueprintValidator)('BlueprintPolicy');
|
|
60
|
+
// The rule's own data is left out here, and checkRule reports what it lacks.
|
|
61
|
+
const dataLeftOut = (error) => error.instancePath === '' && error.keyword === 'required' && error.params.missingProperty === 'data';
|
|
60
62
|
if (!validate((0, rule_check_1.jsonCopy)(withCheck ? envelope : unchecked))) {
|
|
61
|
-
for (const error of validate.errors.filter(reported)) {
|
|
63
|
+
for (const error of validate.errors.filter((error) => reported(error) && !dataLeftOut(error))) {
|
|
62
64
|
const path = error.instancePath.split('/').slice(1).join('.');
|
|
63
65
|
if (error.keyword === 'additionalProperties') {
|
|
64
66
|
const key = String(error.params.additionalProperty);
|
package/context.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export type ProjectContext = {
|
|
|
13
13
|
accountUserId: string;
|
|
14
14
|
accountEmail?: string;
|
|
15
15
|
accountAgent?: PlanAgent;
|
|
16
|
-
/** The host's api endpoint: every control-plane request goes there, whatever
|
|
16
|
+
/** The host's api endpoint: every control-plane request goes there, whatever an injected context pins. */
|
|
17
17
|
controlApiEndpoint: string;
|
|
18
18
|
apiEndpoint: string;
|
|
19
19
|
modulesEndpoint: string;
|
|
@@ -22,7 +22,7 @@ export type ProjectContext = {
|
|
|
22
22
|
dataEndpoint: string;
|
|
23
23
|
hash?: string;
|
|
24
24
|
};
|
|
25
|
-
export type ProjectContextFailureCode = '
|
|
25
|
+
export type ProjectContextFailureCode = 'not-bound' | 'no-backend' | 'missing-credentials' | 'db-missing' | 'db-suspended' | 'account-mismatch' | 'backend-unreachable' | 'schema-unresolved';
|
|
26
26
|
export type ResolveResult = {
|
|
27
27
|
context: ProjectContext | null;
|
|
28
28
|
reason: string;
|
|
@@ -39,16 +39,14 @@ export type ResolveResult = {
|
|
|
39
39
|
export declare const CONTEXT_ENV_KEYS: readonly ["ACCESS_TOKEN", "DATABASE_ID", "API_ENDPOINT", "MODULES_ENDPOINT", "DATABASE_NAME", "OWNER_ID"];
|
|
40
40
|
export type ContextEnvKey = (typeof CONTEXT_ENV_KEYS)[number];
|
|
41
41
|
/** Prefix for injected variables: `ACCESS_TOKEN` is far too generic to claim in
|
|
42
|
-
* a shared process environment, `CONSTRUCTIVE_ACCESS_TOKEN` is not.
|
|
43
|
-
*
|
|
44
|
-
* writes), so both spellings resolve, prefixed winning. */
|
|
42
|
+
* a shared process environment, `CONSTRUCTIVE_ACCESS_TOKEN` is not. Both
|
|
43
|
+
* spellings resolve, prefixed winning. */
|
|
45
44
|
export declare const CONTEXT_ENV_PREFIX = "CONSTRUCTIVE_";
|
|
46
45
|
/** Values keyed by name, or a lookup function (a host with a secret store). */
|
|
47
46
|
export type ContextSource = Record<string, string | undefined> | ((name: string) => string | undefined);
|
|
48
47
|
/** Use the process environment (or any injected record) as the source. */
|
|
49
48
|
export declare function fromEnvironment(environment?: Record<string, string | undefined>): ContextSource;
|
|
50
|
-
|
|
51
|
-
* Returns null when the file is absent. */
|
|
49
|
+
export declare function readEnv(content: string): Record<string, string>;
|
|
52
50
|
export declare function fromEnvFile(cwd: string): Promise<ContextSource | null>;
|
|
53
51
|
export type ResolveOptions = {
|
|
54
52
|
/** Which plane the context is for. Ownership gates the control plane only:
|
|
@@ -62,8 +60,9 @@ export type ResolveOptions = {
|
|
|
62
60
|
/**
|
|
63
61
|
* Resolve the project context from injected values, or from a project folder.
|
|
64
62
|
*
|
|
65
|
-
* Passing a `cwd` string reads the binding in `<cwd>/.
|
|
66
|
-
* through the host.
|
|
63
|
+
* Passing a `cwd` string reads the binding in `<cwd>/.constructive/project.json`
|
|
64
|
+
* and authenticates through the host. That file names no endpoint and holds no
|
|
65
|
+
* token: every request goes to the host's backend.
|
|
67
66
|
* Headless hosts pass values instead: `fromEnvironment()` for a container or
|
|
68
67
|
* Job, an explicit record for anything else.
|
|
69
68
|
*/
|
|
@@ -72,6 +71,7 @@ export declare function resolveProjectContext(input: string | ContextSource, opt
|
|
|
72
71
|
export type DataTokenResult = {
|
|
73
72
|
token?: string;
|
|
74
73
|
userId?: string;
|
|
74
|
+
email?: string;
|
|
75
75
|
reason?: string;
|
|
76
76
|
failure?: ToolFailure;
|
|
77
77
|
};
|
package/context.js
CHANGED
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.CONTEXT_ENV_PREFIX = exports.CONTEXT_ENV_KEYS = void 0;
|
|
7
7
|
exports.fromEnvironment = fromEnvironment;
|
|
8
|
+
exports.readEnv = readEnv;
|
|
8
9
|
exports.fromEnvFile = fromEnvFile;
|
|
9
10
|
exports.resolveProjectContext = resolveProjectContext;
|
|
10
11
|
exports.resolveDataToken = resolveDataToken;
|
|
@@ -17,15 +18,15 @@ const dotenv_1 = require("12factor-env/dotenv");
|
|
|
17
18
|
const db_probe_1 = require("./db-probe");
|
|
18
19
|
const failure_1 = require("./failure");
|
|
19
20
|
const host_1 = require("./host");
|
|
20
|
-
const
|
|
21
|
+
const project_file_1 = require("./project-file");
|
|
21
22
|
// The failure's code is `code` unless `why.code` names a more precise one.
|
|
22
23
|
function unresolved(code, why, cause) {
|
|
23
24
|
const failure = { ...why, code: why.code ?? code };
|
|
24
25
|
return { context: null, reason: (0, failure_1.failureText)(failure), code, ...(cause ? { cause } : {}), failure };
|
|
25
26
|
}
|
|
26
|
-
// The project values pi needs, and where they come from. A
|
|
27
|
-
//
|
|
28
|
-
// a Job, CI — injects values without writing
|
|
27
|
+
// The project values pi needs, and where they come from. A project folder
|
|
28
|
+
// carries its binding in `.constructive/project.json`; a headless host — a
|
|
29
|
+
// container, a Job, CI — injects these values without writing them into a git clone.
|
|
29
30
|
exports.CONTEXT_ENV_KEYS = [
|
|
30
31
|
'ACCESS_TOKEN',
|
|
31
32
|
'DATABASE_ID',
|
|
@@ -35,9 +36,8 @@ exports.CONTEXT_ENV_KEYS = [
|
|
|
35
36
|
'OWNER_ID',
|
|
36
37
|
];
|
|
37
38
|
/** Prefix for injected variables: `ACCESS_TOKEN` is far too generic to claim in
|
|
38
|
-
* a shared process environment, `CONSTRUCTIVE_ACCESS_TOKEN` is not.
|
|
39
|
-
*
|
|
40
|
-
* writes), so both spellings resolve, prefixed winning. */
|
|
39
|
+
* a shared process environment, `CONSTRUCTIVE_ACCESS_TOKEN` is not. Both
|
|
40
|
+
* spellings resolve, prefixed winning. */
|
|
41
41
|
exports.CONTEXT_ENV_PREFIX = 'CONSTRUCTIVE_';
|
|
42
42
|
const lookup = (source) => typeof source === 'function' ? source : (name) => source[name];
|
|
43
43
|
const readContextValue = (source, key) => {
|
|
@@ -49,54 +49,70 @@ const readContextValue = (source, key) => {
|
|
|
49
49
|
function fromEnvironment(environment = process.env) {
|
|
50
50
|
return environment;
|
|
51
51
|
}
|
|
52
|
-
|
|
53
|
-
|
|
52
|
+
function readEnv(content) {
|
|
53
|
+
return (0, dotenv_1.parseDotenv)(content);
|
|
54
|
+
}
|
|
54
55
|
async function fromEnvFile(cwd) {
|
|
55
56
|
try {
|
|
56
|
-
return (
|
|
57
|
+
return readEnv(await (0, promises_1.readFile)(node_path_1.default.join(cwd, '.env'), 'utf8'));
|
|
57
58
|
}
|
|
58
59
|
catch {
|
|
59
60
|
return null;
|
|
60
61
|
}
|
|
61
62
|
}
|
|
63
|
+
/** The value checks of an injected context: a value that is not of its form is never used, sent or shown. */
|
|
64
|
+
const CONTEXT_FORMS = {
|
|
65
|
+
DATABASE_ID: project_file_1.isUuid,
|
|
66
|
+
OWNER_ID: project_file_1.isUuid,
|
|
67
|
+
DATABASE_NAME: project_file_1.isDatabaseName,
|
|
68
|
+
API_ENDPOINT: project_file_1.isEndpoint,
|
|
69
|
+
MODULES_ENDPOINT: project_file_1.isEndpoint,
|
|
70
|
+
};
|
|
71
|
+
const invalidContextKeys = (env) => Object.entries(CONTEXT_FORMS).flatMap(([key, valid]) => (env[key] && !valid(env[key]) ? [key] : []));
|
|
62
72
|
/**
|
|
63
73
|
* Resolve the project context from injected values, or from a project folder.
|
|
64
74
|
*
|
|
65
|
-
* Passing a `cwd` string reads the binding in `<cwd>/.
|
|
66
|
-
* through the host.
|
|
75
|
+
* Passing a `cwd` string reads the binding in `<cwd>/.constructive/project.json`
|
|
76
|
+
* and authenticates through the host. That file names no endpoint and holds no
|
|
77
|
+
* token: every request goes to the host's backend.
|
|
67
78
|
* Headless hosts pass values instead: `fromEnvironment()` for a container or
|
|
68
79
|
* Job, an explicit record for anything else.
|
|
69
80
|
*/
|
|
70
81
|
async function resolveProjectContext(input, options = {}) {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
return unresolved('missing-credentials', (0, failure_1.invalidBinding)(invalid, fileBacked ? '.env' : 'the injected project context'));
|
|
84
|
-
const accessToken = env.ACCESS_TOKEN;
|
|
85
|
-
const databaseId = env.DATABASE_ID;
|
|
86
|
-
if (!databaseId || (!fileBacked && !accessToken)) {
|
|
87
|
-
return unresolved('missing-credentials', fileBacked
|
|
88
|
-
? {
|
|
89
|
-
message: 'Project is not connected to a Constructive database yet (missing DATABASE_ID in .env).',
|
|
90
|
-
hint: 'Bind this directory to a database (the person approves it), then retry.',
|
|
82
|
+
let env;
|
|
83
|
+
// The backend the binding was made on: compared with the host's, never sent to.
|
|
84
|
+
let boundBackend;
|
|
85
|
+
if (typeof input === 'string') {
|
|
86
|
+
const file = await (0, project_file_1.readProjectFile)(input);
|
|
87
|
+
if (file.kind === 'failed')
|
|
88
|
+
return unresolved('missing-credentials', file.failure);
|
|
89
|
+
const database = file.value?.database;
|
|
90
|
+
if (!database) {
|
|
91
|
+
return unresolved('not-bound', {
|
|
92
|
+
message: `This directory is not bound to a database yet (no binding in ${project_file_1.PROJECT_FILE}).`,
|
|
93
|
+
hint: 'Create or bind a database for this directory (the person approves it), then retry.',
|
|
91
94
|
calls: [failure_1.NEW_DATABASE],
|
|
92
|
-
}
|
|
93
|
-
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
env = { ACCESS_TOKEN: undefined, DATABASE_ID: database.id, API_ENDPOINT: undefined, MODULES_ENDPOINT: undefined, DATABASE_NAME: database.name, OWNER_ID: database.ownerId };
|
|
98
|
+
boundBackend = file.value?.backend;
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
env = Object.fromEntries(exports.CONTEXT_ENV_KEYS.map((key) => [key, readContextValue(input, key)]));
|
|
102
|
+
const invalid = invalidContextKeys(env);
|
|
103
|
+
if (invalid.length)
|
|
104
|
+
return unresolved('missing-credentials', (0, failure_1.invalidBinding)(invalid, 'the injected project context'));
|
|
105
|
+
if (!env.ACCESS_TOKEN || !env.DATABASE_ID) {
|
|
106
|
+
return unresolved('missing-credentials', {
|
|
94
107
|
message: `Missing ${exports.CONTEXT_ENV_PREFIX}ACCESS_TOKEN or ${exports.CONTEXT_ENV_PREFIX}DATABASE_ID from the injected project context.`,
|
|
95
108
|
});
|
|
109
|
+
}
|
|
96
110
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
//
|
|
111
|
+
const accessToken = env.ACCESS_TOKEN;
|
|
112
|
+
const databaseId = env.DATABASE_ID;
|
|
113
|
+
// An injected pin wins for the DATA plane (the access key belongs to whatever
|
|
114
|
+
// backend the host injected it for); otherwise the host's backend config,
|
|
115
|
+
// the only endpoint source of a project folder.
|
|
100
116
|
const host = (0, host_1.getHost)();
|
|
101
117
|
const backendRead = (0, host_1.readBackendConfig)(host);
|
|
102
118
|
if (backendRead.kind === 'failed')
|
|
@@ -108,9 +124,9 @@ async function resolveProjectContext(input, options = {}) {
|
|
|
108
124
|
// tools) authenticates with the ACCOUNT bearer: the platform api rejects
|
|
109
125
|
// per-database keys, so the project ACCESS_TOKEN can never act on metaschema
|
|
110
126
|
// surfaces. An explicitly injected key stays in the context for the data plane only.
|
|
111
|
-
// The bearer is only ever sent to the app-configured backend
|
|
112
|
-
//
|
|
113
|
-
const accountRead = await (0, host_1.readAccount)(host);
|
|
127
|
+
// The bearer is only ever sent to the app-configured backend, never to an
|
|
128
|
+
// injected pin.
|
|
129
|
+
const accountRead = await (0, host_1.readAccount)(host, backend);
|
|
114
130
|
if (accountRead.kind === 'failed')
|
|
115
131
|
return unresolved('missing-credentials', accountRead.failure);
|
|
116
132
|
const account = accountRead.value;
|
|
@@ -125,6 +141,13 @@ async function resolveProjectContext(input, options = {}) {
|
|
|
125
141
|
if (!controlApiEndpoint || !controlModulesEndpoint) {
|
|
126
142
|
return unresolved('no-backend', (0, failure_1.noBackendFailure)(host.signInHint));
|
|
127
143
|
}
|
|
144
|
+
if (boundBackend && boundBackend !== controlApiEndpoint) {
|
|
145
|
+
return unresolved('db-missing', {
|
|
146
|
+
message: `This directory is bound to ${env.DATABASE_NAME ?? `database ${databaseId}`} on ${boundBackend}, and the session uses ${controlApiEndpoint}.`,
|
|
147
|
+
hint: 'Switch the session to that backend, or bind this directory to a database on this one (the person approves it).',
|
|
148
|
+
calls: [failure_1.NEW_DATABASE],
|
|
149
|
+
});
|
|
150
|
+
}
|
|
128
151
|
const apiEndpoint = env.API_ENDPOINT || controlApiEndpoint;
|
|
129
152
|
const modulesEndpoint = env.MODULES_ENDPOINT || controlModulesEndpoint;
|
|
130
153
|
const controlHeaders = { Authorization: `Bearer ${accountBearer}` };
|
|
@@ -143,7 +166,7 @@ async function resolveProjectContext(input, options = {}) {
|
|
|
143
166
|
}
|
|
144
167
|
if (probe.status === 'missing') {
|
|
145
168
|
return unresolved('db-missing', {
|
|
146
|
-
message: `The bound
|
|
169
|
+
message: `The database this project is bound to (ID ${databaseId}) no longer exists on this backend, or this account lost access to it.`,
|
|
147
170
|
hint: (0, host_1.reprovisionAdvice)(host),
|
|
148
171
|
...(0, host_1.replaceCall)(host),
|
|
149
172
|
});
|
|
@@ -160,7 +183,7 @@ async function resolveProjectContext(input, options = {}) {
|
|
|
160
183
|
sessionUserId &&
|
|
161
184
|
probe.ownerId !== sessionUserId) {
|
|
162
185
|
return unresolved('account-mismatch', {
|
|
163
|
-
message: `The bound
|
|
186
|
+
message: `The database this project is bound to (ID ${databaseId}) was provisioned under a different account than the one signed in.`,
|
|
164
187
|
hint: (0, host_1.reprovisionAdvice)(host),
|
|
165
188
|
...(0, host_1.replaceCall)(host),
|
|
166
189
|
});
|
|
@@ -170,7 +193,7 @@ async function resolveProjectContext(input, options = {}) {
|
|
|
170
193
|
if (probe.status === 'suspended') {
|
|
171
194
|
const why = probe.suspendedReason ? ` (${probe.suspendedReason})` : '';
|
|
172
195
|
return unresolved('db-suspended', {
|
|
173
|
-
message: `The bound
|
|
196
|
+
message: `The database this project is bound to (ID ${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, but nothing can read or change it until the suspension is lifted.`,
|
|
174
197
|
});
|
|
175
198
|
}
|
|
176
199
|
const databaseName = env.DATABASE_NAME || probe.name || '';
|
|
@@ -245,8 +268,7 @@ function appSignedOut(why = 'Not signed in to the app database yet.') {
|
|
|
245
268
|
const failure = {
|
|
246
269
|
code: 'app-signed-out',
|
|
247
270
|
message: why,
|
|
248
|
-
hint: (0, host_1.getHost)().
|
|
249
|
-
'Sign in from the Sheets tab, or open the Preview and sign in to your app, then try again.',
|
|
271
|
+
hint: (0, host_1.getHost)().appSignInHint ?? 'Sign in from the Sheets tab, or open the Preview and sign in to your app, then try again.',
|
|
250
272
|
};
|
|
251
273
|
return { reason: (0, failure_1.failureText)(failure), failure };
|
|
252
274
|
}
|
|
@@ -261,10 +283,10 @@ async function resolveDataToken(context) {
|
|
|
261
283
|
const broker = host.dataAuthBroker;
|
|
262
284
|
const active = broker?.getActiveToken(context.databaseId);
|
|
263
285
|
if (active)
|
|
264
|
-
return { token: active.token, userId: active.userId };
|
|
286
|
+
return { token: active.token, userId: active.userId, email: active.email };
|
|
265
287
|
let preview = null;
|
|
266
288
|
try {
|
|
267
|
-
preview = host.previewToken ? await host.previewToken() : null;
|
|
289
|
+
preview = host.previewToken ? await host.previewToken({ databaseId: context.databaseId, databaseName: context.databaseName }) : null;
|
|
268
290
|
}
|
|
269
291
|
catch (err) {
|
|
270
292
|
return appSignedOut(`Could not read the app sign-in: ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -280,11 +302,12 @@ async function resolveDataToken(context) {
|
|
|
280
302
|
return appSignedOut();
|
|
281
303
|
broker?.adoptToken(context.databaseId, {
|
|
282
304
|
userId: preview.userId,
|
|
305
|
+
email: preview.email,
|
|
283
306
|
token: preview.accessToken,
|
|
284
307
|
expiresAt,
|
|
285
308
|
origin: 'harvest',
|
|
286
309
|
});
|
|
287
|
-
return { token: preview.accessToken, userId: preview.userId };
|
|
310
|
+
return { token: preview.accessToken, userId: preview.userId, email: preview.email };
|
|
288
311
|
}
|
|
289
312
|
// Per-DB endpoints are deterministic on the provisioning subdomain (= DATABASE_NAME):
|
|
290
313
|
// each plane swaps the first host label of its control-plane endpoint
|
|
@@ -305,18 +328,33 @@ function deriveSubdomainEndpoint(baseEndpoint, firstLabel) {
|
|
|
305
328
|
// user the database's ownerId points at. Best-effort display lookup only —
|
|
306
329
|
// binding health never depends on it. Authenticates with the account bearer
|
|
307
330
|
// against the app-configured auth endpoint (the platform rejects per-database
|
|
308
|
-
// keys, and the bearer never goes to
|
|
331
|
+
// keys, and the bearer never goes to an injected pin).
|
|
332
|
+
// The bearer goes only to an auth plane the host names, or to the one an `api.` host implies (api.x -> auth.x):
|
|
333
|
+
// any other host would be a guess.
|
|
334
|
+
function derivedAuthEndpoint(apiEndpoint) {
|
|
335
|
+
if (!apiEndpoint)
|
|
336
|
+
return undefined;
|
|
337
|
+
try {
|
|
338
|
+
if (new URL(apiEndpoint).hostname.split('.')[0] !== 'api')
|
|
339
|
+
return undefined;
|
|
340
|
+
}
|
|
341
|
+
catch {
|
|
342
|
+
return undefined;
|
|
343
|
+
}
|
|
344
|
+
return deriveSubdomainEndpoint(apiEndpoint, 'auth') || undefined;
|
|
345
|
+
}
|
|
309
346
|
async function resolveOrgName(ownerId) {
|
|
310
347
|
try {
|
|
311
348
|
const host = (0, host_1.getHost)();
|
|
312
|
-
const
|
|
349
|
+
const config = host.backendConfig();
|
|
350
|
+
const accountRead = await (0, host_1.readAccount)(host, config);
|
|
351
|
+
if (accountRead.kind === 'failed')
|
|
352
|
+
return undefined;
|
|
353
|
+
const account = accountRead.value;
|
|
313
354
|
const bearer = account?.apiKey ?? account?.accessToken;
|
|
314
355
|
if (!bearer)
|
|
315
356
|
return undefined;
|
|
316
|
-
const
|
|
317
|
-
if (!apiEndpoint)
|
|
318
|
-
return undefined;
|
|
319
|
-
const authEndpoint = deriveSubdomainEndpoint(apiEndpoint, 'auth');
|
|
357
|
+
const authEndpoint = config?.authEndpoint ?? derivedAuthEndpoint(config?.apiEndpoint);
|
|
320
358
|
if (!authEndpoint)
|
|
321
359
|
return undefined;
|
|
322
360
|
const client = sdk_1.auth.createClient({
|
package/db-probe.js
CHANGED
|
@@ -23,7 +23,7 @@ const document = (databaseId, fields) => `
|
|
|
23
23
|
// rejected account credential, an error this probe doesn't know); recovery is
|
|
24
24
|
// a retry or a sign-in, never a reprovision.
|
|
25
25
|
//
|
|
26
|
-
// The probe authenticates with the ACCOUNT bearer, not
|
|
26
|
+
// The probe authenticates with the ACCOUNT bearer, not an injected project key:
|
|
27
27
|
// the platform api rejects per-database keys, and the singular `database(id:)`
|
|
28
28
|
// field is gone from the current contract, so the lookup goes through the
|
|
29
29
|
// `databases` collection filter.
|
|
@@ -101,7 +101,7 @@ async function probeBoundDatabase(databaseId) {
|
|
|
101
101
|
if (backendRead.kind === 'failed') {
|
|
102
102
|
return { status: 'unreachable', databaseId, cause: 'error', detail: (0, failure_1.failureText)(backendRead.failure) };
|
|
103
103
|
}
|
|
104
|
-
const accountRead = await (0, host_1.readAccount)(host);
|
|
104
|
+
const accountRead = await (0, host_1.readAccount)(host, backendRead.value);
|
|
105
105
|
if (accountRead.kind === 'failed') {
|
|
106
106
|
return { status: 'unreachable', databaseId, cause: 'auth', detail: (0, failure_1.failureText)(accountRead.failure) };
|
|
107
107
|
}
|
|
@@ -52,8 +52,10 @@ export function ruleShapeProblems(rule, { withCheck = false } = {}) {
|
|
|
52
52
|
if (!withCheck && envelope.with_check !== undefined)
|
|
53
53
|
problems.push({ path: 'with_check', code: 'not-supported', message: `"with_check" ${RULE_KEY_HINTS.with_check}` });
|
|
54
54
|
const validate = blueprintValidator('BlueprintPolicy');
|
|
55
|
+
// The rule's own data is left out here, and checkRule reports what it lacks.
|
|
56
|
+
const dataLeftOut = (error) => error.instancePath === '' && error.keyword === 'required' && error.params.missingProperty === 'data';
|
|
55
57
|
if (!validate(jsonCopy(withCheck ? envelope : unchecked))) {
|
|
56
|
-
for (const error of validate.errors.filter(reported)) {
|
|
58
|
+
for (const error of validate.errors.filter((error) => reported(error) && !dataLeftOut(error))) {
|
|
57
59
|
const path = error.instancePath.split('/').slice(1).join('.');
|
|
58
60
|
if (error.keyword === 'additionalProperties') {
|
|
59
61
|
const key = String(error.params.additionalProperty);
|
package/esm/context.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ export type ProjectContext = {
|
|
|
13
13
|
accountUserId: string;
|
|
14
14
|
accountEmail?: string;
|
|
15
15
|
accountAgent?: PlanAgent;
|
|
16
|
-
/** The host's api endpoint: every control-plane request goes there, whatever
|
|
16
|
+
/** The host's api endpoint: every control-plane request goes there, whatever an injected context pins. */
|
|
17
17
|
controlApiEndpoint: string;
|
|
18
18
|
apiEndpoint: string;
|
|
19
19
|
modulesEndpoint: string;
|
|
@@ -22,7 +22,7 @@ export type ProjectContext = {
|
|
|
22
22
|
dataEndpoint: string;
|
|
23
23
|
hash?: string;
|
|
24
24
|
};
|
|
25
|
-
export type ProjectContextFailureCode = '
|
|
25
|
+
export type ProjectContextFailureCode = 'not-bound' | 'no-backend' | 'missing-credentials' | 'db-missing' | 'db-suspended' | 'account-mismatch' | 'backend-unreachable' | 'schema-unresolved';
|
|
26
26
|
export type ResolveResult = {
|
|
27
27
|
context: ProjectContext | null;
|
|
28
28
|
reason: string;
|
|
@@ -39,16 +39,14 @@ export type ResolveResult = {
|
|
|
39
39
|
export declare const CONTEXT_ENV_KEYS: readonly ["ACCESS_TOKEN", "DATABASE_ID", "API_ENDPOINT", "MODULES_ENDPOINT", "DATABASE_NAME", "OWNER_ID"];
|
|
40
40
|
export type ContextEnvKey = (typeof CONTEXT_ENV_KEYS)[number];
|
|
41
41
|
/** Prefix for injected variables: `ACCESS_TOKEN` is far too generic to claim in
|
|
42
|
-
* a shared process environment, `CONSTRUCTIVE_ACCESS_TOKEN` is not.
|
|
43
|
-
*
|
|
44
|
-
* writes), so both spellings resolve, prefixed winning. */
|
|
42
|
+
* a shared process environment, `CONSTRUCTIVE_ACCESS_TOKEN` is not. Both
|
|
43
|
+
* spellings resolve, prefixed winning. */
|
|
45
44
|
export declare const CONTEXT_ENV_PREFIX = "CONSTRUCTIVE_";
|
|
46
45
|
/** Values keyed by name, or a lookup function (a host with a secret store). */
|
|
47
46
|
export type ContextSource = Record<string, string | undefined> | ((name: string) => string | undefined);
|
|
48
47
|
/** Use the process environment (or any injected record) as the source. */
|
|
49
48
|
export declare function fromEnvironment(environment?: Record<string, string | undefined>): ContextSource;
|
|
50
|
-
|
|
51
|
-
* Returns null when the file is absent. */
|
|
49
|
+
export declare function readEnv(content: string): Record<string, string>;
|
|
52
50
|
export declare function fromEnvFile(cwd: string): Promise<ContextSource | null>;
|
|
53
51
|
export type ResolveOptions = {
|
|
54
52
|
/** Which plane the context is for. Ownership gates the control plane only:
|
|
@@ -62,8 +60,9 @@ export type ResolveOptions = {
|
|
|
62
60
|
/**
|
|
63
61
|
* Resolve the project context from injected values, or from a project folder.
|
|
64
62
|
*
|
|
65
|
-
* Passing a `cwd` string reads the binding in `<cwd>/.
|
|
66
|
-
* through the host.
|
|
63
|
+
* Passing a `cwd` string reads the binding in `<cwd>/.constructive/project.json`
|
|
64
|
+
* and authenticates through the host. That file names no endpoint and holds no
|
|
65
|
+
* token: every request goes to the host's backend.
|
|
67
66
|
* Headless hosts pass values instead: `fromEnvironment()` for a container or
|
|
68
67
|
* Job, an explicit record for anything else.
|
|
69
68
|
*/
|
|
@@ -72,6 +71,7 @@ export declare function resolveProjectContext(input: string | ContextSource, opt
|
|
|
72
71
|
export type DataTokenResult = {
|
|
73
72
|
token?: string;
|
|
74
73
|
userId?: string;
|
|
74
|
+
email?: string;
|
|
75
75
|
reason?: string;
|
|
76
76
|
failure?: ToolFailure;
|
|
77
77
|
};
|