@xlinklight/testkit 0.0.0-stage → 7.0.0-rc.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 +21 -0
- package/README.md +169 -3
- package/content/platform-baseline.sql +273 -0
- package/package.json +274 -3
- package/src/acceptance-oracle.d.mts +24 -0
- package/src/acceptance-oracle.mjs +79 -0
- package/src/architecture-database.d.mts +36 -0
- package/src/architecture-database.mjs +64 -0
- package/src/artifact-build.d.mts +3 -0
- package/src/artifact-build.mjs +35 -0
- package/src/artifact-declarations.mjs +24 -0
- package/src/artifact-graphs.mjs +61 -0
- package/src/artifact-lock.mjs +32 -0
- package/src/artifact-observation.mjs +50 -0
- package/src/artifact-publisher.d.mts +30 -0
- package/src/artifact-publisher.mjs +84 -0
- package/src/browser-lifecycle.mjs +45 -0
- package/src/browser-operation-owner.mjs +28 -0
- package/src/cloudflare-browser.d.mts +14 -0
- package/src/cloudflare-browser.mjs +41 -0
- package/src/cloudflare-build.d.mts +19 -0
- package/src/cloudflare-build.mjs +61 -0
- package/src/cloudflare-http.d.mts +5 -0
- package/src/cloudflare-http.mjs +65 -0
- package/src/cloudflare-pages.d.mts +34 -0
- package/src/cloudflare-pages.mjs +170 -0
- package/src/cloudflare-provider-http.d.mts +8 -0
- package/src/cloudflare-provider-http.mjs +32 -0
- package/src/cloudflare-worker-package.d.mts +6 -0
- package/src/cloudflare-worker-package.mjs +24 -0
- package/src/cloudflare-worker-qualification.d.mts +4 -0
- package/src/cloudflare-worker-qualification.mjs +63 -0
- package/src/cloudflare-workers.d.mts +37 -0
- package/src/cloudflare-workers.mjs +90 -0
- package/src/cluster-directory.d.mts +16 -0
- package/src/cluster-directory.mjs +90 -0
- package/src/core-publishing.d.mts +75 -0
- package/src/core-publishing.mjs +214 -0
- package/src/dev-command-runner.mjs +97 -0
- package/src/fixture-path.mjs +19 -0
- package/src/function-admission.d.mts +1 -0
- package/src/function-admission.mjs +58 -0
- package/src/host-artifact.mjs +32 -0
- package/src/host-stop.mjs +15 -0
- package/src/independent-artifact-qualification.mjs +67 -0
- package/src/independent-runtime-qualification.mjs +647 -0
- package/src/isolated-browser-child.mjs +29 -0
- package/src/isolated-browser.mjs +69 -0
- package/src/lifecycle-trace.mjs +32 -0
- package/src/managed-native-fixture.d.mts +84 -0
- package/src/managed-native-fixture.mjs +209 -0
- package/src/native-fixture.mjs +125 -0
- package/src/native-platform.mjs +56 -0
- package/src/operator-accounts.mjs +103 -0
- package/src/operator-vault.d.mts +2 -0
- package/src/operator-vault.mjs +9 -0
- package/src/owned-process.mjs +75 -0
- package/src/owner-build-cli.d.mts +1 -0
- package/src/owner-build-cli.mjs +31 -0
- package/src/owner-database.mjs +215 -0
- package/src/owner-operator-build.d.mts +1 -0
- package/src/owner-operator-build.mjs +33 -0
- package/src/owner-package-build.d.mts +2 -0
- package/src/owner-package-build.mjs +29 -0
- package/src/owner-production-browser.mjs +215 -0
- package/src/owner-production-instances.mjs +41 -0
- package/src/owner-production.d.mts +104 -0
- package/src/owner-production.mjs +338 -0
- package/src/owner-release.mjs +41 -0
- package/src/owner-worker-build.d.mts +3 -0
- package/src/owner-worker-build.mjs +83 -0
- package/src/prebuilt-build.d.mts +8 -0
- package/src/prebuilt-build.mjs +69 -0
- package/src/prebuilt-output.d.mts +2 -0
- package/src/prebuilt-output.mjs +104 -0
- package/src/production-hosts.mjs +38 -0
- package/src/publisher-acceptance-host-cli.mjs +23 -0
- package/src/publisher-acceptance-owner.mjs +116 -0
- package/src/publisher-acceptance-runner.mjs +250 -0
- package/src/publisher-acceptance-service.mjs +49 -0
- package/src/publisher-acceptance.d.mts +61 -0
- package/src/publisher-acceptance.mjs +3 -0
- package/src/publishing-source.d.mts +11 -0
- package/src/publishing-source.mjs +32 -0
- package/src/qualification-function-host.mjs +26 -0
- package/src/qualification-route-owner.mjs +64 -0
- package/src/qualification-transport.mjs +18 -0
- package/src/registry-core-selection.mjs +41 -0
- package/src/release-artifact.d.mts +17 -0
- package/src/release-artifact.mjs +113 -0
- package/src/release-build.d.mts +12 -0
- package/src/release-build.mjs +71 -0
- package/src/release-cli.d.mts +27 -0
- package/src/release-cli.mjs +79 -0
- package/src/release-control.mjs +45 -0
- package/src/release-coordinator.d.mts +9 -0
- package/src/release-coordinator.mjs +222 -0
- package/src/release-credentials.d.mts +8 -0
- package/src/release-credentials.mjs +97 -0
- package/src/release-environment.mjs +60 -0
- package/src/release-mutex.d.mts +10 -0
- package/src/release-mutex.mjs +38 -0
- package/src/release-operator.d.mts +6 -0
- package/src/release-operator.mjs +59 -0
- package/src/release-supabase.d.mts +7 -0
- package/src/release-supabase.mjs +37 -0
- package/src/release-vercel.d.mts +22 -0
- package/src/release-vercel.mjs +51 -0
- package/src/release-writer.d.mts +6 -0
- package/src/release-writer.mjs +172 -0
- package/src/retained-postgres-shutdown.d.mts +51 -0
- package/src/retained-postgres-shutdown.mjs +262 -0
- package/src/schema-snapshot.mjs +51 -0
- package/src/static-ui-artifact.mjs +54 -0
- package/src/static-ui-routes.mjs +3 -0
- package/src/temporary-acquisition.mjs +62 -0
- package/src/temporary-scope.d.mts +47 -0
- package/src/temporary-scope.mjs +268 -0
- package/src/unscoped-read.mjs +14 -0
- package/src/worker-artifact.mjs +214 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import {randomBytes} from 'node:crypto';
|
|
2
|
+
import {createClient} from '@supabase/supabase-js';
|
|
3
|
+
import {createSupabaseReleaseClient} from './release-supabase.mjs';
|
|
4
|
+
import {vaultIsolationGuard} from './operator-vault.mjs';
|
|
5
|
+
|
|
6
|
+
export function selectAcceptanceApiKeys(rows, projectRef, needsAdmin = false) {
|
|
7
|
+
if (!Array.isArray(rows)) throw Error('ACCEPTANCE_API_KEYS_UNKNOWN');
|
|
8
|
+
const found=rows.filter(row=>row.type==='publishable'&&row.name==='default');
|
|
9
|
+
if(found.length!==1||typeof found[0].api_key!=='string'||!/^sb_publishable_[A-Za-z0-9_-]{16,256}$/.test(found[0].api_key))throw Error('ACCEPTANCE_API_KEYS_UNKNOWN');
|
|
10
|
+
const selected={publishable:found[0].api_key};if(!needsAdmin)return selected;
|
|
11
|
+
// CLI2.107 masks modern Secret display values. This explicit project-scoped
|
|
12
|
+
// administrative credential is used only to initialize owned synthetic users.
|
|
13
|
+
const administrative=rows.filter(row=>row.type==='legacy'&&row.name==='service_role');
|
|
14
|
+
try{
|
|
15
|
+
if(administrative.length!==1||typeof administrative[0].api_key!=='string'||administrative[0].api_key.length>4096||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(administrative[0].api_key))throw Error();
|
|
16
|
+
const claims=JSON.parse(Buffer.from(administrative[0].api_key.split('.')[1],'base64url').toString('utf8'));
|
|
17
|
+
if(typeof projectRef!=='string'||!/^[a-z]{20}$/.test(projectRef)||claims.ref!==projectRef||claims.role!=='service_role'||!Number.isSafeInteger(claims.exp)||claims.exp*1000<=Date.now())throw Error();
|
|
18
|
+
return {...selected,administrative:administrative[0].api_key};
|
|
19
|
+
}catch{throw Error('ACCEPTANCE_ADMIN_CREDENTIAL_UNKNOWN');}
|
|
20
|
+
}
|
|
21
|
+
function target(options){
|
|
22
|
+
const {projectRef,scope,emails,name,ownership}=options;
|
|
23
|
+
if(typeof projectRef!=='string'||!/^[a-z]{20}$/.test(projectRef)||typeof scope!=='string'||!/^[a-z][a-z0-9:/._-]{1,127}$/.test(scope)
|
|
24
|
+
||!Array.isArray(emails)||!emails.length||emails.length>8||new Set(emails).size!==emails.length||emails.some(email=>typeof email!=='string'||email.length>254||!/^ll-release-[a-z0-9-]+@[a-z0-9.-]+$/.test(email)||email.split('@')[0].length>64||!email.split('@')[1].split('.').every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)))
|
|
25
|
+
||typeof name!=='string'||!/^link-light\/[a-z0-9/._-]{1,200}$/.test(name)||typeof ownership!=='string'||!/^link-light[a-z0-9/._-]{1,127}$/.test(ownership))throw Error('ACCEPTANCE_TARGET_INVALID');
|
|
26
|
+
return {projectRef,scope,emails:[...emails],name,ownership};
|
|
27
|
+
}
|
|
28
|
+
export function validateOperatorAccounts(value,options){
|
|
29
|
+
const expected=target(options);
|
|
30
|
+
if(!value||value.schemaVersion!==1||value.projectRef!==expected.projectRef||value.scope!==expected.scope||!Array.isArray(value.accounts)||value.accounts.length!==expected.emails.length
|
|
31
|
+
||value.accounts.some((item,index)=>!item||item.email!==expected.emails[index]||typeof item.password!=='string'||!/^[a-f0-9]{64}$/.test(item.password))
|
|
32
|
+
||new Set(value.accounts.map(item=>item.password)).size!==value.accounts.length)throw Error('ACCEPTANCE_CREDENTIALS_INVALID');
|
|
33
|
+
return value;
|
|
34
|
+
}
|
|
35
|
+
export function assessOperatorUsers(rows,credentials,options){
|
|
36
|
+
const expected=target(options);validateOperatorAccounts(credentials,expected);
|
|
37
|
+
if(!Array.isArray(rows)||rows.some(row=>!expected.emails.includes(row.email)))throw Error('ACCEPTANCE_USER_OWNERSHIP_UNKNOWN');
|
|
38
|
+
return credentials.accounts.map(account=>{
|
|
39
|
+
const selected=rows.filter(row=>row.email===account.email);
|
|
40
|
+
if(selected.length>1||selected.some(row=>typeof row.id!=='string'||!row.id||row.confirmed!==true||row.app_metadata?.link_light_release_scope!==expected.scope))throw Error('ACCEPTANCE_USER_OWNERSHIP_UNKNOWN');
|
|
41
|
+
return selected.length?{email:account.email,userId:selected[0].id,state:'EXISTS'}:{email:account.email,state:'MISSING'};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function context(options){const expected=target(options),client=createSupabaseReleaseClient(options.root,expected.projectRef);return {expected,client};}
|
|
45
|
+
export async function readOperatorAccounts(options){
|
|
46
|
+
const {expected,client}=context(options);
|
|
47
|
+
const observed=await client.query(`DO $isolation$ BEGIN ${vaultIsolationGuard} END $isolation$;
|
|
48
|
+
SELECT description,decrypted_secret FROM vault.decrypted_secrets WHERE name='${expected.name}';`,{signal:options.signal});
|
|
49
|
+
if(!observed.rows.length)return undefined;
|
|
50
|
+
if(observed.rows.length!==1||observed.rows[0].description!==expected.ownership)throw Error('ACCEPTANCE_VAULT_OWNERSHIP_UNKNOWN');
|
|
51
|
+
let value;try{value=JSON.parse(observed.rows[0].decrypted_secret);}catch{throw Error('ACCEPTANCE_CREDENTIALS_INVALID');}
|
|
52
|
+
return validateOperatorAccounts(value,expected);
|
|
53
|
+
}
|
|
54
|
+
async function observeUsers(options,client,expected){
|
|
55
|
+
const encoded=Buffer.from(JSON.stringify(expected.emails)).toString('base64');
|
|
56
|
+
return (await client.query(`SELECT id::text,email,raw_app_meta_data AS app_metadata,email_confirmed_at IS NOT NULL AS confirmed
|
|
57
|
+
FROM auth.users WHERE email IN (SELECT jsonb_array_elements_text(convert_from(decode('${encoded}','base64'),'UTF8')::jsonb));`,{signal:options.signal})).rows;
|
|
58
|
+
}
|
|
59
|
+
function authClient(projectRef,key,signal){return createClient(`https://${projectRef}.supabase.co`,key,{auth:{persistSession:false,autoRefreshToken:false,detectSessionInUrl:false},global:{fetch:(url,options)=>fetch(url,{...options,redirect:'error',signal:AbortSignal.any([...(signal?[signal]:[]),...(options?.signal?[options.signal]:[]),AbortSignal.timeout(15000)])})}});}
|
|
60
|
+
/** Operator initialization only. No signup email, password reset, account adoption,
|
|
61
|
+
* deployed administrative credential, or change to an existing user's metadata. */
|
|
62
|
+
export async function prepareOperatorAccounts(options){
|
|
63
|
+
const mode=options.mode??'inspect';
|
|
64
|
+
if(!['inspect','apply','verify'].includes(mode)||mode==='apply'&&process.env.FORGE_RELEASE_COMMAND&&process.env.FORGE_RELEASE_COMMAND!=='publish')throw Error('ACCEPTANCE_MODE_INVALID');
|
|
65
|
+
const {expected,client}=context(options);let credentials=await readOperatorAccounts(options),credentialWrite=false;
|
|
66
|
+
const before=await observeUsers(options,client,expected);
|
|
67
|
+
if(!credentials&&before.length)throw Error('ACCEPTANCE_USER_OWNERSHIP_UNKNOWN');
|
|
68
|
+
if(!credentials&&mode!=='apply')return {status:'SETUP_REQUIRED',writes:0,credentialWrite};
|
|
69
|
+
if(!credentials){
|
|
70
|
+
const fresh={schemaVersion:1,projectRef:expected.projectRef,scope:expected.scope,accounts:expected.emails.map(email=>({email,password:randomBytes(32).toString('hex')}))};
|
|
71
|
+
const encoded=Buffer.from(JSON.stringify(fresh)).toString('base64');
|
|
72
|
+
await client.query(`DO $accounts$ BEGIN
|
|
73
|
+
IF NOT pg_try_advisory_xact_lock(hashtextextended('${expected.name}',0)) THEN RAISE EXCEPTION 'ACCEPTANCE_SETUP_BUSY'; END IF;
|
|
74
|
+
${vaultIsolationGuard}
|
|
75
|
+
IF NOT EXISTS(SELECT 1 FROM vault.secrets WHERE name='${expected.name}') THEN
|
|
76
|
+
PERFORM vault.create_secret(convert_from(decode('${encoded}','base64'),'UTF8'),'${expected.name}','${expected.ownership}');
|
|
77
|
+
END IF;
|
|
78
|
+
END $accounts$;`,{signal:options.signal});
|
|
79
|
+
credentialWrite=true;credentials=await readOperatorAccounts(options);if(!credentials)throw Error('ACCEPTANCE_VAULT_WRITE_UNKNOWN');
|
|
80
|
+
}
|
|
81
|
+
let users=assessOperatorUsers(before,credentials,expected),writes=0;
|
|
82
|
+
if(mode==='inspect')return {status:users.every(row=>row.state==='EXISTS')?'PREPARED':'CREATION_REQUIRED',users,writes,credentialWrite};
|
|
83
|
+
const needsAdmin=mode==='apply'&&users.some(row=>row.state==='MISSING');
|
|
84
|
+
const keys=selectAcceptanceApiKeys(await client.readPrivateApiKeys({signal:options.signal}),expected.projectRef,needsAdmin);
|
|
85
|
+
if(needsAdmin){
|
|
86
|
+
const admin=authClient(expected.projectRef,keys.administrative,options.signal);
|
|
87
|
+
for(const selected of users.filter(row=>row.state==='MISSING')){
|
|
88
|
+
options.signal?.throwIfAborted();const account=credentials.accounts.find(row=>row.email===selected.email);
|
|
89
|
+
const result=await admin.auth.admin.createUser({email:account.email,password:account.password,email_confirm:true,app_metadata:{link_light_release_scope:expected.scope}});
|
|
90
|
+
if(result.error||!result.data.user||result.data.user.email!==selected.email)throw Error('ACCEPTANCE_ACCOUNT_CREATION_UNKNOWN',{cause:result.error});writes++;
|
|
91
|
+
}
|
|
92
|
+
users=assessOperatorUsers(await observeUsers(options,client,expected),credentials,expected);
|
|
93
|
+
}
|
|
94
|
+
if(!users.every(row=>row.state==='EXISTS'))throw Error('ACCEPTANCE_ACCOUNTS_INCOMPLETE');
|
|
95
|
+
for(const account of credentials.accounts){
|
|
96
|
+
const auth=authClient(expected.projectRef,keys.publishable,options.signal),signedIn=await auth.auth.signInWithPassword(account);
|
|
97
|
+
if(signedIn.error||!signedIn.data.session)throw Error('ACCEPTANCE_LOGIN_FAILED',{cause:signedIn.error});
|
|
98
|
+
const session=signedIn.data.session;
|
|
99
|
+
try{const verified=await auth.auth.getUser(session.access_token);if(verified.error||verified.data.user?.id!==users.find(row=>row.email===account.email)?.userId)throw Error('ACCEPTANCE_IDENTITY_MISMATCH');}
|
|
100
|
+
finally{const closed=await auth.auth.admin.signOut(session.access_token,'local');if(closed.error)throw Error('ACCEPTANCE_LOGOUT_UNKNOWN');}
|
|
101
|
+
}
|
|
102
|
+
return {status:'PREPARED_AND_AUTHENTICATED',users,writes,credentialWrite};
|
|
103
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Provider administrative operators are explicit. Runtime identities and roles
|
|
2
|
+
* they can SET must not have any plaintext Vault column privilege. */
|
|
3
|
+
export const vaultIsolationGuard = `IF EXISTS(SELECT 1 FROM pg_roles actor CROSS JOIN pg_roles access WHERE
|
|
4
|
+
(actor.rolcanlogin AND actor.rolname NOT IN ('postgres','supabase_admin','service_role','supabase_read_only_user','supabase_etl_admin','authenticator','supabase_storage_admin','cli_login_postgres') OR actor.rolname IN ('anon','authenticated','platform_runtime','platform_worker','platform_control'))
|
|
5
|
+
AND (actor.oid=access.oid OR pg_has_role(actor.oid,access.oid,'SET'))
|
|
6
|
+
AND has_schema_privilege(access.oid,'vault','USAGE')
|
|
7
|
+
AND has_any_column_privilege(access.oid,'vault.decrypted_secrets','SELECT')) THEN
|
|
8
|
+
RAISE EXCEPTION 'VAULT_NOT_ISOLATED';
|
|
9
|
+
END IF;`;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { spawn, execFile } from "node:child_process";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
export function startOwnedProcess(executable, args, options = {}) {
|
|
5
|
+
const { signal, onSpawn, terminationGraceMs = 10000, stopMode = "tree", ...spawnOptions } = options;
|
|
6
|
+
if (!Number.isInteger(terminationGraceMs) || terminationGraceMs < 1 || terminationGraceMs > 10000) throw Error("Owned process termination grace must be 1..10000 ms");
|
|
7
|
+
if (!["tree", "direct-child", "natural"].includes(stopMode)) throw Error("Unknown owned process stop mode");
|
|
8
|
+
signal?.throwIfAborted();
|
|
9
|
+
const posix = process.platform !== "win32";
|
|
10
|
+
// A separate POSIX process group belongs to this handle. Descendants inherit
|
|
11
|
+
// that group unless they deliberately create a new session; fixture children
|
|
12
|
+
// must not escape it. Windows uses the owned PID tree via taskkill instead.
|
|
13
|
+
const requestedAt = new Date().toISOString();
|
|
14
|
+
const child = spawn(executable, args, { windowsHide: true, stdio: ["ignore", "pipe", "pipe"], ...spawnOptions, ...(posix && stopMode === "tree" ? { detached: true } : {}) });
|
|
15
|
+
const state = { pid: child.pid, requestedAt, command: { executable: child.spawnfile, args: child.spawnargs?.slice(1) ?? args, cwd: spawnOptions.cwd ?? process.cwd() }, closed: false, exitCode: null, stopError: null,
|
|
16
|
+
stopScope: stopMode === "tree" ? "owned-tree" : "direct-child",
|
|
17
|
+
stopMethod: stopMode === "natural" ? "bounded-natural-close" : stopMode === "direct-child" ? "owned-child-handle" : posix ? "owned-posix-group" : "owned-windows-tree" };
|
|
18
|
+
let stopPromise;
|
|
19
|
+
const completion = new Promise(resolve => {
|
|
20
|
+
child.once("error", error => { state.error = error.message; });
|
|
21
|
+
child.once("close", (code, signalCode) => { state.closed = true; state.closedAt = new Date().toISOString(); state.signalCode = signalCode ?? null; state.exitCode = code; state.stdoutEof = child.stdout?.readableEnded === true; state.stderrEof = child.stderr?.readableEnded === true; signal?.removeEventListener("abort", abort); resolve(state); });
|
|
22
|
+
});
|
|
23
|
+
function signalGroup(signalName) {
|
|
24
|
+
if (!child.pid) return false;
|
|
25
|
+
try { process.kill(-child.pid, signalName); return true; }
|
|
26
|
+
catch (error) { if (error.code === "ESRCH") return false; throw error; }
|
|
27
|
+
}
|
|
28
|
+
async function stop() {
|
|
29
|
+
if (stopPromise) return stopPromise;
|
|
30
|
+
if ((!posix || stopMode !== "tree") && state.closed) return completion;
|
|
31
|
+
stopPromise = (async () => {
|
|
32
|
+
if (stopMode === "direct-child") {
|
|
33
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
34
|
+
try { if (!child.kill("SIGTERM")) state.stopError ??= "Owned child signal was not delivered"; }
|
|
35
|
+
catch (error) { state.stopError ??= error.message; }
|
|
36
|
+
}
|
|
37
|
+
} else if (stopMode === "natural") {
|
|
38
|
+
// A finite command owns its own shutdown. Await its actual close within
|
|
39
|
+
// this existing bound; this establishes no detached-descendant claim.
|
|
40
|
+
} else if (posix && child.pid) {
|
|
41
|
+
// The leader can exit before its descendants. Closed stdout/parent
|
|
42
|
+
// does not release our responsibility for that still-owned group.
|
|
43
|
+
signalGroup("SIGTERM");
|
|
44
|
+
const deadline = Date.now() + terminationGraceMs;
|
|
45
|
+
while (signalGroup(0) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 25));
|
|
46
|
+
if (signalGroup(0)) {
|
|
47
|
+
signalGroup("SIGKILL");
|
|
48
|
+
const killedBy = Date.now() + 1000;
|
|
49
|
+
while (signalGroup(0) && Date.now() < killedBy) await new Promise(resolve => setTimeout(resolve, 25));
|
|
50
|
+
if (signalGroup(0)) state.stopError ??= "Owned process group did not disappear within shutdown bound";
|
|
51
|
+
}
|
|
52
|
+
} else if (child.exitCode === null && child.signalCode === null && child.pid) {
|
|
53
|
+
const executable = path.join(process.env.SystemRoot, "System32", "taskkill.exe"), args = ["/pid", String(child.pid), "/t", "/f"], startedAt = new Date().toISOString(), rootClosedBefore = state.closed;
|
|
54
|
+
const result = await new Promise(resolve => {
|
|
55
|
+
const utility = execFile(executable, args, { windowsHide: true, timeout: 10000, maxBuffer: 8192, encoding: "buffer" }, (error, stdout, stderr) => {
|
|
56
|
+
resolve({ pid: utility.pid, status: typeof error?.code === "number" ? error.code : error ? null : 0,
|
|
57
|
+
signal: error?.signal ?? null, error: error && typeof error.code !== "number" ? error : null, stdout, stderr });
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
const stdout = Buffer.from(result.stdout ?? []), stderr = Buffer.from(result.stderr ?? []);
|
|
61
|
+
state.stopAttempt = { executable, args, startedAt, endedAt: new Date().toISOString(), rootClosedBefore, pid: result.pid, status: result.status, signal: result.signal ?? null, error: result.error ? { code: result.error.code, message: result.error.message } : null, stdoutBytes: stdout.length, stderrBytes: stderr.length, stdoutBase64: stdout.subarray(0,8192).toString('base64'), stderrBase64: stderr.subarray(0,8192).toString('base64'), captureComplete: !result.error && !result.signal && stdout.length <= 8192 && stderr.length <= 8192 };
|
|
62
|
+
if (result.error) state.stopError ??= result.error.message;
|
|
63
|
+
else if (result.status !== 0) state.stopError ??= "Owned Windows tree termination failed (exit " + String(result.status) + ")";
|
|
64
|
+
}
|
|
65
|
+
let timer;
|
|
66
|
+
const bound = new Promise((_, reject) => { timer = setTimeout(() => { state.stopError ??= "Owned process did not close within shutdown bound"; reject(Error(state.stopError)); }, stopMode === "tree" ? 10000 : terminationGraceMs); });
|
|
67
|
+
try { return await Promise.race([completion, bound]); } finally { clearTimeout(timer); }
|
|
68
|
+
})();
|
|
69
|
+
return stopPromise;
|
|
70
|
+
}
|
|
71
|
+
function abort() { void stop().catch(error => { state.stopError ??= error.message; }); }
|
|
72
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
73
|
+
child.once("spawn", () => { state.spawnedAt = new Date().toISOString(); onSpawn?.(); });
|
|
74
|
+
return { child, state, completion, stop };
|
|
75
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function runOwnerBuildCommand(options:{root:string;args:readonly string[]}):Promise<Record<string,unknown>>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
5
|
+
|
|
6
|
+
const commands=new Set(['build-info','build-package','build-operator','build-worker','build-static-ui']);
|
|
7
|
+
/** Local owner builds only. Publication and credentials belong to the
|
|
8
|
+
* separately installed publishing client and its private durable journal. */
|
|
9
|
+
export async function runOwnerBuildCommand({root,args}){
|
|
10
|
+
if(!Array.isArray(args)||args.length!==1||!commands.has(args[0])||typeof root!=='string'||!path.isAbsolute(root))throw Error('OWNER_BUILD_ARGUMENT_INVALID');
|
|
11
|
+
const [command]=args;
|
|
12
|
+
root=fs.realpathSync(root);
|
|
13
|
+
const build=await import('./release-build.mjs');
|
|
14
|
+
if(command==='build-info')return build.writeOwnerBuildInfo({root});
|
|
15
|
+
if(command==='build-package')return build.prepareOwnerPackageBuild({root});
|
|
16
|
+
if(command==='build-operator')return build.prepareOwnerOperatorBuild({root});
|
|
17
|
+
if(command==='build-worker'){
|
|
18
|
+
const entry=path.join(root,'deployment/worker-build.mjs'),info=fs.lstatSync(entry);
|
|
19
|
+
if(!info.isFile()||info.isSymbolicLink()||info.nlink!==1||info.size>65536||fs.realpathSync(entry)!==entry)throw Error('OWNER_WORKER_BUILD_MODULE_INVALID');
|
|
20
|
+
const selected=await import(pathToFileURL(entry).href);if(typeof selected.buildWorker!=='function')throw Error('OWNER_WORKER_BUILD_MODULE_INVALID');return selected.buildWorker({root});
|
|
21
|
+
}
|
|
22
|
+
return build.prepareOwnerStaticUiBuild({root});
|
|
23
|
+
}
|
|
24
|
+
if(process.argv[1]&&fs.existsSync(process.argv[1])&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url)){
|
|
25
|
+
try{
|
|
26
|
+
const report=await runOwnerBuildCommand({root:process.cwd(),args:process.argv.slice(2)});
|
|
27
|
+
console.log(JSON.stringify(report));process.exitCode=report?.ok===false?1:0;
|
|
28
|
+
}catch(error){
|
|
29
|
+
console.error(JSON.stringify({ok:false,status:'FAIL_OR_UNKNOWN',code:/^[A-Z][A-Z0-9_]{1,127}$/.test(error?.message??'')?error.message:'OWNER_BUILD_UNKNOWN'}));process.exitCode=1;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {createRequire} from 'node:module';
|
|
5
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
6
|
+
import pg from 'pg';
|
|
7
|
+
import {createSupabaseReleaseClient} from './release-supabase.mjs';
|
|
8
|
+
import {vaultIsolationGuard} from './operator-vault.mjs';
|
|
9
|
+
import {schemaSnapshotSql,readSchemaSnapshot,assertSchemaSnapshot} from './schema-snapshot.mjs';
|
|
10
|
+
|
|
11
|
+
const ownership='link-light-owner-runtime/v2';
|
|
12
|
+
const kinds=['application','worker'];
|
|
13
|
+
/** Explicit owner configuration dispatch; SQL authority remains in the existing
|
|
14
|
+
* database preparation API and the selected owner's public schema export. */
|
|
15
|
+
export async function runOwnerDatabaseCommand({root,args,environment=process.env,signal=AbortSignal.timeout(300000)}){
|
|
16
|
+
if(!Array.isArray(args)||args.length!==1||!['--contract','--inspect','--apply','--auto'].includes(args[0]))throw Error('OWNER_DATABASE_MODE_REQUIRED');
|
|
17
|
+
const mode=args[0];
|
|
18
|
+
if(mode==='--auto'&&(!['check','publish'].includes(environment.FORGE_RELEASE_COMMAND)||!/^[a-f0-9]{40}$/.test(environment.FORGE_RELEASE_SHA??'')))throw Error('RELEASE_JOB_CONTEXT_INVALID');
|
|
19
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||fs.realpathSync(root)!==path.resolve(root))throw Error('OWNER_DATABASE_CONFIGURATION_INVALID');
|
|
20
|
+
root=path.resolve(root);const require=createRequire(path.join(root,'package.json')),read=relative=>JSON.parse(fs.readFileSync(path.join(root,relative),'utf8'));
|
|
21
|
+
const metadata=read('package.json'),config=read('deployment/database.json'),deployment=read('deployment/target.json');
|
|
22
|
+
if(config.schemaVersion!==1||config.target.projectRef!==deployment.projectRef||config.domain.entry!==metadata.name+'/postgres-schema')throw Error('OWNER_DATABASE_CONFIGURATION_INVALID');
|
|
23
|
+
const outputPath=path.join(root,'deployment/schema-contract.json');
|
|
24
|
+
if(mode==='--contract')return buildOwnerSchemaContract({root,target:config.target,domain:config.domain,outputPath,signal});
|
|
25
|
+
const contract=read('deployment/schema-contract.json'),schemaSql=fs.readFileSync(require.resolve(config.domain.entry),'utf8');
|
|
26
|
+
if(contract.schemaVersion!==1||contract.schemaSqlDigest!=='sha256:'+createHash('sha256').update(schemaSql).digest('hex'))throw Error('OWNER_DATABASE_CONTRACT_REBUILD_REQUIRED');
|
|
27
|
+
let upgrade={};
|
|
28
|
+
if(config.upgrade){
|
|
29
|
+
const owned=relative=>{if(typeof relative!=='string'||!relative||relative.split('/').some(part=>!part||part==='.'||part==='..')||/[\\:\0]/.test(relative))throw Error('OWNER_DATABASE_UPGRADE_INPUT');const filename=path.join(root,relative);if(fs.realpathSync(filename)!==filename||!fs.statSync(filename).isFile()||fs.statSync(filename).size>1048576)throw Error('OWNER_DATABASE_UPGRADE_INPUT');return filename;};
|
|
30
|
+
const predecessor=JSON.parse(fs.readFileSync(owned(config.upgrade.contract),'utf8')),upgradeSql=fs.readFileSync(owned(config.upgrade.sql),'utf8');
|
|
31
|
+
if(predecessor.schemaVersion!==1||predecessor.upgradeSqlDigest!=='sha256:'+createHash('sha256').update(upgradeSql).digest('hex'))throw Error('OWNER_DATABASE_UPGRADE_INPUT');
|
|
32
|
+
upgrade={previousSnapshot:predecessor.snapshot,upgradeSql};
|
|
33
|
+
}
|
|
34
|
+
return prepareOwnerDatabase({root,target:config.target,connection:config.connection,baseSnapshot:contract.snapshot,schemaSql,...upgrade,apply:mode==='--apply'||mode==='--auto'&&environment.FORGE_RELEASE_COMMAND==='publish',signal});
|
|
35
|
+
}
|
|
36
|
+
export async function buildOwnerSchemaContract({root,target,domain,outputPath,signal}){
|
|
37
|
+
validateOwnerDatabaseTarget(target);
|
|
38
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||domain?.name!==target.schema||domain.owner!==target.schemaOwner||!Array.isArray(domain.tables)||typeof outputPath!=='string')throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
39
|
+
root=path.resolve(root);if(fs.realpathSync(root)!==root)throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
40
|
+
const relative=path.relative(root,outputPath);
|
|
41
|
+
if(!relative||relative.startsWith('..')||path.isAbsolute(relative)||fs.realpathSync(path.dirname(outputPath))!==path.dirname(outputPath))throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
42
|
+
const require=createRequire(path.join(root,'package.json')),schemaFile=require.resolve(domain.entry),sql=fs.readFileSync(schemaFile);
|
|
43
|
+
if(sql.length>65536||sql.includes(13))throw Error('OWNER_DATABASE_SCHEMA_REQUIRES_LF');
|
|
44
|
+
const {startNativeFixture}=await import('./native-fixture.mjs');
|
|
45
|
+
const fixture=await startNativeFixture({root,runtimeRoot:root,label:'release-schema-contract',domains:[domain],signal});
|
|
46
|
+
let result={status:'FAIL'};
|
|
47
|
+
try{
|
|
48
|
+
const snapshot=await readSchemaSnapshot({query:sql=>fixture.owner.query(sql)},target.schema,{signal});
|
|
49
|
+
if(snapshot?.owner!==target.schemaOwner)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
50
|
+
const contract={schemaVersion:1,schemaSqlDigest:'sha256:'+createHash('sha256').update(sql).digest('hex'),snapshot};
|
|
51
|
+
const bytes=Buffer.from(JSON.stringify(contract,null,2)+'\n');if(bytes.length>1048576)throw Error('OWNER_DATABASE_CONTRACT_BUDGET');
|
|
52
|
+
if(fs.existsSync(outputPath)&&(!fs.lstatSync(outputPath).isFile()||fs.lstatSync(outputPath).isSymbolicLink()))throw Error('OWNER_DATABASE_CONTRACT_INPUT');
|
|
53
|
+
fs.writeFileSync(outputPath,bytes);result={status:'PASS'};
|
|
54
|
+
return {status:'SCHEMA_CONTRACT_BUILT',schema:target.schema,bytes:bytes.length,schemaSqlDigest:contract.schemaSqlDigest};
|
|
55
|
+
}catch(error){result={status:'FAIL',error:error.message};throw error;}
|
|
56
|
+
finally{await fixture.dispose(result);}
|
|
57
|
+
}
|
|
58
|
+
function identifier(value){if(typeof value!=='string'||!/^[a-z][a-z0-9_]{0,62}$/.test(value)||/^(pg_|platform(?:_|$))/.test(value)||['public','auth','storage','vault','extensions','information_schema'].includes(value))throw Error('OWNER_DATABASE_TARGET_INVALID');return value;}
|
|
59
|
+
const literal=value=>"'"+String(value).replaceAll("'","''")+"'";
|
|
60
|
+
export function validateOwnerDatabaseTarget(target){
|
|
61
|
+
if(!target||target.schemaVersion!==2||Object.keys(target).sort().join(',')!=='applicationRole,projectRef,schema,schemaOwner,schemaVersion,solutionId,workerRole'||typeof target.projectRef!=='string'||!/^[a-z]{20}$/.test(target.projectRef)||typeof target.solutionId!=='string'||!/^[a-z][a-z0-9-]{0,63}$/.test(target.solutionId))throw Error('OWNER_DATABASE_TARGET_INVALID');
|
|
62
|
+
for(const key of ['schema','schemaOwner',...kinds.map(kind=>kind+'Role')])identifier(target[key]);
|
|
63
|
+
if(new Set(['schemaOwner',...kinds.map(kind=>kind+'Role')].map(key=>target[key])).size!==3)throw Error('OWNER_DATABASE_TARGET_INVALID');
|
|
64
|
+
return target;
|
|
65
|
+
}
|
|
66
|
+
export function validateOwnerDatabaseCredentials(value,target){
|
|
67
|
+
validateOwnerDatabaseTarget(target);
|
|
68
|
+
if(!value||value.schemaVersion!==2||!isDeepStrictEqual(value.target,target)||!value.credentials||Object.keys(value.credentials).sort().join(',')!=='application,worker')throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
69
|
+
for(const kind of kinds)if(value.credentials[kind]?.role!==target[kind+'Role']||typeof value.credentials[kind].password!=='string'||!/^[a-f0-9]{64}$/.test(value.credentials[kind].password))throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
70
|
+
if(new Set(kinds.map(kind=>value.credentials[kind].password)).size!==2)throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
function namespace(target){return 'link-light/runtime/'+validateOwnerDatabaseTarget(target).solutionId+'/v2';}
|
|
74
|
+
const aclOrder=(a,b)=>Buffer.compare(Buffer.from(a.grantee+'\0'+a.privilege+'\0'+a.grantor),Buffer.from(b.grantee+'\0'+b.privilege+'\0'+b.grantor));
|
|
75
|
+
/** Keep policy membership in the neutral runtime group, but move the owner's
|
|
76
|
+
* object GRANTs to its application login. Other runtimes then fail GRANT checks
|
|
77
|
+
* before RLS; Worker identities receive no business table privileges. */
|
|
78
|
+
export function scopedSchemaSnapshot(base,applicationRole){
|
|
79
|
+
identifier(applicationRole);
|
|
80
|
+
if(!base||base.unsupported!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
81
|
+
const visit=value=>Array.isArray(value)?value.map(visit):value&&typeof value==='object'?Object.fromEntries(Object.entries(value).map(([key,item])=>[key,key==='acl'?item.map(acl=>({...acl,grantee:acl.grantee==='platform_runtime'?applicationRole:acl.grantee})).sort(aclOrder):visit(item)])):value;
|
|
82
|
+
return visit(base);
|
|
83
|
+
}
|
|
84
|
+
export function scopeSchemaPrivilegesSql(base,applicationRole){
|
|
85
|
+
identifier(base?.schemaName);identifier(applicationRole);
|
|
86
|
+
if(base.unsupported!==false||!Array.isArray(base.relations)||!Array.isArray(base.functions))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
87
|
+
const statements=[];
|
|
88
|
+
function grants(acl,object,allowed,column){
|
|
89
|
+
if(!Array.isArray(acl))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
90
|
+
for(const grant of acl.filter(item=>item.grantee==='platform_runtime')){
|
|
91
|
+
if(!allowed.includes(grant.privilege)||grant.grantable!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
92
|
+
const privilege=grant.privilege+(column?'('+identifier(column)+')':'');
|
|
93
|
+
statements.push(`GRANT ${privilege} ON ${object} TO ${applicationRole};REVOKE ${privilege} ON ${object} FROM platform_runtime;`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
grants(base.acl,'SCHEMA '+base.schemaName,['USAGE','CREATE']);
|
|
97
|
+
for(const relation of base.relations){
|
|
98
|
+
identifier(relation.name);
|
|
99
|
+
if(!['r','p','v','m','S'].includes(relation.kind))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
100
|
+
const object=(relation.kind==='S'?'SEQUENCE ':'TABLE ')+base.schemaName+'.'+relation.name;
|
|
101
|
+
grants(relation.acl,object,relation.kind==='S'?['SELECT','UPDATE','USAGE']:['SELECT','INSERT','UPDATE','DELETE','TRUNCATE','REFERENCES','TRIGGER','MAINTAIN']);
|
|
102
|
+
for(const column of relation.columns)grants(column.acl,object,['SELECT','INSERT','UPDATE','REFERENCES'],column.name);
|
|
103
|
+
}
|
|
104
|
+
for(const fn of base.functions){
|
|
105
|
+
identifier(fn.name);if(typeof fn.arguments!=='string'||!/^[a-zA-Z0-9_ [\],]*$/.test(fn.arguments))throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
106
|
+
grants(fn.acl,'FUNCTION '+base.schemaName+'.'+fn.name+'('+fn.arguments+')',['EXECUTE']);
|
|
107
|
+
}
|
|
108
|
+
return statements.join('\n');
|
|
109
|
+
}
|
|
110
|
+
function fresh(target){return {schemaVersion:2,target,credentials:Object.fromEntries(kinds.map(kind=>[kind,{role:target[kind+'Role'],password:randomBytes(32).toString('hex')}]))};}
|
|
111
|
+
export async function readOwnerDatabaseCredentials(options){
|
|
112
|
+
const {target,signal}=options;validateOwnerDatabaseTarget(target);
|
|
113
|
+
const client=options.client??createSupabaseReleaseClient(options.root,target.projectRef);
|
|
114
|
+
const observed=await client.query(`DO $isolation$ BEGIN ${vaultIsolationGuard} END $isolation$;SELECT description,decrypted_secret FROM vault.decrypted_secrets WHERE name=${literal(namespace(target))};`,{signal});
|
|
115
|
+
if(!observed.rows.length)return null;
|
|
116
|
+
if(observed.rows.length!==1||observed.rows[0].description!==ownership)throw Error('OWNER_DATABASE_OWNERSHIP_UNKNOWN');
|
|
117
|
+
let value;try{value=JSON.parse(observed.rows[0].decrypted_secret);}catch{throw Error('OWNER_DATABASE_CREDENTIALS_INVALID');}
|
|
118
|
+
return validateOwnerDatabaseCredentials(value,target);
|
|
119
|
+
}
|
|
120
|
+
function assertSqlSchema(schema,expected){
|
|
121
|
+
const sql=schemaSnapshotSql(schema).replace(/;$/,'');
|
|
122
|
+
return `IF (SELECT snapshot FROM (${sql}) observed) IS DISTINCT FROM ${expected===null?'NULL::jsonb':literal(JSON.stringify(expected))+'::jsonb'} THEN RAISE EXCEPTION 'OWNER_DATABASE_SCHEMA_CHANGED';END IF;`;
|
|
123
|
+
}
|
|
124
|
+
/** Pure transaction builder for an explicit operator. No admin credential is
|
|
125
|
+
* returned or installed in runtime; no business row is updated or deleted.
|
|
126
|
+
* @param {{target:object,credentials:object,baseSnapshot:object,observedSnapshot:object|null,schemaSql:string,previousSnapshot?:object,upgradeSql?:string}} options */
|
|
127
|
+
export function ownerDatabaseBootstrapSql({target,credentials,baseSnapshot,observedSnapshot,schemaSql,previousSnapshot=undefined,upgradeSql=undefined}){
|
|
128
|
+
validateOwnerDatabaseCredentials(credentials,target);
|
|
129
|
+
if(baseSnapshot?.schemaName!==target.schema||baseSnapshot.owner!==target.schemaOwner||baseSnapshot.unsupported!==false)throw Error('OWNER_DATABASE_SCHEMA_INVALID');
|
|
130
|
+
const scoped=scopedSchemaSnapshot(baseSnapshot,target.applicationRole);
|
|
131
|
+
const upgrade=previousSnapshot&&isDeepStrictEqual(previousSnapshot,observedSnapshot);
|
|
132
|
+
if(observedSnapshot!==null&&!isDeepStrictEqual(baseSnapshot,observedSnapshot)&&!isDeepStrictEqual(scoped,observedSnapshot)&&!upgrade)throw Error('SCHEMA_CONTRACT_MISMATCH');
|
|
133
|
+
let ddl='';
|
|
134
|
+
if(observedSnapshot===null||upgrade){
|
|
135
|
+
const sql=upgrade?upgradeSql:schemaSql;
|
|
136
|
+
if(typeof sql!=='string'||Buffer.byteLength(sql)>65536||!/^\s*(?:--[^\n]*\n)*BEGIN;[\s\S]+COMMIT;\s*$/.test(sql))throw Error('OWNER_DATABASE_SCHEMA_SQL_INVALID');
|
|
137
|
+
ddl=sql.replace(/^(\s*(?:--[^\n]*\n)*)BEGIN;/,'$1').replace(/COMMIT;\s*$/,'');
|
|
138
|
+
}
|
|
139
|
+
const encoded=Buffer.from(JSON.stringify(credentials)).toString('base64'),name=namespace(target),roleList=kinds.map(kind=>literal(target[kind+'Role'])).join(',');
|
|
140
|
+
return `BEGIN;SELECT pg_advisory_xact_lock(hashtextextended(${literal(ownership+'/'+target.solutionId)},0));
|
|
141
|
+
DO $preflight$ BEGIN
|
|
142
|
+
IF to_regclass('platform_private.runtime_roles') IS NULL OR to_regclass('vault.decrypted_secrets') IS NULL THEN RAISE EXCEPTION 'BOOTSTRAP_BASELINE_REQUIRED';END IF;
|
|
143
|
+
${vaultIsolationGuard}
|
|
144
|
+
${assertSqlSchema(target.schema,observedSnapshot)}
|
|
145
|
+
END $preflight$;
|
|
146
|
+
${ddl}
|
|
147
|
+
DO $credentials$ DECLARE payload jsonb:=convert_from(decode('${encoded}','base64'),'UTF8')::jsonb;BEGIN
|
|
148
|
+
IF EXISTS(SELECT 1 FROM vault.secrets WHERE name=${literal(name)}) THEN
|
|
149
|
+
IF NOT EXISTS(SELECT 1 FROM vault.decrypted_secrets WHERE name=${literal(name)} AND description=${literal(ownership)} AND decrypted_secret::jsonb=payload)
|
|
150
|
+
OR (SELECT count(*) FROM pg_roles WHERE rolname IN (${roleList}))<>2 THEN RAISE EXCEPTION 'OWNER_DATABASE_OWNERSHIP_UNKNOWN';END IF;
|
|
151
|
+
ELSE
|
|
152
|
+
IF EXISTS(SELECT 1 FROM pg_roles WHERE rolname IN (${roleList})) THEN RAISE EXCEPTION 'BOOTSTRAP_ROLE_ALREADY_EXISTS';END IF;
|
|
153
|
+
${kinds.map(kind=>`EXECUTE format('CREATE ROLE %I LOGIN INHERIT NOSUPERUSER NOBYPASSRLS NOCREATEDB NOCREATEROLE NOREPLICATION PASSWORD %L',${literal(target[kind+'Role'])},payload->'credentials'->'${kind}'->>'password');`).join('\n')}
|
|
154
|
+
PERFORM vault.create_secret(payload::text,${literal(name)},${literal(ownership)});
|
|
155
|
+
END IF;
|
|
156
|
+
IF EXISTS(SELECT 1 FROM pg_roles r WHERE rolname IN (${roleList}) AND (NOT rolcanlogin OR rolsuper OR rolbypassrls OR rolcreatedb OR rolcreaterole OR rolreplication))
|
|
157
|
+
OR NOT EXISTS(SELECT 1 FROM pg_roles r WHERE rolname=${literal(target.schemaOwner)} AND NOT(rolcanlogin OR rolsuper OR rolbypassrls OR rolcreatedb OR rolcreaterole OR rolreplication)) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
158
|
+
IF EXISTS(SELECT 1 FROM platform_private.runtime_roles WHERE role_name IN (${roleList}) AND solution_id<>${literal(target.solutionId)}) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_SCOPE_CONFLICT';END IF;
|
|
159
|
+
END $credentials$;
|
|
160
|
+
GRANT platform_runtime TO ${target.applicationRole} WITH INHERIT TRUE,SET FALSE;
|
|
161
|
+
GRANT platform_worker TO ${target.workerRole} WITH INHERIT TRUE,SET FALSE;
|
|
162
|
+
INSERT INTO platform_private.runtime_roles(role_name,solution_id) VALUES(${literal(target.applicationRole)},${literal(target.solutionId)}),(${literal(target.workerRole)},${literal(target.solutionId)}) ON CONFLICT(role_name) DO NOTHING;
|
|
163
|
+
${isDeepStrictEqual(observedSnapshot,scoped)?'':scopeSchemaPrivilegesSql(baseSnapshot,target.applicationRole)}
|
|
164
|
+
DO $verify$ BEGIN
|
|
165
|
+
IF EXISTS(SELECT 1 FROM pg_auth_members m JOIN pg_roles member ON member.oid=m.member JOIN pg_roles parent ON parent.oid=m.roleid
|
|
166
|
+
WHERE member.rolname IN (${roleList}) AND NOT (
|
|
167
|
+
member.rolname=${literal(target.applicationRole)} AND parent.rolname='platform_runtime' AND m.inherit_option AND NOT m.set_option
|
|
168
|
+
OR member.rolname=${literal(target.workerRole)} AND parent.rolname='platform_worker' AND m.inherit_option AND NOT m.set_option)) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
169
|
+
IF EXISTS(SELECT 1 FROM pg_namespace n JOIN pg_roles owner ON owner.oid=n.nspowner WHERE owner.rolname IN (${roleList})) THEN RAISE EXCEPTION 'OWNER_DATABASE_ROLE_UNSAFE';END IF;
|
|
170
|
+
${assertSqlSchema(target.schema,scoped)}
|
|
171
|
+
END $verify$;COMMIT;
|
|
172
|
+
SELECT 'OWNER_DATABASE_PREPARED' AS status;`;
|
|
173
|
+
}
|
|
174
|
+
export function ownerDatabaseConnections(credentials,connection){
|
|
175
|
+
const {target}=credentials;validateOwnerDatabaseCredentials(credentials,target);
|
|
176
|
+
if(!connection||connection.port!==5432||connection.database!=='postgres'||connection.ssl?.rejectUnauthorized!==true||typeof connection.ssl.ca!=='string'||!connection.ssl.ca||typeof connection.host!=='string'||!connection.host||connection.host.length>255)throw Error('OWNER_DATABASE_CONNECTION_INVALID');
|
|
177
|
+
return Object.fromEntries(kinds.map(kind=>{const credential=credentials.credentials[kind],url=new URL('postgresql://placeholder/');url.hostname=connection.host;url.port=String(connection.port);url.pathname='/'+connection.database;url.username=credential.role+'.'+target.projectRef;url.password=credential.password;return [kind,{connectionString:url.href,role:credential.role,max:kind==='application'?2:1,connectionTimeoutMs:10000,idleTimeoutMs:10000,statementTimeoutMs:10000,ssl:connection.ssl}];}));
|
|
178
|
+
}
|
|
179
|
+
/** The caller supplies its public platform verifier and owned readiness port.
|
|
180
|
+
* Pools and their ordinary TLS identities are closed before returning. */
|
|
181
|
+
export async function verifyOwnerDatabaseConnections({credentials,connection,verify,signal}){
|
|
182
|
+
if(typeof verify!=='function')throw Error('OWNER_DATABASE_VERIFIER_REQUIRED');
|
|
183
|
+
const database=ownerDatabaseConnections(credentials,connection),target=credentials.target;
|
|
184
|
+
for(const kind of kinds){
|
|
185
|
+
signal?.throwIfAborted();const config=database[kind],pool=new pg.Pool({connectionString:config.connectionString,ssl:config.ssl,max:1,connectionTimeoutMillis:10000,statement_timeout:10000,allowExitOnIdle:true});let fault;pool.on('error',error=>{fault??=error;});
|
|
186
|
+
try{await verify(pool,{kind,role:config.role,solutionId:target.solutionId});if(fault)throw Error('OWNER_DATABASE_CONNECTION_UNKNOWN',{cause:fault});}
|
|
187
|
+
finally{await pool.end();}
|
|
188
|
+
}
|
|
189
|
+
return {roles:kinds.map(kind=>target[kind+'Role']),verifiedTls:true};
|
|
190
|
+
}
|
|
191
|
+
export async function prepareOwnerDatabase(options){
|
|
192
|
+
const {target,signal}=options;validateOwnerDatabaseTarget(target);
|
|
193
|
+
const client=options.client??createSupabaseReleaseClient(options.root,target.projectRef);
|
|
194
|
+
const existing=await readOwnerDatabaseCredentials({...options,client});
|
|
195
|
+
const observedSnapshot=await readSchemaSnapshot(client,target.schema,{signal});
|
|
196
|
+
const baseSnapshot=options.baseSnapshot,scoped=scopedSchemaSnapshot(baseSnapshot,target.applicationRole);
|
|
197
|
+
const upgrade=options.previousSnapshot&&isDeepStrictEqual(options.previousSnapshot,observedSnapshot);
|
|
198
|
+
if(observedSnapshot!==null&&!isDeepStrictEqual(baseSnapshot,observedSnapshot)&&!isDeepStrictEqual(scoped,observedSnapshot)&&!upgrade)throw Error('SCHEMA_CONTRACT_MISMATCH');
|
|
199
|
+
if(!options.apply)return {status:existing&&isDeepStrictEqual(scoped,observedSnapshot)?'SCHEMA_AND_CREDENTIALS_PREPARED':upgrade?'UPGRADE_REQUIRED':'SETUP_REQUIRED',writes:0,schema:target.schema};
|
|
200
|
+
if(process.env.FORGE_RELEASE_COMMAND&&process.env.FORGE_RELEASE_COMMAND!=='publish')throw Error('OWNER_DATABASE_READ_ONLY_CHECK');
|
|
201
|
+
const credentials=existing??fresh(target);
|
|
202
|
+
ownerDatabaseConnections(credentials,options.connection);
|
|
203
|
+
await client.query(ownerDatabaseBootstrapSql({...options,credentials,observedSnapshot}),{signal});
|
|
204
|
+
const persisted=await readOwnerDatabaseCredentials({...options,client});
|
|
205
|
+
if(!persisted||!isDeepStrictEqual(persisted,credentials))throw Error('OWNER_DATABASE_COMMIT_UNKNOWN');
|
|
206
|
+
assertSchemaSnapshot(scoped,await readSchemaSnapshot(client,target.schema,{signal}));
|
|
207
|
+
// A live ordinary connection proves the pooler routing identity and TLS before
|
|
208
|
+
// any application environment receives it. The platform host does full grants.
|
|
209
|
+
for(const config of Object.values(ownerDatabaseConnections(credentials,options.connection))){
|
|
210
|
+
const db=new pg.Client({...config,connectionTimeoutMillis:10000,statement_timeout:10000});
|
|
211
|
+
try{await db.connect();const row=(await db.query('SELECT current_user AS role,session_user')).rows[0];if(row.role!==config.role||row.session_user!==config.role)throw Error('OWNER_DATABASE_LOGIN_MISMATCH');}
|
|
212
|
+
finally{await db.end();}
|
|
213
|
+
}
|
|
214
|
+
return {status:'PREPARED',writes:1,credentialWrite:!existing,schema:target.schema,roles:kinds.map(kind=>target[kind+'Role']),verifiedTls:true};
|
|
215
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function prepareOwnerOperatorBuild(options:{root:string;signal?:AbortSignal}):Promise<{status:'OWNER_OPERATOR_BUILT';schemaVersion:1;kind:'operator';files:{path:string;bytes:number;sha256:string}[]}>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const fail=()=>Error('OWNER_OPERATOR_BUILD_INVALID');
|
|
6
|
+
const sha=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
7
|
+
const declaration="import {exerciseOwnerProduction,createOwnerProductionPlan} from '@xlinklight/testkit/owner-production';\nimport type {AcceptanceOracleStatement} from '@xlinklight/testkit/acceptance-oracle';\nexport type OwnerAcceptanceOptions=Omit<Parameters<typeof exerciseOwnerProduction>[0],'solutionId'|'execution'|'browser'|'providers'|'oracleStatements'>;\nexport const oracles:readonly AcceptanceOracleStatement[];\nexport function acceptOwnerRelease(options:OwnerAcceptanceOptions):ReturnType<typeof exerciseOwnerProduction>;\nexport function createOwnerAcceptancePlan(options:OwnerAcceptanceOptions):ReturnType<typeof createOwnerProductionPlan>;\n";
|
|
8
|
+
async function regular(file,maximum){const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>maximum||await fs.realpath(file)!==file)throw fail();return fs.readFile(file);}
|
|
9
|
+
/** Build the installed trusted oracle library. Public Core ports stay public
|
|
10
|
+
* imports; no provider SDK or uploaded business module is evaluated here. */
|
|
11
|
+
export async function prepareOwnerOperatorBuild({root,signal}={}){
|
|
12
|
+
if(typeof root!=='string'||!path.isAbsolute(root))throw fail();signal?.throwIfAborted();root=await fs.realpath(root);
|
|
13
|
+
const entry=path.join(root,'deployment/operator.mjs');await regular(entry,65536);
|
|
14
|
+
const {build}=await import('vite');
|
|
15
|
+
const result=await build({root,configFile:false,envDir:false,publicDir:false,logLevel:'silent',build:{write:false,emptyOutDir:false,minify:false,sourcemap:false,lib:{entry,formats:['es'],fileName:()=> 'main.mjs'},rolldownOptions:{external:id=>!id.startsWith('.')&&!path.isAbsolute(id)}}});
|
|
16
|
+
signal?.throwIfAborted();const outputs=(Array.isArray(result)?result:[result]).flatMap(value=>value.output??[]);
|
|
17
|
+
if(outputs.length!==1||outputs[0].type!=='chunk'||outputs[0].dynamicImports.length||outputs[0].fileName!=='main.mjs'||!outputs[0].exports.includes('acceptOwnerRelease')||!outputs[0].exports.includes('createOwnerAcceptancePlan')||!outputs[0].exports.includes('oracles'))throw fail();
|
|
18
|
+
const chunk=outputs[0],allowed=new Set(['@xlinklight/testkit/owner-production','@xlinklight/testkit/acceptance-oracle','@xlinklight/platform/worker','node:assert/strict']);
|
|
19
|
+
if(chunk.imports.some(value=>!allowed.has(value)))throw fail();
|
|
20
|
+
for(const id of chunk.moduleIds){if(id.startsWith('\0'))continue;const relative=path.relative(root,id);if(!relative||relative==='..'||relative.startsWith('..'+path.sep)||path.isAbsolute(relative)||relative.split(path.sep).includes('node_modules'))throw fail();}
|
|
21
|
+
const phaseDeclaration=chunk.exports.includes('productionPhaseNames')?"export const productionPhaseNames:ReturnType<typeof import('@xlinklight/testkit/owner-production').ownerProductionPhaseNames>;\n":'';
|
|
22
|
+
const files=[{path:'main.mjs',bytes:Buffer.from(chunk.code)},{path:'main.d.mts',bytes:Buffer.from(declaration+phaseDeclaration)}];if(files[0].bytes.byteLength>4194304)throw fail();
|
|
23
|
+
const output=path.join(root,'dist-operator');let exists=true;try{await fs.lstat(output);}catch(error){if(error.code!=='ENOENT')throw error;exists=false;}
|
|
24
|
+
if(exists){
|
|
25
|
+
if(await fs.realpath(output)!==output)throw fail();const names=(await fs.readdir(output)).sort();if(names.join(',')!=='main.d.mts,main.mjs,operator-build.json')throw fail();
|
|
26
|
+
const previous=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await regular(path.join(output,'operator-build.json'),65536)));
|
|
27
|
+
if(previous.schemaVersion!==1||previous.kind!=='operator'||!Array.isArray(previous.files)||previous.files.length!==2)throw fail();
|
|
28
|
+
for(const file of files){const record=previous.files.find(value=>value.path===file.path),bytes=await regular(path.join(output,file.path),4194304);if(record?.sha256!==sha(bytes)||record.bytes!==bytes.byteLength)throw fail();}
|
|
29
|
+
}else await fs.mkdir(output);
|
|
30
|
+
const record={schemaVersion:1,kind:'operator',files:files.map(file=>({path:file.path,bytes:file.bytes.byteLength,sha256:sha(file.bytes)}))};
|
|
31
|
+
for(const file of files)await fs.writeFile(path.join(output,file.path),file.bytes);
|
|
32
|
+
await fs.writeFile(path.join(output,'operator-build.json'),JSON.stringify(record)+'\n');return {status:'OWNER_OPERATOR_BUILT',...record};
|
|
33
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import type {CloudflareBuildProcessReceipt} from './cloudflare-build.mjs';
|
|
2
|
+
export function prepareOwnerPackageBuild(options:{root:string;pnpm?:string;signal?:AbortSignal}):Promise<{schemaVersion:2;name:string;version:string;integrity:string;archiveBytes:number;process:CloudflareBuildProcessReceipt}>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {captureCli} from './release-cli.mjs';
|
|
5
|
+
|
|
6
|
+
const fail=()=>Error('OWNER_PACKAGE_BUILD_INVALID');
|
|
7
|
+
const integrity=bytes=>'sha512-'+createHash('sha512').update(bytes).digest('base64');
|
|
8
|
+
async function read(root,relative,maximum){const file=path.join(root,relative),info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>maximum||await fs.realpath(file)!==file)throw fail();return fs.readFile(file);}
|
|
9
|
+
/** One actual neutral business-library archive. Runtime bundles and receipts
|
|
10
|
+
* are produced separately, so the archive identity has no self-reference. */
|
|
11
|
+
export async function prepareOwnerPackageBuild({root,pnpm=process.env.npm_execpath??process.env.LINK_LIGHT_PNPM_CLI,signal}){
|
|
12
|
+
if(typeof root!=='string'||!path.isAbsolute(root)||typeof pnpm!=='string'||!path.isAbsolute(pnpm))throw fail();
|
|
13
|
+
signal?.throwIfAborted();root=await fs.realpath(root);if(!(await fs.stat(pnpm)).isFile())throw fail();
|
|
14
|
+
const metadata=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await read(root,'package.json',65536)));
|
|
15
|
+
if(metadata.packageManager!=='pnpm@10.33.2'||!/^@[a-z0-9._-]+\/[a-z0-9._-]+$/.test(metadata.name??'')||!/^\d+\.\d+\.\d+$/.test(metadata.version??'')||!Array.isArray(metadata.files)||!metadata.files.length)throw fail();
|
|
16
|
+
for(const entry of metadata.files){
|
|
17
|
+
if(typeof entry!=='string'||!entry||/[\\:*?\0]/.test(entry)||entry.split('/').some(part=>part==='..'))throw fail();
|
|
18
|
+
const selected=entry.replace(/^\.\//,'').replace(/\/$/,'');
|
|
19
|
+
if(!selected||['dist-worker','dist-runtime','apps/runtime','deployment/generated'].some(runtime=>runtime===selected||runtime.startsWith(selected+'/')||selected.startsWith(runtime+'/')))throw fail();
|
|
20
|
+
}
|
|
21
|
+
const deployment=path.join(root,'deployment');if(await fs.realpath(deployment)!==deployment)throw fail();
|
|
22
|
+
const directory=path.join(deployment,'generated');await fs.mkdir(directory,{recursive:true});if(await fs.realpath(directory)!==directory)throw fail();
|
|
23
|
+
let old;try{old=await read(root,'deployment/generated/package.tgz',67108864);}catch(error){if(error.code!=='ENOENT')throw error;}
|
|
24
|
+
if(old){const record=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(await read(root,'deployment/generated/package-build.json',65536)));if(record.schemaVersion!==2||record.name!==metadata.name||record.integrity!==integrity(old))throw fail();}
|
|
25
|
+
const version=await captureCli(process.execPath,[pnpm,'--version'],{cwd:root,signal,timeoutMs:15000,maxOutputBytes:65536});if(version.stdout.toString().trim()!=='10.33.2')throw fail();
|
|
26
|
+
const captured=await captureCli(process.execPath,[pnpm,'pack','--out','deployment/generated/package.tgz'],{cwd:root,signal,timeoutMs:60000,maxOutputBytes:65536});
|
|
27
|
+
const bytes=await read(root,'deployment/generated/package.tgz',67108864),record={schemaVersion:2,name:metadata.name,version:metadata.version,integrity:integrity(bytes)};
|
|
28
|
+
await fs.writeFile(path.join(directory,'package-build.json'),JSON.stringify(record)+'\n');return {...record,archiveBytes:bytes.byteLength,process:captured.process};
|
|
29
|
+
}
|