@xlinklight/testkit 7.0.0-rc.0 → 8.0.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 -21
- package/README.md +171 -169
- package/package.json +11 -4
- package/src/architecture-database.d.mts +36 -36
- package/src/architecture-database.mjs +64 -64
- package/src/artifact-observation.mjs +50 -50
- package/src/browser-lifecycle.mjs +45 -45
- package/src/cloudflare-browser.mjs +41 -41
- package/src/cloudflare-pages.d.mts +34 -34
- package/src/cloudflare-pages.mjs +170 -170
- package/src/cloudflare-provider-http.mjs +32 -32
- package/src/cluster-directory.d.mts +16 -16
- package/src/cluster-directory.mjs +90 -90
- package/src/core-publishing.d.mts +75 -75
- package/src/core-publishing.mjs +214 -214
- package/src/dev-command-runner.mjs +97 -97
- package/src/fixture-path.mjs +19 -19
- package/src/function-admission.d.mts +1 -1
- package/src/function-admission.mjs +58 -58
- package/src/host-artifact.mjs +32 -32
- package/src/host-stop.mjs +15 -15
- package/src/lifecycle-trace.mjs +32 -32
- package/src/managed-native-fixture.d.mts +84 -84
- package/src/managed-native-fixture.mjs +209 -209
- package/src/native-fixture.mjs +125 -125
- package/src/native-platform.mjs +56 -56
- package/src/operator-accounts.mjs +103 -103
- package/src/owned-process.mjs +75 -75
- package/src/owner-build-cli.mjs +3 -4
- package/src/owner-database.mjs +215 -215
- package/src/owner-deployment-definition.mjs +31 -0
- package/src/owner-deployment.d.mts +32 -0
- package/src/owner-deployment.mjs +105 -0
- package/src/owner-operator-build.mjs +63 -33
- package/src/owner-production-browser.mjs +215 -215
- package/src/owner-production-instances.mjs +41 -41
- package/src/owner-production.d.mts +114 -104
- package/src/owner-production.mjs +350 -338
- package/src/owner-worker-build.mjs +83 -83
- package/src/prebuilt-output.d.mts +2 -2
- package/src/prebuilt-output.mjs +104 -104
- package/src/production-hosts.mjs +38 -38
- package/src/publisher-acceptance-host-cli.mjs +12 -5
- package/src/release-build.mjs +71 -71
- package/src/release-control.mjs +45 -45
- package/src/release-coordinator.d.mts +9 -9
- package/src/release-coordinator.mjs +222 -222
- package/src/release-credentials.d.mts +8 -8
- package/src/release-credentials.mjs +97 -97
- package/src/release-mutex.mjs +38 -38
- package/src/release-operator.d.mts +6 -6
- package/src/release-operator.mjs +59 -59
- package/src/release-supabase.d.mts +7 -7
- package/src/release-supabase.mjs +37 -37
- package/src/release-vercel.d.mts +22 -22
- package/src/release-vercel.mjs +51 -51
- package/src/release-writer.d.mts +6 -6
- package/src/release-writer.mjs +172 -172
- package/src/retained-postgres-shutdown.d.mts +51 -51
- package/src/retained-postgres-shutdown.mjs +262 -262
- package/src/temporary-acquisition.mjs +62 -62
- package/src/temporary-scope.d.mts +47 -47
- package/src/temporary-scope.mjs +268 -268
- package/src/worker-artifact.mjs +214 -214
|
@@ -1,103 +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
|
-
}
|
|
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
|
+
}
|
package/src/owned-process.mjs
CHANGED
|
@@ -1,75 +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
|
-
}
|
|
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
|
+
}
|
package/src/owner-build-cli.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import {fileURLToPath
|
|
4
|
+
import {fileURLToPath} from 'node:url';
|
|
5
5
|
|
|
6
6
|
const commands=new Set(['build-info','build-package','build-operator','build-worker','build-static-ui']);
|
|
7
7
|
/** Local owner builds only. Publication and credentials belong to the
|
|
@@ -15,9 +15,8 @@ export async function runOwnerBuildCommand({root,args}){
|
|
|
15
15
|
if(command==='build-package')return build.prepareOwnerPackageBuild({root});
|
|
16
16
|
if(command==='build-operator')return build.prepareOwnerOperatorBuild({root});
|
|
17
17
|
if(command==='build-worker'){
|
|
18
|
-
const
|
|
19
|
-
|
|
20
|
-
const selected=await import(pathToFileURL(entry).href);if(typeof selected.buildWorker!=='function')throw Error('OWNER_WORKER_BUILD_MODULE_INVALID');return selected.buildWorker({root});
|
|
18
|
+
const {buildOwnerDeploymentWorker}=await import('./owner-deployment.mjs');
|
|
19
|
+
return buildOwnerDeploymentWorker({root});
|
|
21
20
|
}
|
|
22
21
|
return build.prepareOwnerStaticUiBuild({root});
|
|
23
22
|
}
|