@agentic-kit/db-tools 0.2.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/LICENSE +23 -0
- package/README.md +138 -0
- package/app-workspace.d.ts +16 -0
- package/app-workspace.js +145 -0
- package/context.d.ts +62 -0
- package/context.js +282 -0
- package/db-probe.d.ts +30 -0
- package/db-probe.js +50 -0
- package/esm/app-workspace.d.ts +16 -0
- package/esm/app-workspace.js +134 -0
- package/esm/context.d.ts +62 -0
- package/esm/context.js +270 -0
- package/esm/db-probe.d.ts +30 -0
- package/esm/db-probe.js +47 -0
- package/esm/host.d.ts +115 -0
- package/esm/host.js +23 -0
- package/esm/index.d.ts +20 -0
- package/esm/index.js +52 -0
- package/esm/policy/add-policies-to-table.d.ts +26 -0
- package/esm/policy/add-policies-to-table.js +66 -0
- package/esm/policy/provision-helpers.d.ts +38 -0
- package/esm/policy/provision-helpers.js +50 -0
- package/esm/provision-database/credential.d.ts +14 -0
- package/esm/provision-database/credential.js +19 -0
- package/esm/provision-database/env-file.d.ts +37 -0
- package/esm/provision-database/env-file.js +85 -0
- package/esm/provision-database/manifest.d.ts +10 -0
- package/esm/provision-database/manifest.js +48 -0
- package/esm/provision-database/pg-fixups.d.ts +16 -0
- package/esm/provision-database/pg-fixups.js +132 -0
- package/esm/provision-database/preset-match.d.ts +13 -0
- package/esm/provision-database/preset-match.js +66 -0
- package/esm/provision-database/presets.d.ts +4 -0
- package/esm/provision-database/presets.js +13 -0
- package/esm/provision-database/request-database.d.ts +61 -0
- package/esm/provision-database/request-database.js +130 -0
- package/esm/provision-database/resolve.d.ts +27 -0
- package/esm/provision-database/resolve.js +49 -0
- package/esm/records/meta.d.ts +41 -0
- package/esm/records/meta.js +167 -0
- package/esm/run-codegen/barrels.d.ts +3 -0
- package/esm/run-codegen/barrels.js +48 -0
- package/esm/run-codegen/endpoints.d.ts +8 -0
- package/esm/run-codegen/endpoints.js +46 -0
- package/esm/schema-resolve.d.ts +23 -0
- package/esm/schema-resolve.js +69 -0
- package/esm/tool-schema.d.ts +3 -0
- package/esm/tool-schema.js +10 -0
- package/esm/tools/add-policies.d.ts +24 -0
- package/esm/tools/add-policies.js +94 -0
- package/esm/tools/add-records.d.ts +18 -0
- package/esm/tools/add-records.js +122 -0
- package/esm/tools/add-relation-schema.d.ts +29 -0
- package/esm/tools/add-relation-schema.js +56 -0
- package/esm/tools/add-relation.d.ts +10 -0
- package/esm/tools/add-relation.js +91 -0
- package/esm/tools/create-api-key.d.ts +25 -0
- package/esm/tools/create-api-key.js +214 -0
- package/esm/tools/describe-schema.d.ts +19 -0
- package/esm/tools/describe-schema.js +130 -0
- package/esm/tools/manage-entity-types.d.ts +40 -0
- package/esm/tools/manage-entity-types.js +201 -0
- package/esm/tools/mutations.d.ts +35 -0
- package/esm/tools/mutations.js +230 -0
- package/esm/tools/provision-blueprint.d.ts +21 -0
- package/esm/tools/provision-blueprint.js +109 -0
- package/esm/tools/provision-database.d.ts +18 -0
- package/esm/tools/provision-database.js +260 -0
- package/esm/tools/run-codegen.d.ts +12 -0
- package/esm/tools/run-codegen.js +137 -0
- package/esm/tools/templates.d.ts +71 -0
- package/esm/tools/templates.js +331 -0
- package/host.d.ts +115 -0
- package/host.js +28 -0
- package/index.d.ts +20 -0
- package/index.js +76 -0
- package/package.json +49 -0
- package/policy/add-policies-to-table.d.ts +26 -0
- package/policy/add-policies-to-table.js +71 -0
- package/policy/provision-helpers.d.ts +38 -0
- package/policy/provision-helpers.js +58 -0
- package/provision-database/credential.d.ts +14 -0
- package/provision-database/credential.js +22 -0
- package/provision-database/env-file.d.ts +37 -0
- package/provision-database/env-file.js +91 -0
- package/provision-database/manifest.d.ts +10 -0
- package/provision-database/manifest.js +56 -0
- package/provision-database/pg-fixups.d.ts +16 -0
- package/provision-database/pg-fixups.js +170 -0
- package/provision-database/preset-match.d.ts +13 -0
- package/provision-database/preset-match.js +70 -0
- package/provision-database/presets.d.ts +4 -0
- package/provision-database/presets.js +17 -0
- package/provision-database/request-database.d.ts +61 -0
- package/provision-database/request-database.js +134 -0
- package/provision-database/resolve.d.ts +27 -0
- package/provision-database/resolve.js +53 -0
- package/records/meta.d.ts +41 -0
- package/records/meta.js +172 -0
- package/run-codegen/barrels.d.ts +3 -0
- package/run-codegen/barrels.js +54 -0
- package/run-codegen/endpoints.d.ts +8 -0
- package/run-codegen/endpoints.js +51 -0
- package/schema-resolve.d.ts +23 -0
- package/schema-resolve.js +75 -0
- package/tool-schema.d.ts +3 -0
- package/tool-schema.js +13 -0
- package/tools/add-policies.d.ts +24 -0
- package/tools/add-policies.js +97 -0
- package/tools/add-records.d.ts +18 -0
- package/tools/add-records.js +125 -0
- package/tools/add-relation-schema.d.ts +29 -0
- package/tools/add-relation-schema.js +60 -0
- package/tools/add-relation.d.ts +10 -0
- package/tools/add-relation.js +94 -0
- package/tools/create-api-key.d.ts +25 -0
- package/tools/create-api-key.js +220 -0
- package/tools/describe-schema.d.ts +19 -0
- package/tools/describe-schema.js +133 -0
- package/tools/manage-entity-types.d.ts +40 -0
- package/tools/manage-entity-types.js +206 -0
- package/tools/mutations.d.ts +35 -0
- package/tools/mutations.js +233 -0
- package/tools/provision-blueprint.d.ts +21 -0
- package/tools/provision-blueprint.js +112 -0
- package/tools/provision-database.d.ts +18 -0
- package/tools/provision-database.js +266 -0
- package/tools/run-codegen.d.ts +12 -0
- package/tools/run-codegen.js +141 -0
- package/tools/templates.d.ts +71 -0
- package/tools/templates.js +335 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export type CrudOperation = 'create' | 'read' | 'update' | 'delete';
|
|
2
|
+
export interface OperationPolicyConfig {
|
|
3
|
+
roleName: string;
|
|
4
|
+
isPermissive: boolean;
|
|
5
|
+
policyData: Record<string, unknown>;
|
|
6
|
+
isCustomized: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface CrudPolicyConfigs {
|
|
9
|
+
create: OperationPolicyConfig;
|
|
10
|
+
read: OperationPolicyConfig;
|
|
11
|
+
update: OperationPolicyConfig;
|
|
12
|
+
delete: OperationPolicyConfig;
|
|
13
|
+
}
|
|
14
|
+
export declare const CRUD_OPERATIONS: CrudOperation[];
|
|
15
|
+
export type GrantPrivilege = [string, string | string[]];
|
|
16
|
+
export interface GrantEntry {
|
|
17
|
+
roles: string[];
|
|
18
|
+
privileges: GrantPrivilege[];
|
|
19
|
+
}
|
|
20
|
+
export interface PolicyEntry {
|
|
21
|
+
$type: string;
|
|
22
|
+
data?: Record<string, unknown>;
|
|
23
|
+
privileges?: string[];
|
|
24
|
+
policy_role?: string;
|
|
25
|
+
permissive?: boolean;
|
|
26
|
+
policy_name?: string;
|
|
27
|
+
}
|
|
28
|
+
export declare const ALL_CRUD_PRIVILEGES: GrantPrivilege[];
|
|
29
|
+
export declare function crudOpToPrivilege(op: CrudOperation): string;
|
|
30
|
+
export declare function crudOpsToPrivileges(ops: readonly CrudOperation[]): string[];
|
|
31
|
+
export declare function buildGrants(roles?: string[], privileges?: GrantPrivilege[]): GrantEntry[];
|
|
32
|
+
export declare function buildPolicyEntry(type: string, opts?: Partial<Omit<PolicyEntry, '$type'>>): PolicyEntry;
|
|
33
|
+
export interface OperationGroup {
|
|
34
|
+
roleName: string;
|
|
35
|
+
isPermissive: boolean;
|
|
36
|
+
privileges: string[];
|
|
37
|
+
}
|
|
38
|
+
export declare function groupOperationsByConfig(enabledOperations: readonly CrudOperation[], operations: CrudPolicyConfigs): OperationGroup[];
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export const CRUD_OPERATIONS = ['create', 'read', 'update', 'delete'];
|
|
2
|
+
export const ALL_CRUD_PRIVILEGES = [
|
|
3
|
+
['select', '*'],
|
|
4
|
+
['insert', '*'],
|
|
5
|
+
['update', '*'],
|
|
6
|
+
['delete', '*'],
|
|
7
|
+
];
|
|
8
|
+
const CRUD_OP_TO_LOWER_PRIVILEGE = {
|
|
9
|
+
create: 'insert',
|
|
10
|
+
read: 'select',
|
|
11
|
+
update: 'update',
|
|
12
|
+
delete: 'delete',
|
|
13
|
+
};
|
|
14
|
+
export function crudOpToPrivilege(op) {
|
|
15
|
+
return CRUD_OP_TO_LOWER_PRIVILEGE[op];
|
|
16
|
+
}
|
|
17
|
+
export function crudOpsToPrivileges(ops) {
|
|
18
|
+
return ops.map(crudOpToPrivilege);
|
|
19
|
+
}
|
|
20
|
+
export function buildGrants(roles = ['authenticated'], privileges = ALL_CRUD_PRIVILEGES) {
|
|
21
|
+
return [{ roles, privileges }];
|
|
22
|
+
}
|
|
23
|
+
export function buildPolicyEntry(type, opts = {}) {
|
|
24
|
+
const entry = { $type: type };
|
|
25
|
+
if (opts.data && Object.keys(opts.data).length > 0)
|
|
26
|
+
entry.data = opts.data;
|
|
27
|
+
if (opts.privileges && opts.privileges.length > 0)
|
|
28
|
+
entry.privileges = opts.privileges;
|
|
29
|
+
if (opts.policy_role)
|
|
30
|
+
entry.policy_role = opts.policy_role;
|
|
31
|
+
if (opts.permissive !== undefined)
|
|
32
|
+
entry.permissive = opts.permissive;
|
|
33
|
+
if (opts.policy_name)
|
|
34
|
+
entry.policy_name = opts.policy_name;
|
|
35
|
+
return entry;
|
|
36
|
+
}
|
|
37
|
+
export function groupOperationsByConfig(enabledOperations, operations) {
|
|
38
|
+
const groupMap = new Map();
|
|
39
|
+
for (const op of enabledOperations) {
|
|
40
|
+
const config = operations[op];
|
|
41
|
+
const key = `${config.roleName}:${config.isPermissive}`;
|
|
42
|
+
let group = groupMap.get(key);
|
|
43
|
+
if (!group) {
|
|
44
|
+
group = { roleName: config.roleName, isPermissive: config.isPermissive, privileges: [] };
|
|
45
|
+
groupMap.set(key, group);
|
|
46
|
+
}
|
|
47
|
+
group.privileges.push(...crudOpsToPrivileges([op]));
|
|
48
|
+
}
|
|
49
|
+
return [...groupMap.values()];
|
|
50
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type AccountCredential = {
|
|
2
|
+
userId: string;
|
|
3
|
+
accessToken: string;
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
};
|
|
6
|
+
export type ProvisionCredential = {
|
|
7
|
+
mode: 'account';
|
|
8
|
+
ownerId: string;
|
|
9
|
+
bearer: string;
|
|
10
|
+
} | {
|
|
11
|
+
mode: 'error';
|
|
12
|
+
reason: string;
|
|
13
|
+
};
|
|
14
|
+
export declare function selectProvisionCredential(account: AccountCredential | null | undefined, signInHint?: string): ProvisionCredential;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Pure: decide which credential authenticates a project's provisioning. Under the
|
|
2
|
+
// account gate a signed-in session is guaranteed, so every new project provisions
|
|
3
|
+
// UNDER the account (account-owned + enumerable): the database's owner_id is the
|
|
4
|
+
// account's own userId, and the account's API key (falling back to its session
|
|
5
|
+
// token) is the bearer that authenticates the provision mutation and lands in the
|
|
6
|
+
// project .env as ACCESS_TOKEN (refreshed on every provision run, including the
|
|
7
|
+
// skip path). A signed-in session with no usable bearer (keychain locked) is an
|
|
8
|
+
// explicit error, never a silent throwaway owner.
|
|
9
|
+
// Side-effect-free so the branch is unit-testable without runtime/network.
|
|
10
|
+
export function selectProvisionCredential(account, signInHint) {
|
|
11
|
+
const bearer = account?.apiKey ?? account?.accessToken;
|
|
12
|
+
if (account?.userId && bearer) {
|
|
13
|
+
return { mode: 'account', ownerId: account.userId, bearer };
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
mode: 'error',
|
|
17
|
+
reason: `No usable account credential. ${signInHint ?? 'Sign in (or unlock your session) before provisioning a database.'}`,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export type EnvVars = Record<string, string>;
|
|
2
|
+
/**
|
|
3
|
+
* Upsert `vars` into the existing `.env` `content`. Existing keys are replaced
|
|
4
|
+
* in place (preserving surrounding lines/comments); new keys are appended.
|
|
5
|
+
* Returns the new file body, trailing-newline-terminated.
|
|
6
|
+
*/
|
|
7
|
+
export declare function mergeEnv(content: string, vars: EnvVars): string;
|
|
8
|
+
/** The credential keys provision_database owns in a project's .env. */
|
|
9
|
+
export declare const PROVISION_ENV_KEYS: readonly ["DATABASE_ID", "DATABASE_NAME", "OWNER_ID", "ACCESS_TOKEN", "PGDATABASE", "API_ENDPOINT", "MODULES_ENDPOINT"];
|
|
10
|
+
/**
|
|
11
|
+
* Keys archived as comments on reprovision — the binding identity: which
|
|
12
|
+
* database, under whom, on which backend. ACCESS_TOKEN is the account login
|
|
13
|
+
* token, identical across bindings, so it is overwritten in place rather than
|
|
14
|
+
* archived.
|
|
15
|
+
*/
|
|
16
|
+
export declare const ARCHIVED_BINDING_KEYS: readonly ["DATABASE_ID", "DATABASE_NAME", "OWNER_ID", "PGDATABASE", "API_ENDPOINT", "MODULES_ENDPOINT"];
|
|
17
|
+
/**
|
|
18
|
+
* Build the provisioning credential block written to a project's .env. The
|
|
19
|
+
* endpoint pins record which backend owns this binding — outside-app consumers
|
|
20
|
+
* (verify-feature.sh, skill scripts, dev-server shells) resolve them instead of
|
|
21
|
+
* falling back to localhost defaults when the app targets a hosted backend.
|
|
22
|
+
*/
|
|
23
|
+
export declare function provisionEnvVars(args: {
|
|
24
|
+
databaseId: string;
|
|
25
|
+
databaseName: string;
|
|
26
|
+
ownerId: string;
|
|
27
|
+
accessToken: string;
|
|
28
|
+
apiEndpoint: string;
|
|
29
|
+
modulesEndpoint: string;
|
|
30
|
+
}): EnvVars;
|
|
31
|
+
/**
|
|
32
|
+
* Comment out the given keys in place (`# archived <date>: KEY=value`) so a
|
|
33
|
+
* reprovision keeps the previous binding readable in the file instead of
|
|
34
|
+
* silently overwriting it. Every other line — including existing comments and
|
|
35
|
+
* already-archived entries — passes through untouched.
|
|
36
|
+
*/
|
|
37
|
+
export declare function archiveBindingKeys(content: string, keys: readonly string[], archivedOn: string): string;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// Pure .env merge — used by provision_database to persist provisioning
|
|
2
|
+
// credentials without clobbering existing keys: replace a key in place if
|
|
3
|
+
// present, else append.
|
|
4
|
+
// Kept side-effect-free so it is unit-testable (the tool does the fs write).
|
|
5
|
+
/**
|
|
6
|
+
* Upsert `vars` into the existing `.env` `content`. Existing keys are replaced
|
|
7
|
+
* in place (preserving surrounding lines/comments); new keys are appended.
|
|
8
|
+
* Returns the new file body, trailing-newline-terminated.
|
|
9
|
+
*/
|
|
10
|
+
export function mergeEnv(content, vars) {
|
|
11
|
+
let out = content;
|
|
12
|
+
for (const [key, val] of Object.entries(vars)) {
|
|
13
|
+
// Escape the key for the regex, and use a replacement function so `$`
|
|
14
|
+
// sequences in the value are never treated as replacement specials.
|
|
15
|
+
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
16
|
+
const regex = new RegExp(`^${escapedKey}=.*`, 'm');
|
|
17
|
+
if (regex.test(out))
|
|
18
|
+
out = out.replace(regex, () => `${key}=${val}`);
|
|
19
|
+
else
|
|
20
|
+
out += `\n${key}=${val}`;
|
|
21
|
+
}
|
|
22
|
+
return out.trim() + '\n';
|
|
23
|
+
}
|
|
24
|
+
/** The credential keys provision_database owns in a project's .env. */
|
|
25
|
+
export const PROVISION_ENV_KEYS = [
|
|
26
|
+
'DATABASE_ID',
|
|
27
|
+
'DATABASE_NAME',
|
|
28
|
+
'OWNER_ID',
|
|
29
|
+
'ACCESS_TOKEN',
|
|
30
|
+
'PGDATABASE',
|
|
31
|
+
'API_ENDPOINT',
|
|
32
|
+
'MODULES_ENDPOINT',
|
|
33
|
+
];
|
|
34
|
+
/**
|
|
35
|
+
* Keys archived as comments on reprovision — the binding identity: which
|
|
36
|
+
* database, under whom, on which backend. ACCESS_TOKEN is the account login
|
|
37
|
+
* token, identical across bindings, so it is overwritten in place rather than
|
|
38
|
+
* archived.
|
|
39
|
+
*/
|
|
40
|
+
export const ARCHIVED_BINDING_KEYS = [
|
|
41
|
+
'DATABASE_ID',
|
|
42
|
+
'DATABASE_NAME',
|
|
43
|
+
'OWNER_ID',
|
|
44
|
+
'PGDATABASE',
|
|
45
|
+
'API_ENDPOINT',
|
|
46
|
+
'MODULES_ENDPOINT',
|
|
47
|
+
];
|
|
48
|
+
/**
|
|
49
|
+
* Build the provisioning credential block written to a project's .env. The
|
|
50
|
+
* endpoint pins record which backend owns this binding — outside-app consumers
|
|
51
|
+
* (verify-feature.sh, skill scripts, dev-server shells) resolve them instead of
|
|
52
|
+
* falling back to localhost defaults when the app targets a hosted backend.
|
|
53
|
+
*/
|
|
54
|
+
export function provisionEnvVars(args) {
|
|
55
|
+
return {
|
|
56
|
+
DATABASE_ID: args.databaseId,
|
|
57
|
+
DATABASE_NAME: args.databaseName,
|
|
58
|
+
OWNER_ID: args.ownerId,
|
|
59
|
+
ACCESS_TOKEN: args.accessToken,
|
|
60
|
+
PGDATABASE: args.databaseName,
|
|
61
|
+
API_ENDPOINT: args.apiEndpoint,
|
|
62
|
+
MODULES_ENDPOINT: args.modulesEndpoint,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Comment out the given keys in place (`# archived <date>: KEY=value`) so a
|
|
67
|
+
* reprovision keeps the previous binding readable in the file instead of
|
|
68
|
+
* silently overwriting it. Every other line — including existing comments and
|
|
69
|
+
* already-archived entries — passes through untouched.
|
|
70
|
+
*/
|
|
71
|
+
export function archiveBindingKeys(content, keys, archivedOn) {
|
|
72
|
+
const keySet = new Set(keys);
|
|
73
|
+
return content
|
|
74
|
+
.split('\n')
|
|
75
|
+
.map((line) => {
|
|
76
|
+
if (line.trimStart().startsWith('#'))
|
|
77
|
+
return line;
|
|
78
|
+
const eq = line.indexOf('=');
|
|
79
|
+
if (eq === -1)
|
|
80
|
+
return line;
|
|
81
|
+
const key = line.slice(0, eq).trim();
|
|
82
|
+
return keySet.has(key) ? `# archived ${archivedOn}: ${line.trim()}` : line;
|
|
83
|
+
})
|
|
84
|
+
.join('\n');
|
|
85
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ProvisionOverlay } from './resolve';
|
|
2
|
+
export declare const PROVISION_MANIFEST_FILE = "provision.json";
|
|
3
|
+
export type ProvisionManifest = ProvisionOverlay;
|
|
4
|
+
/** Validate an untrusted value as a provision manifest, throwing on bad shape. */
|
|
5
|
+
export declare function parseProvisionManifest(value: unknown): ProvisionManifest;
|
|
6
|
+
/**
|
|
7
|
+
* Load `<dir>/provision.json` as an overlay, or `null` when absent. A malformed
|
|
8
|
+
* file throws so a broken overlay is surfaced rather than silently ignored.
|
|
9
|
+
*/
|
|
10
|
+
export declare function loadProvisionManifest(dir: string): Promise<ProvisionManifest | null>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// `provision.json` overlay manifest.
|
|
2
|
+
//
|
|
3
|
+
// A pure-data overlay, distributed the same way skills are: written into a
|
|
4
|
+
// config/app directory (locally, or materialized there from appstash / a pinned
|
|
5
|
+
// git ref) and read at provision time. It NEVER installs or executes a package
|
|
6
|
+
// — the base preset is a pinned build-time dependency; this file only selects a
|
|
7
|
+
// preset and layers add/remove on top.
|
|
8
|
+
import { readFile } from 'node:fs/promises';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
export const PROVISION_MANIFEST_FILE = 'provision.json';
|
|
12
|
+
const ModuleSchema = z.union([
|
|
13
|
+
z.string(),
|
|
14
|
+
z.tuple([z.string(), z.record(z.string(), z.unknown())]),
|
|
15
|
+
]);
|
|
16
|
+
const ProvisionManifestSchema = z
|
|
17
|
+
.object({
|
|
18
|
+
preset: z.string().optional(),
|
|
19
|
+
add: z.array(ModuleSchema).optional(),
|
|
20
|
+
remove: z.array(z.string()).optional(),
|
|
21
|
+
})
|
|
22
|
+
.strict();
|
|
23
|
+
/** Validate an untrusted value as a provision manifest, throwing on bad shape. */
|
|
24
|
+
export function parseProvisionManifest(value) {
|
|
25
|
+
return ProvisionManifestSchema.parse(value);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Load `<dir>/provision.json` as an overlay, or `null` when absent. A malformed
|
|
29
|
+
* file throws so a broken overlay is surfaced rather than silently ignored.
|
|
30
|
+
*/
|
|
31
|
+
export async function loadProvisionManifest(dir) {
|
|
32
|
+
const file = path.join(dir, PROVISION_MANIFEST_FILE);
|
|
33
|
+
let raw;
|
|
34
|
+
try {
|
|
35
|
+
raw = await readFile(file, 'utf8');
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(raw);
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
throw new Error(`Invalid ${PROVISION_MANIFEST_FILE} at ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
46
|
+
}
|
|
47
|
+
return parseProvisionManifest(parsed);
|
|
48
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type FixupResult = {
|
|
2
|
+
applied: boolean;
|
|
3
|
+
note: string;
|
|
4
|
+
};
|
|
5
|
+
export type PgEnv = {
|
|
6
|
+
host?: string;
|
|
7
|
+
port?: string;
|
|
8
|
+
user?: string;
|
|
9
|
+
password?: string;
|
|
10
|
+
};
|
|
11
|
+
export declare function parsePgpmEnv(stdout: string): PgEnv;
|
|
12
|
+
export declare function resolvePgEnv(): Promise<PgEnv | null>;
|
|
13
|
+
export declare function applySqlFixups(args: {
|
|
14
|
+
databaseName: string;
|
|
15
|
+
physicalDb: string;
|
|
16
|
+
}): Promise<FixupResult>;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// Post-provision SQL fixups for a freshly provisioned database.
|
|
2
|
+
//
|
|
3
|
+
// Two things must happen at the Postgres level that the provisioning GraphQL API
|
|
4
|
+
// does not do for us:
|
|
5
|
+
//
|
|
6
|
+
// 1. Naming settings — `constructive.simple_schema_names` and
|
|
7
|
+
// `schema_use_underscores` make later `provision_blueprint` calls create an
|
|
8
|
+
// `app_public` schema (which resolveSchemaId looks for) instead of a
|
|
9
|
+
// hyphenated `<db>-<hex>-app-public` one. These ALTER DATABASE settings
|
|
10
|
+
// PERSIST, so we set them once here, before any blueprint construction.
|
|
11
|
+
//
|
|
12
|
+
// 2. Membership defaults — new sign-ups otherwise land with
|
|
13
|
+
// is_approved=false/is_verified=false, the AuthzEntityMembership policy then
|
|
14
|
+
// denies every insert/select, and CRUD rows silently never persist
|
|
15
|
+
// (BLUEPRINT-PENDING-001). We flip the defaults (future sign-ups) AND any
|
|
16
|
+
// memberships already created during provisioning.
|
|
17
|
+
//
|
|
18
|
+
// All SQL targets the PHYSICAL control-plane database (`constructive`), NOT the
|
|
19
|
+
// app's database name — that name is only a schema prefix (MEMBERSHIP-DB-001).
|
|
20
|
+
//
|
|
21
|
+
// Connection creds come from the ambient PG* env vars, falling back to sourcing
|
|
22
|
+
// `pgpm env` (the same mechanism the old `eval "$(pgpm env)"` shell step used).
|
|
23
|
+
// If neither yields a connection, provisioning still succeeded — we return a
|
|
24
|
+
// note so the tool can warn the user that sign-in/CRUD may need a manual fixup.
|
|
25
|
+
import { execFile } from 'node:child_process';
|
|
26
|
+
import { promisify } from 'node:util';
|
|
27
|
+
const execFileAsync = promisify(execFile);
|
|
28
|
+
// Parse `pgpm env` output. It prints shell assignments (optionally `export`-
|
|
29
|
+
// prefixed), one per line: `export PGHOST=localhost`. Quotes are stripped.
|
|
30
|
+
export function parsePgpmEnv(stdout) {
|
|
31
|
+
const env = {};
|
|
32
|
+
for (const rawLine of stdout.split('\n')) {
|
|
33
|
+
const line = rawLine.trim().replace(/^export\s+/, '');
|
|
34
|
+
const eq = line.indexOf('=');
|
|
35
|
+
if (eq === -1)
|
|
36
|
+
continue;
|
|
37
|
+
const key = line.slice(0, eq).trim();
|
|
38
|
+
let value = line.slice(eq + 1).trim();
|
|
39
|
+
if ((value.startsWith('"') && value.endsWith('"')) ||
|
|
40
|
+
(value.startsWith("'") && value.endsWith("'"))) {
|
|
41
|
+
value = value.slice(1, -1);
|
|
42
|
+
}
|
|
43
|
+
env[key] = value;
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
host: env.PGHOST,
|
|
47
|
+
port: env.PGPORT,
|
|
48
|
+
user: env.PGUSER,
|
|
49
|
+
password: env.PGPASSWORD,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
export async function resolvePgEnv() {
|
|
53
|
+
if (process.env.PGHOST) {
|
|
54
|
+
return {
|
|
55
|
+
host: process.env.PGHOST,
|
|
56
|
+
port: process.env.PGPORT,
|
|
57
|
+
user: process.env.PGUSER,
|
|
58
|
+
password: process.env.PGPASSWORD,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const { stdout } = await execFileAsync('pgpm', ['env'], { timeout: 15_000 });
|
|
63
|
+
const parsed = parsePgpmEnv(stdout);
|
|
64
|
+
return parsed.host ? parsed : null;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// Find the memberships schema for this app. Schema names use hyphens locally
|
|
71
|
+
// (`<db>-<hex>-memberships-public`) but may use underscores when the naming
|
|
72
|
+
// settings are active — match both, scoped to this app's name prefix.
|
|
73
|
+
const MEMBERSHIPS_SCHEMA_QUERY = `
|
|
74
|
+
SELECT schema_name FROM information_schema.schemata
|
|
75
|
+
WHERE (schema_name LIKE '%memberships-public' OR schema_name LIKE '%memberships_public')
|
|
76
|
+
AND (schema_name LIKE $1 OR schema_name LIKE $2)
|
|
77
|
+
ORDER BY schema_name DESC LIMIT 1`;
|
|
78
|
+
export async function applySqlFixups(args) {
|
|
79
|
+
const pgEnv = await resolvePgEnv();
|
|
80
|
+
if (!pgEnv) {
|
|
81
|
+
return {
|
|
82
|
+
applied: false,
|
|
83
|
+
note: 'Could not reach Postgres (no PGHOST and `pgpm env` unavailable). Database provisioned, but membership defaults were not enabled — sign-in/CRUD may fail until the constructive DB is fixed up manually.',
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
// pg is dynamically imported so the main bundle never loads it unless a
|
|
87
|
+
// provision actually runs with Postgres access. The import lives inside the
|
|
88
|
+
// try: fixups are best-effort, so even a broken pg module must degrade to a
|
|
89
|
+
// note instead of failing the tool after the database is already provisioned.
|
|
90
|
+
let pool;
|
|
91
|
+
try {
|
|
92
|
+
const { Pool } = await import('pg');
|
|
93
|
+
pool = new Pool({
|
|
94
|
+
host: pgEnv.host,
|
|
95
|
+
port: pgEnv.port ? Number(pgEnv.port) : undefined,
|
|
96
|
+
user: pgEnv.user,
|
|
97
|
+
password: pgEnv.password,
|
|
98
|
+
database: args.physicalDb,
|
|
99
|
+
});
|
|
100
|
+
const db = args.physicalDb;
|
|
101
|
+
// Persistent naming settings — so future provision_blueprint calls land an
|
|
102
|
+
// `app_public` schema resolveSchemaId can find.
|
|
103
|
+
await pool.query(`ALTER DATABASE "${db}" SET constructive.simple_schema_names = 'true'`);
|
|
104
|
+
await pool.query(`ALTER DATABASE "${db}" SET constructive.schema_use_underscores = 'true'`);
|
|
105
|
+
const schemaResult = await pool.query(MEMBERSHIPS_SCHEMA_QUERY, [
|
|
106
|
+
`${args.databaseName}-%`,
|
|
107
|
+
`${args.databaseName}\\_%`,
|
|
108
|
+
]);
|
|
109
|
+
if (schemaResult.rows.length === 0) {
|
|
110
|
+
return {
|
|
111
|
+
applied: true,
|
|
112
|
+
note: `Naming settings applied, but no memberships schema was found for "${args.databaseName}" — sign-in may need a manual membership fixup.`,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
const membershipsSchema = schemaResult.rows[0].schema_name;
|
|
116
|
+
await pool.query(`UPDATE "${membershipsSchema}".app_membership_defaults SET is_approved = TRUE, is_verified = TRUE`);
|
|
117
|
+
await pool.query(`UPDATE "${membershipsSchema}".app_memberships
|
|
118
|
+
SET is_approved = TRUE, is_verified = TRUE
|
|
119
|
+
WHERE is_approved = FALSE OR is_verified = FALSE`);
|
|
120
|
+
return { applied: true, note: `Membership defaults enabled (schema: ${membershipsSchema}).` };
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
124
|
+
return {
|
|
125
|
+
applied: false,
|
|
126
|
+
note: `Database provisioned, but SQL fixups failed (${message}). Sign-in/CRUD may fail until membership defaults are enabled manually.`,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
await pool?.end().catch(() => { });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type ProvisionModule } from './presets';
|
|
2
|
+
import type { ProvisionRequest } from './request-database';
|
|
3
|
+
/**
|
|
4
|
+
* The slug of the registry preset whose module set equals `resolved` under
|
|
5
|
+
* the backend's hash semantics, or undefined when no preset matches.
|
|
6
|
+
*/
|
|
7
|
+
export declare function matchPresetSlug(resolved: ProvisionModule[]): string | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Build the requestDatabase input branch: presetSlug when the resolved set
|
|
10
|
+
* equals a registry preset (warm-pool eligible), else the explicit modules
|
|
11
|
+
* array — never both.
|
|
12
|
+
*/
|
|
13
|
+
export declare function selectProvisionRequest(resolved: ProvisionModule[]): ProvisionRequest;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Client-side mirror of the backend's modules_hash normalization
|
|
2
|
+
// (constructive-db: metaschema_private.modules_hash), used to decide whether a
|
|
3
|
+
// resolved module set can be requested by preset slug — the warm-pool-eligible
|
|
4
|
+
// path — or must be sent as an explicit modules array:
|
|
5
|
+
// 1. A bare module name normalizes to [name, {}]; a missing/null options
|
|
6
|
+
// slot normalizes to {}.
|
|
7
|
+
// 2. Options are compared verbatim after canonicalization (object keys
|
|
8
|
+
// sorted at every level) — no default-value normalization.
|
|
9
|
+
// 3. Entries are sorted so the caller's ordering never affects the match.
|
|
10
|
+
// 4. Duplicate normalized entries never match (the backend rejects them).
|
|
11
|
+
// Only equality within this process matters, so string sort order does not
|
|
12
|
+
// need to replicate PostgreSQL collation.
|
|
13
|
+
//
|
|
14
|
+
// The registry presets are the canonical definitions; the backend's
|
|
15
|
+
// db_presets catalog is synced from them. A slug match assumes that sync —
|
|
16
|
+
// preset drift would provision the backend's version of the set.
|
|
17
|
+
import { allModulePresets } from './presets';
|
|
18
|
+
function canonicalize(value) {
|
|
19
|
+
if (Array.isArray(value))
|
|
20
|
+
return value.map(canonicalize);
|
|
21
|
+
if (value && typeof value === 'object') {
|
|
22
|
+
const sorted = {};
|
|
23
|
+
for (const key of Object.keys(value).sort()) {
|
|
24
|
+
sorted[key] = canonicalize(value[key]);
|
|
25
|
+
}
|
|
26
|
+
return sorted;
|
|
27
|
+
}
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
function normalizedEntries(list) {
|
|
31
|
+
const entries = list.map((m) => {
|
|
32
|
+
const name = Array.isArray(m) ? m[0] : m;
|
|
33
|
+
const options = Array.isArray(m) ? (m[1] ?? {}) : {};
|
|
34
|
+
return JSON.stringify([name, canonicalize(options)]);
|
|
35
|
+
});
|
|
36
|
+
entries.sort();
|
|
37
|
+
for (let i = 1; i < entries.length; i++) {
|
|
38
|
+
if (entries[i] === entries[i - 1])
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
return entries;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The slug of the registry preset whose module set equals `resolved` under
|
|
45
|
+
* the backend's hash semantics, or undefined when no preset matches.
|
|
46
|
+
*/
|
|
47
|
+
export function matchPresetSlug(resolved) {
|
|
48
|
+
const target = normalizedEntries(resolved)?.join('\n');
|
|
49
|
+
if (!target)
|
|
50
|
+
return undefined;
|
|
51
|
+
for (const preset of allModulePresets) {
|
|
52
|
+
if (normalizedEntries(preset.modules)?.join('\n') === target) {
|
|
53
|
+
return preset.name;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Build the requestDatabase input branch: presetSlug when the resolved set
|
|
60
|
+
* equals a registry preset (warm-pool eligible), else the explicit modules
|
|
61
|
+
* array — never both.
|
|
62
|
+
*/
|
|
63
|
+
export function selectProvisionRequest(resolved) {
|
|
64
|
+
const presetSlug = matchPresetSlug(resolved);
|
|
65
|
+
return presetSlug ? { presetSlug } : { modules: resolved };
|
|
66
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { allModulePresets, getModulePreset, type ModulePreset } from 'node-type-registry';
|
|
2
|
+
export type ProvisionModule = string | [string, Record<string, unknown>];
|
|
3
|
+
export declare const DEFAULT_PROVISION_PRESET: string;
|
|
4
|
+
export { allModulePresets, getModulePreset, type ModulePreset };
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Provision module presets — the canonical source of truth.
|
|
2
|
+
//
|
|
3
|
+
// The module list is NEVER hand-copied here. It is imported from the pinned
|
|
4
|
+
// `node-type-registry` package (the same presets the backend and dashboard use),
|
|
5
|
+
// so bumping that dependency is how the base module set moves. Hosts customize
|
|
6
|
+
// on top with an ordered overlay (see `resolve.ts`) rather than editing a list.
|
|
7
|
+
import { allModulePresets, getModulePreset, PresetB2bStorage, } from 'node-type-registry';
|
|
8
|
+
// Default base preset. `b2b:storage` = the full multi-tenant B2B shape plus file
|
|
9
|
+
// storage, matching Constructive's app shape. It carries the app-scoped secret,
|
|
10
|
+
// identity-provider, and storage modules the backend's provisioning requires —
|
|
11
|
+
// the drift the old hand-copied list caused (a dropped, then bare/unscoped, set).
|
|
12
|
+
export const DEFAULT_PROVISION_PRESET = PresetB2bStorage.name;
|
|
13
|
+
export { allModulePresets, getModulePreset };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ProvisionModule } from './presets';
|
|
2
|
+
/**
|
|
3
|
+
* Exactly one of presetSlug or modules — requestDatabase rejects both/neither
|
|
4
|
+
* (REQUEST_DATABASE_INVALID_INPUT). `selectProvisionRequest` (preset-match.ts)
|
|
5
|
+
* builds this from the resolved module set.
|
|
6
|
+
*/
|
|
7
|
+
export type ProvisionRequest = {
|
|
8
|
+
presetSlug: string;
|
|
9
|
+
} | {
|
|
10
|
+
modules: ProvisionModule[];
|
|
11
|
+
};
|
|
12
|
+
export type ProvisionTicket = {
|
|
13
|
+
id?: string | null;
|
|
14
|
+
status?: string | null;
|
|
15
|
+
bootstrapStatus?: string | null;
|
|
16
|
+
databaseId?: string | null;
|
|
17
|
+
errorMessage?: string | null;
|
|
18
|
+
bootstrapError?: string | null;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Request + poll seam, injectable for tests (pattern: db-probe's
|
|
22
|
+
* ProbeExecutor). The default executor drives the SDK clients.
|
|
23
|
+
*/
|
|
24
|
+
export type ProvisionRequestExecutor = {
|
|
25
|
+
request(input: {
|
|
26
|
+
databaseName: string;
|
|
27
|
+
subdomain: string;
|
|
28
|
+
domain: string;
|
|
29
|
+
request: ProvisionRequest;
|
|
30
|
+
}): Promise<ProvisionTicket>;
|
|
31
|
+
poll(ticketId: string): Promise<ProvisionTicket | null>;
|
|
32
|
+
};
|
|
33
|
+
export declare const POLL_INTERVAL_MS = 2000;
|
|
34
|
+
/** Stays under airpage's 5-minute per-tool timeout. */
|
|
35
|
+
export declare const POLL_DEADLINE_MS = 240000;
|
|
36
|
+
/**
|
|
37
|
+
* Consecutive unreadable polls tolerated before giving up. Provisioning keeps
|
|
38
|
+
* running server-side, so a dropped request or a momentary 502 must not abort
|
|
39
|
+
* a creation that is about to succeed.
|
|
40
|
+
*/
|
|
41
|
+
export declare const MAX_CONSECUTIVE_POLL_FAILURES = 3;
|
|
42
|
+
/**
|
|
43
|
+
* Request a database and resolve only when it is fully usable: ticket
|
|
44
|
+
* `status` AND `bootstrapStatus` both 'completed'. The ticket the mutation
|
|
45
|
+
* returns is checked before the first sleep, so a warm claim with bootstrap
|
|
46
|
+
* already done never waits. `status: 'failed'` surfaces `errorMessage`;
|
|
47
|
+
* `bootstrapStatus: 'failed'` surfaces `bootstrapError`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function requestDatabaseProvision(args: {
|
|
50
|
+
apiEndpoint: string;
|
|
51
|
+
modulesEndpoint: string;
|
|
52
|
+
bearer: string;
|
|
53
|
+
databaseName: string;
|
|
54
|
+
domain: string;
|
|
55
|
+
request: ProvisionRequest;
|
|
56
|
+
executor?: ProvisionRequestExecutor;
|
|
57
|
+
pollIntervalMs?: number;
|
|
58
|
+
pollDeadlineMs?: number;
|
|
59
|
+
}): Promise<{
|
|
60
|
+
databaseId: string;
|
|
61
|
+
}>;
|