@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,215 +1,215 @@
|
|
|
1
|
-
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
-
import {releaseBytes,releaseJson} from './release-control.mjs';
|
|
3
|
-
import {createBrowserOperationOwner} from './browser-operation-owner.mjs';
|
|
4
|
-
export function productionBrowserOrigins(target,manifest){
|
|
5
|
-
const core=new URL(target.coreOrigin),ui=new URL(manifest?.ui?.url);
|
|
6
|
-
if(core.protocol!=='https:'||core.origin!==target.coreOrigin||ui.protocol!=='https:'||ui.username||ui.password||ui.hash||ui.search||ui.href!==manifest.ui.url||ui.origin===core.origin)throw Error('RELEASE_PRODUCTION_BROWSER_ORIGIN_INVALID');
|
|
7
|
-
return [core.origin,ui.origin];
|
|
8
|
-
}
|
|
9
|
-
/** Real core page, actual remote iframe and deployed finite Worker. The owner's
|
|
10
|
-
* browser definition supplies input gestures and visible literal value oracles. */
|
|
11
|
-
export async function exerciseOwnerProductionBrowser({target,id,account,fixture,definition,browserHost,writeEvidence,signal,request=fetch,priorSubmission,qualificationJobId}){
|
|
12
|
-
if(typeof request!=='function'||!browserHost||typeof browserHost.open!=='function'||typeof writeEvidence!=='function')throw Error('RELEASE_PRODUCTION_BROWSER_INPUT_INVALID');
|
|
13
|
-
const allowedOrigins=productionBrowserOrigins(target,id.manifest);
|
|
14
|
-
const core=new URL(target.coreOrigin);
|
|
15
|
-
const invokePath=typeof id.instance==='string'?'/api/instances/'+encodeURIComponent(id.instance)+'/invoke':undefined;
|
|
16
|
-
const checkbox=priorSubmission?.verifiedCheckbox;
|
|
17
|
-
let owned,browser,context,cookie,failure,result,failed=false,retiring=false,contextClosing,loginRequested=false,step='launch';
|
|
18
|
-
const errors=[],routes=new Set(),routeErrors=[],operation=createBrowserOperationOwner();
|
|
19
|
-
const login={};
|
|
20
|
-
const browserCookie=async()=>{
|
|
21
|
-
const selected=(await context.cookies(core.origin)).filter(value=>value.name==='link_light_session');
|
|
22
|
-
login.storedCookies=selected.length;
|
|
23
|
-
const session=selected[0];
|
|
24
|
-
if(selected.length!==1||!(/^[a-f0-9]{64}$/.test(session.value))||session.domain!==core.hostname||session.path!=='/'||!session.httpOnly||!session.secure||session.sameSite!=='Strict')return;
|
|
25
|
-
return session.name+'='+session.value;
|
|
26
|
-
};
|
|
27
|
-
const closeContext=()=>contextClosing??=Promise.resolve().then(()=>context?.close());operation.setCancel(closeContext);
|
|
28
|
-
const stop=()=>operation.fail(signal.reason??Error('RELEASE_PRODUCTION_BROWSER_ABORTED'));signal?.addEventListener('abort',stop,{once:true});
|
|
29
|
-
try{
|
|
30
|
-
owned=await browserHost.open({allowedOrigins,signal});browser=owned.browser;
|
|
31
|
-
signal?.throwIfAborted();context=await operation.openContext(()=>browser.newContext({viewport:{width:1280,height:900},serviceWorkers:'block'}));
|
|
32
|
-
await context.route('**/*',route=>{
|
|
33
|
-
if(retiring)return route.abort('aborted').catch(()=>{});
|
|
34
|
-
const task=(async()=>{
|
|
35
|
-
const url=new URL(route.request().url());if(url.protocol!=='https:'||!allowedOrigins.includes(url.origin)){operation.fail(Error('RELEASE_PRODUCTION_BROWSER_ORIGIN_REJECTED'));await route.abort('blockedbyclient');return;}operation.guard();
|
|
36
|
-
if(url.origin===core.origin&&url.pathname==='/api/auth/login'&&!url.search&&route.request().method()==='POST'){
|
|
37
|
-
const posted=route.request().postData();
|
|
38
|
-
if(typeof posted!=='string'||Buffer.byteLength(posted)>8192)throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_REQUEST_INVALID');
|
|
39
|
-
const input=JSON.parse(posted);
|
|
40
|
-
if(loginRequested||!input||Object.keys(input).length!==2||input.email!==account.email||input.password!==account.password)throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_REQUEST_INVALID');
|
|
41
|
-
loginRequested=true;
|
|
42
|
-
// Browser Run can remove Set-Cookie when fulfilling a fetched response.
|
|
43
|
-
// Forward the browser's exact login through the owned Core transport.
|
|
44
|
-
const response=await releaseBytes(url,{method:'POST',headers:{origin:core.origin,'content-type':'application/json'},body:posted},{signal,request,maximumBytes:8192});
|
|
45
|
-
login.status=response.status;
|
|
46
|
-
const cookies=response.headers.getSetCookie();
|
|
47
|
-
const parts=cookies[0]?.split(';').map(value=>value.trim())??[];
|
|
48
|
-
const [issued,...flags]=parts;
|
|
49
|
-
if(typeof issued==='string'&&/^link_light_session=[a-f0-9]{64}$/.test(issued))cookie=issued;
|
|
50
|
-
const ttlFlag=flags.find(flag=>/^Max-Age=[1-9][0-9]{0,5}$/i.test(flag));
|
|
51
|
-
const ttl=ttlFlag?Number(ttlFlag.split('=')[1]):0;
|
|
52
|
-
if(response.status!==204||cookies.length!==1||!cookie||ttl<1||ttl>86400||!['Path=/','HttpOnly','SameSite=Strict','Secure'].every(flag=>flags.includes(flag))||flags.some(flag=>/^Domain=/i.test(flag)))throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_FAILED');
|
|
53
|
-
await context.addCookies([{name:'link_light_session',value:cookie.slice('link_light_session='.length),url:core.origin+'/',secure:true,httpOnly:true,sameSite:'Strict',expires:Math.floor(Date.now()/1000)+ttl}]);
|
|
54
|
-
operation.guard();
|
|
55
|
-
await route.fulfill({status:204,headers:{'cache-control':'no-store'}});
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
// route.continue follows redirects without routing each hop. Fetch one
|
|
59
|
-
// response through the official context API and refuse redirects before
|
|
60
|
-
// fulfillment. Passing the original response retains its exact bytes and
|
|
61
|
-
// cookie headers through Playwright's same-connection response handle.
|
|
62
|
-
let runtimeRead=false;
|
|
63
|
-
if(url.origin===core.origin&&url.pathname===invokePath&&!url.search&&route.request().method()==='POST'){
|
|
64
|
-
let body;
|
|
65
|
-
try{body=route.request().postDataJSON();}catch{/* Unrecognized requests keep the original single attempt. */}
|
|
66
|
-
if(checkbox&&body?.method==='submit'){
|
|
67
|
-
const sha=createHash('sha256').update(JSON.stringify([body.input?.operationId,body.input?.input])).digest('hex');
|
|
68
|
-
if(sha!==checkbox.submissionSha256)throw Error('RELEASE_PRODUCTION_BROWSER_CHECKBOX_PAYLOAD_MISMATCH');
|
|
69
|
-
}
|
|
70
|
-
runtimeRead=(body?.method==='getRun'&&typeof body.input?.runId==='string')||(body?.method==='query'&&typeof body.input?.queryId==='string');
|
|
71
|
-
}
|
|
72
|
-
const fetchOptions={maxRedirects:0,maxRetries:0,timeout:runtimeRead?45000:30000};
|
|
73
|
-
let response;
|
|
74
|
-
try{response=await route.fetch(fetchOptions);}
|
|
75
|
-
catch(error){
|
|
76
|
-
if(!runtimeRead||signal?.aborted||error?.name!=='TimeoutError')throw error;
|
|
77
|
-
operation.guard();
|
|
78
|
-
// The actual browser receives the timeout. The scenario still has to
|
|
79
|
-
// prove its submitted result and its explicit visible and reload reads.
|
|
80
|
-
await route.abort('timedout');
|
|
81
|
-
return;
|
|
82
|
-
}
|
|
83
|
-
try{
|
|
84
|
-
if(response.status()>=300&&response.status()<400){operation.fail(Error('RELEASE_PRODUCTION_BROWSER_REDIRECT_REJECTED'));await route.abort('blockedbyclient');return;}
|
|
85
|
-
operation.guard();await route.fulfill({response});
|
|
86
|
-
}finally{await response.dispose();}
|
|
87
|
-
})();
|
|
88
|
-
routes.add(task);task.then(()=>routes.delete(task),error=>{routeErrors.push(error);routes.delete(task);operation.fail(error);});return task.catch(()=>{});
|
|
89
|
-
});
|
|
90
|
-
// The finite HTTP/iframe contract needs no WebSocket egress.
|
|
91
|
-
await context.routeWebSocket('**/*',socket=>{
|
|
92
|
-
if(retiring)return socket.close({code:1008,reason:'Acceptance closing'}).catch(()=>{});
|
|
93
|
-
const task=Promise.resolve().then(()=>{operation.fail(Error('RELEASE_PRODUCTION_BROWSER_WEBSOCKET_REJECTED'));return socket.close({code:1008,reason:'Finite production acceptance'});});
|
|
94
|
-
routes.add(task);task.then(()=>routes.delete(task),error=>{routeErrors.push(error);routes.delete(task);operation.fail(error);});return task.catch(()=>{});
|
|
95
|
-
});
|
|
96
|
-
await operation.run(async()=>{
|
|
97
|
-
step='login';
|
|
98
|
-
const page=await context.newPage();page.setDefaultTimeout(30000);const pageErrors=[],foreignOrigins=new Set();
|
|
99
|
-
page.on('pageerror',()=>pageErrors.push('PAGE_ERROR'));
|
|
100
|
-
page.on('request',request=>{const url=new URL(request.url());if(['https:','http:'].includes(url.protocol)&&!allowedOrigins.includes(url.origin))foreignOrigins.add(url.origin);});
|
|
101
|
-
await page.goto(target.coreOrigin+'/login',{waitUntil:'domcontentloaded'});
|
|
102
|
-
await page.locator('#login-email').fill(account.email);await page.locator('#login-password').fill(account.password);
|
|
103
|
-
const signedPromise=page.waitForResponse(response=>response.url()===target.coreOrigin+'/api/auth/login'&&response.request().method()==='POST');void signedPromise.catch(()=>{});
|
|
104
|
-
await page.locator('button[type="submit"]').click();const signed=await signedPromise;
|
|
105
|
-
login.status=signed.status();
|
|
106
|
-
// The isolated browser's cookie store is authoritative after the exact
|
|
107
|
-
// login response. Browser hosts may filter Set-Cookie response headers.
|
|
108
|
-
const stored=await browserCookie();
|
|
109
|
-
if(signed.status()!==204||!cookie||stored!==cookie)throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_FAILED');
|
|
110
|
-
await page.waitForURL(target.coreOrigin+'/');
|
|
111
|
-
const instanceUrl=target.coreOrigin+'/api/instances/'+encodeURIComponent(id.instance);
|
|
112
|
-
const iframe=page.locator('.remote-business iframe');
|
|
113
|
-
const ownedFrame=page.frameLocator('.remote-business iframe');let submitted=0,restored=false;
|
|
114
|
-
const frame=checkbox?new Proxy(ownedFrame,{get(target,key){
|
|
115
|
-
if(key==='getByRole')return (role,options)=>{
|
|
116
|
-
if(role!=='checkbox')return target.getByRole(role,options);
|
|
117
|
-
if(options?.exact!==true||options.name!==checkbox.ariaLabel)throw Error('RELEASE_PRODUCTION_BROWSER_CHECKBOX_LABEL_MISMATCH');
|
|
118
|
-
// A recovered visible entity is tied to the previously verified fact,
|
|
119
|
-
// even when more than one accessible selector has the same label.
|
|
120
|
-
step='business-checkbox';
|
|
121
|
-
return target.locator('label').filter({hasText:checkbox.fingerprint,visible:true})
|
|
122
|
-
.locator('input[type="checkbox"][aria-label='+JSON.stringify(checkbox.ariaLabel)+']');
|
|
123
|
-
};
|
|
124
|
-
const value=Reflect.get(target,key,target);
|
|
125
|
-
return typeof value==='function'?value.bind(target):value;
|
|
126
|
-
}}):ownedFrame;
|
|
127
|
-
const open=async()=>{
|
|
128
|
-
// Set the locale before opening the owned view. Changing the iframe's
|
|
129
|
-
// fragment after it mounts can leave the previous bridge channel running.
|
|
130
|
-
await page.locator('main .business-card').first().waitFor();
|
|
131
|
-
const switchToEnglish=page.locator('main[lang="zh-CN"] .language');
|
|
132
|
-
if(await switchToEnglish.isVisible())await switchToEnglish.click();
|
|
133
|
-
// Candidate instances use the workbench's solution-ID label because the
|
|
134
|
-
// candidate manifest is deliberately absent from the live catalog.
|
|
135
|
-
const name=qualificationJobId?id.manifest.solutionId:id.manifest.display.en.name;
|
|
136
|
-
const cards=page.locator('main[lang="en"] .business-card').filter({has:page.getByRole('heading',{name,exact:true})});
|
|
137
|
-
const card=qualificationJobId?cards.filter({has:page.getByRole('button',{name:'Open',exact:true})}):cards;
|
|
138
|
-
const opened=page.waitForResponse(response=>response.url()===instanceUrl&&response.request().method()==='GET');
|
|
139
|
-
void opened.catch(()=>{});
|
|
140
|
-
await card.getByRole('button',{name:'Open',exact:true}).click();
|
|
141
|
-
if((await opened).status()!==200)throw Error('RELEASE_PRODUCTION_BROWSER_OPEN_FAILED');
|
|
142
|
-
await page.locator('.remote-business iframe[src]').waitFor();
|
|
143
|
-
const src=await iframe.getAttribute('src');
|
|
144
|
-
if(await iframe.getAttribute('sandbox')!=='allow-scripts allow-same-origin'||await iframe.getAttribute('referrerpolicy')!=='no-referrer'||!src?.startsWith(id.manifest.ui.url+'#'))throw Error('RELEASE_PRODUCTION_IFRAME_BOUNDARY_FAILED');
|
|
145
|
-
const parameters=new URLSearchParams(new URL(src).hash.slice(1));
|
|
146
|
-
if(parameters.get('locale')!=='en'||parameters.get('instanceId')!==id.instance||parameters.get('hostOrigin')!==core.origin)throw Error('RELEASE_PRODUCTION_IFRAME_BOUNDARY_FAILED');
|
|
147
|
-
};
|
|
148
|
-
step='iframe';await open();
|
|
149
|
-
const withStep=async(label,run)=>{
|
|
150
|
-
const previous=step;step=label;
|
|
151
|
-
const output=await run();
|
|
152
|
-
step=previous;return output;
|
|
153
|
-
};
|
|
154
|
-
const checkedFixture=Object.fromEntries(Object.entries(fixture).map(([name,value])=>[name,typeof value==='function'?function(...args){operation.guard();return value.apply(fixture,args);}:value]));
|
|
155
|
-
checkedFixture.query=(...args)=>withStep('business-public-query',()=>{operation.guard();return fixture.query(...args);});
|
|
156
|
-
checkedFixture.oracle={...fixture.oracle,query(...args){return withStep('business-oracle',()=>{operation.guard();return fixture.oracle.query(...args);});}};
|
|
157
|
-
const view={page,frame,async submit(button){
|
|
158
|
-
operation.guard();
|
|
159
|
-
if(priorSubmission&&!restored){
|
|
160
|
-
step='business-run-read';
|
|
161
|
-
const ref={runId:priorSubmission.runId,instanceId:id.instance};
|
|
162
|
-
const run=await checkedFixture.invoke(id,'getRun',{runId:ref.runId});
|
|
163
|
-
if(run?.runId!==ref.runId||run.instanceId!==ref.instanceId||run.releaseDigest!==id.manifest.releaseDigest||run.status!=='succeeded')throw Error('RELEASE_PRODUCTION_BROWSER_RECOVERY_UNPROVEN');
|
|
164
|
-
const proof=priorSubmission.commit;
|
|
165
|
-
if(!proof||proof.results!==1||proof.terminal!==1||proof.outbox!==1)throw Error('RELEASE_PRODUCTION_BROWSER_RECOVERY_UNPROVEN');
|
|
166
|
-
restored=true;
|
|
167
|
-
return ref;
|
|
168
|
-
}
|
|
169
|
-
step='business-submit';
|
|
170
|
-
const responsePromise=page.waitForResponse(response=>{if(response.url()!==instanceUrl+'/invoke'||response.request().method()!=='POST')return false;try{return response.request().postDataJSON()?.method==='submit';}catch{return false;}});void responsePromise.catch(()=>{});
|
|
171
|
-
await button.click();const response=await responsePromise;if(response.status()!==200)throw Error('RELEASE_PRODUCTION_BROWSER_SUBMIT_FAILED');
|
|
172
|
-
step='business-checkpoint';const ref=await response.json();await checkedFixture.trackRun(id,ref);
|
|
173
|
-
step='business-commit';await checkedFixture.awaitBrowserCommit(ref);submitted++;return ref;
|
|
174
|
-
}};
|
|
175
|
-
step='business-gesture';const data=await definition.prepare(checkedFixture,id,priorSubmission?.label??'browser-'+randomUUID());
|
|
176
|
-
await definition.drive(checkedFixture,id,data,view);
|
|
177
|
-
if(restored&&!submitted)await definition.reread(checkedFixture,id,data,view);
|
|
178
|
-
step='business-result';await definition.visible(checkedFixture,id,data,view);
|
|
179
|
-
step='screenshots';await writeEvidence('desktop.png',await page.screenshot({fullPage:false}),{signal});
|
|
180
|
-
step='reload';await page.reload({waitUntil:'domcontentloaded'});await open();await definition.reread(checkedFixture,id,data,view);await definition.visible(checkedFixture,id,data,view);
|
|
181
|
-
await page.setViewportSize({width:360,height:780});
|
|
182
|
-
if(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1)||await frame.locator('body').evaluate(body=>body.scrollWidth>innerWidth+1))throw Error('RELEASE_PRODUCTION_BROWSER_OVERFLOW');
|
|
183
|
-
await writeEvidence('mobile.png',await page.screenshot({fullPage:false}),{signal});
|
|
184
|
-
if(pageErrors.length||foreignOrigins.size||(!submitted&&!restored))throw Error('RELEASE_PRODUCTION_BROWSER_FAILED');
|
|
185
|
-
result={status:'PASS',actualCorePage:true,actualDistinctOriginIframe:true,actualUiSubmit:true,submissions:submitted+Number(restored),reload:true,mobileWidth:360};
|
|
186
|
-
});
|
|
187
|
-
}catch(error){failure=error;failed=true;}
|
|
188
|
-
finally{
|
|
189
|
-
retiring=true;
|
|
190
|
-
if(!operation.failed)await Promise.allSettled([...routes]);
|
|
191
|
-
try{await closeContext();}catch(error){errors.push(error);}
|
|
192
|
-
signal?.removeEventListener('abort',stop);
|
|
193
|
-
await Promise.allSettled([...routes]);for(const error of routeErrors)if(!failed||error!==failure)errors.push(error);
|
|
194
|
-
if(cookie)try{
|
|
195
|
-
const response=await releaseJson(target.coreOrigin+'/api/auth/logout',{method:'POST',headers:{cookie,origin:target.coreOrigin,'content-type':'application/json'},body:'{}'},{request});
|
|
196
|
-
const revoked=await releaseJson(target.coreOrigin+'/api/me',{headers:{cookie}},{request});
|
|
197
|
-
if(response.status!==204||revoked.status!==403||revoked.value?.code!=='NOT_AUTHORIZED')throw Error('RELEASE_PRODUCTION_BROWSER_LOGOUT_UNKNOWN');
|
|
198
|
-
}catch(error){errors.push(error);}
|
|
199
|
-
if(operation.failed&&(!failed||operation.firstError!==failure)&&!errors.includes(operation.firstError))errors.push(operation.firstError);
|
|
200
|
-
try{if(owned){const closure=await owned.close();if(closure?.status!=='closed'||typeof closure.sessionId!=='string'||!closure.sessionId)throw Error('RELEASE_PRODUCTION_BROWSER_SESSION_CLOSE_UNCONFIRMED');if(result)result.session=closure;}}catch(error){errors.push(error);}
|
|
201
|
-
if((failed||errors.length)&&browserHost.recordFailure){
|
|
202
|
-
const describe=(error,depth=0)=>{
|
|
203
|
-
const message=typeof error?.message==='string'?error.message:'';
|
|
204
|
-
const locator=/^(?:frameLocator|locator)\.(check|fill|waitFor|click|evaluate|isVisible):/.exec(message)?.[1];
|
|
205
|
-
const locatorCode=locator?'BROWSER_LOCATOR_'+locator.toUpperCase():undefined;
|
|
206
|
-
const code=/^[A-Z][A-Z0-9_]{1,100}$/.test(message)?message:error?.name==='TimeoutError'?'BROWSER_TIMEOUT':error?.code==='ERR_ASSERTION'||error?.name==='AssertionError'?'BROWSER_ASSERTION':error?.name==='TypeError'?'BROWSER_TYPE_ERROR':message.includes('strict mode violation')?'BROWSER_STRICT_SELECTOR':message.includes('did not change its checked state')?'BROWSER_CHECK_STATE_UNCHANGED':'BROWSER_UNCLASSIFIED';
|
|
207
|
-
const status=Number.isSafeInteger(error?.status)&&error.status>=400&&error.status<=599?['BROWSER_HTTP_'+error.status]:[];
|
|
208
|
-
const codes=[code,...status,...(locatorCode?[locatorCode]:[])];
|
|
209
|
-
return depth<2&&error instanceof AggregateError?[...codes,...error.errors.slice(0,4).flatMap(value=>describe(value,depth+1))]:codes;
|
|
210
|
-
};
|
|
211
|
-
try{await browserHost.recordFailure({step,login,codes:[...new Set([...(failed?describe(failure):[]),...errors.slice(0,4).flatMap(error=>describe(error))])].slice(0,16)});}catch(error){errors.push(error);}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
if(errors.length)throw new AggregateError([...(failed?[failure]:[]),...errors],'RELEASE_PRODUCTION_BROWSER_CLOSE_UNKNOWN');if(failed)throw failure;return result;
|
|
215
|
-
}
|
|
1
|
+
import {createHash,randomUUID} from 'node:crypto';
|
|
2
|
+
import {releaseBytes,releaseJson} from './release-control.mjs';
|
|
3
|
+
import {createBrowserOperationOwner} from './browser-operation-owner.mjs';
|
|
4
|
+
export function productionBrowserOrigins(target,manifest){
|
|
5
|
+
const core=new URL(target.coreOrigin),ui=new URL(manifest?.ui?.url);
|
|
6
|
+
if(core.protocol!=='https:'||core.origin!==target.coreOrigin||ui.protocol!=='https:'||ui.username||ui.password||ui.hash||ui.search||ui.href!==manifest.ui.url||ui.origin===core.origin)throw Error('RELEASE_PRODUCTION_BROWSER_ORIGIN_INVALID');
|
|
7
|
+
return [core.origin,ui.origin];
|
|
8
|
+
}
|
|
9
|
+
/** Real core page, actual remote iframe and deployed finite Worker. The owner's
|
|
10
|
+
* browser definition supplies input gestures and visible literal value oracles. */
|
|
11
|
+
export async function exerciseOwnerProductionBrowser({target,id,account,fixture,definition,browserHost,writeEvidence,signal,request=fetch,priorSubmission,qualificationJobId}){
|
|
12
|
+
if(typeof request!=='function'||!browserHost||typeof browserHost.open!=='function'||typeof writeEvidence!=='function')throw Error('RELEASE_PRODUCTION_BROWSER_INPUT_INVALID');
|
|
13
|
+
const allowedOrigins=productionBrowserOrigins(target,id.manifest);
|
|
14
|
+
const core=new URL(target.coreOrigin);
|
|
15
|
+
const invokePath=typeof id.instance==='string'?'/api/instances/'+encodeURIComponent(id.instance)+'/invoke':undefined;
|
|
16
|
+
const checkbox=priorSubmission?.verifiedCheckbox;
|
|
17
|
+
let owned,browser,context,cookie,failure,result,failed=false,retiring=false,contextClosing,loginRequested=false,step='launch';
|
|
18
|
+
const errors=[],routes=new Set(),routeErrors=[],operation=createBrowserOperationOwner();
|
|
19
|
+
const login={};
|
|
20
|
+
const browserCookie=async()=>{
|
|
21
|
+
const selected=(await context.cookies(core.origin)).filter(value=>value.name==='link_light_session');
|
|
22
|
+
login.storedCookies=selected.length;
|
|
23
|
+
const session=selected[0];
|
|
24
|
+
if(selected.length!==1||!(/^[a-f0-9]{64}$/.test(session.value))||session.domain!==core.hostname||session.path!=='/'||!session.httpOnly||!session.secure||session.sameSite!=='Strict')return;
|
|
25
|
+
return session.name+'='+session.value;
|
|
26
|
+
};
|
|
27
|
+
const closeContext=()=>contextClosing??=Promise.resolve().then(()=>context?.close());operation.setCancel(closeContext);
|
|
28
|
+
const stop=()=>operation.fail(signal.reason??Error('RELEASE_PRODUCTION_BROWSER_ABORTED'));signal?.addEventListener('abort',stop,{once:true});
|
|
29
|
+
try{
|
|
30
|
+
owned=await browserHost.open({allowedOrigins,signal});browser=owned.browser;
|
|
31
|
+
signal?.throwIfAborted();context=await operation.openContext(()=>browser.newContext({viewport:{width:1280,height:900},serviceWorkers:'block'}));
|
|
32
|
+
await context.route('**/*',route=>{
|
|
33
|
+
if(retiring)return route.abort('aborted').catch(()=>{});
|
|
34
|
+
const task=(async()=>{
|
|
35
|
+
const url=new URL(route.request().url());if(url.protocol!=='https:'||!allowedOrigins.includes(url.origin)){operation.fail(Error('RELEASE_PRODUCTION_BROWSER_ORIGIN_REJECTED'));await route.abort('blockedbyclient');return;}operation.guard();
|
|
36
|
+
if(url.origin===core.origin&&url.pathname==='/api/auth/login'&&!url.search&&route.request().method()==='POST'){
|
|
37
|
+
const posted=route.request().postData();
|
|
38
|
+
if(typeof posted!=='string'||Buffer.byteLength(posted)>8192)throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_REQUEST_INVALID');
|
|
39
|
+
const input=JSON.parse(posted);
|
|
40
|
+
if(loginRequested||!input||Object.keys(input).length!==2||input.email!==account.email||input.password!==account.password)throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_REQUEST_INVALID');
|
|
41
|
+
loginRequested=true;
|
|
42
|
+
// Browser Run can remove Set-Cookie when fulfilling a fetched response.
|
|
43
|
+
// Forward the browser's exact login through the owned Core transport.
|
|
44
|
+
const response=await releaseBytes(url,{method:'POST',headers:{origin:core.origin,'content-type':'application/json'},body:posted},{signal,request,maximumBytes:8192});
|
|
45
|
+
login.status=response.status;
|
|
46
|
+
const cookies=response.headers.getSetCookie();
|
|
47
|
+
const parts=cookies[0]?.split(';').map(value=>value.trim())??[];
|
|
48
|
+
const [issued,...flags]=parts;
|
|
49
|
+
if(typeof issued==='string'&&/^link_light_session=[a-f0-9]{64}$/.test(issued))cookie=issued;
|
|
50
|
+
const ttlFlag=flags.find(flag=>/^Max-Age=[1-9][0-9]{0,5}$/i.test(flag));
|
|
51
|
+
const ttl=ttlFlag?Number(ttlFlag.split('=')[1]):0;
|
|
52
|
+
if(response.status!==204||cookies.length!==1||!cookie||ttl<1||ttl>86400||!['Path=/','HttpOnly','SameSite=Strict','Secure'].every(flag=>flags.includes(flag))||flags.some(flag=>/^Domain=/i.test(flag)))throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_FAILED');
|
|
53
|
+
await context.addCookies([{name:'link_light_session',value:cookie.slice('link_light_session='.length),url:core.origin+'/',secure:true,httpOnly:true,sameSite:'Strict',expires:Math.floor(Date.now()/1000)+ttl}]);
|
|
54
|
+
operation.guard();
|
|
55
|
+
await route.fulfill({status:204,headers:{'cache-control':'no-store'}});
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
// route.continue follows redirects without routing each hop. Fetch one
|
|
59
|
+
// response through the official context API and refuse redirects before
|
|
60
|
+
// fulfillment. Passing the original response retains its exact bytes and
|
|
61
|
+
// cookie headers through Playwright's same-connection response handle.
|
|
62
|
+
let runtimeRead=false;
|
|
63
|
+
if(url.origin===core.origin&&url.pathname===invokePath&&!url.search&&route.request().method()==='POST'){
|
|
64
|
+
let body;
|
|
65
|
+
try{body=route.request().postDataJSON();}catch{/* Unrecognized requests keep the original single attempt. */}
|
|
66
|
+
if(checkbox&&body?.method==='submit'){
|
|
67
|
+
const sha=createHash('sha256').update(JSON.stringify([body.input?.operationId,body.input?.input])).digest('hex');
|
|
68
|
+
if(sha!==checkbox.submissionSha256)throw Error('RELEASE_PRODUCTION_BROWSER_CHECKBOX_PAYLOAD_MISMATCH');
|
|
69
|
+
}
|
|
70
|
+
runtimeRead=(body?.method==='getRun'&&typeof body.input?.runId==='string')||(body?.method==='query'&&typeof body.input?.queryId==='string');
|
|
71
|
+
}
|
|
72
|
+
const fetchOptions={maxRedirects:0,maxRetries:0,timeout:runtimeRead?45000:30000};
|
|
73
|
+
let response;
|
|
74
|
+
try{response=await route.fetch(fetchOptions);}
|
|
75
|
+
catch(error){
|
|
76
|
+
if(!runtimeRead||signal?.aborted||error?.name!=='TimeoutError')throw error;
|
|
77
|
+
operation.guard();
|
|
78
|
+
// The actual browser receives the timeout. The scenario still has to
|
|
79
|
+
// prove its submitted result and its explicit visible and reload reads.
|
|
80
|
+
await route.abort('timedout');
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
try{
|
|
84
|
+
if(response.status()>=300&&response.status()<400){operation.fail(Error('RELEASE_PRODUCTION_BROWSER_REDIRECT_REJECTED'));await route.abort('blockedbyclient');return;}
|
|
85
|
+
operation.guard();await route.fulfill({response});
|
|
86
|
+
}finally{await response.dispose();}
|
|
87
|
+
})();
|
|
88
|
+
routes.add(task);task.then(()=>routes.delete(task),error=>{routeErrors.push(error);routes.delete(task);operation.fail(error);});return task.catch(()=>{});
|
|
89
|
+
});
|
|
90
|
+
// The finite HTTP/iframe contract needs no WebSocket egress.
|
|
91
|
+
await context.routeWebSocket('**/*',socket=>{
|
|
92
|
+
if(retiring)return socket.close({code:1008,reason:'Acceptance closing'}).catch(()=>{});
|
|
93
|
+
const task=Promise.resolve().then(()=>{operation.fail(Error('RELEASE_PRODUCTION_BROWSER_WEBSOCKET_REJECTED'));return socket.close({code:1008,reason:'Finite production acceptance'});});
|
|
94
|
+
routes.add(task);task.then(()=>routes.delete(task),error=>{routeErrors.push(error);routes.delete(task);operation.fail(error);});return task.catch(()=>{});
|
|
95
|
+
});
|
|
96
|
+
await operation.run(async()=>{
|
|
97
|
+
step='login';
|
|
98
|
+
const page=await context.newPage();page.setDefaultTimeout(30000);const pageErrors=[],foreignOrigins=new Set();
|
|
99
|
+
page.on('pageerror',()=>pageErrors.push('PAGE_ERROR'));
|
|
100
|
+
page.on('request',request=>{const url=new URL(request.url());if(['https:','http:'].includes(url.protocol)&&!allowedOrigins.includes(url.origin))foreignOrigins.add(url.origin);});
|
|
101
|
+
await page.goto(target.coreOrigin+'/login',{waitUntil:'domcontentloaded'});
|
|
102
|
+
await page.locator('#login-email').fill(account.email);await page.locator('#login-password').fill(account.password);
|
|
103
|
+
const signedPromise=page.waitForResponse(response=>response.url()===target.coreOrigin+'/api/auth/login'&&response.request().method()==='POST');void signedPromise.catch(()=>{});
|
|
104
|
+
await page.locator('button[type="submit"]').click();const signed=await signedPromise;
|
|
105
|
+
login.status=signed.status();
|
|
106
|
+
// The isolated browser's cookie store is authoritative after the exact
|
|
107
|
+
// login response. Browser hosts may filter Set-Cookie response headers.
|
|
108
|
+
const stored=await browserCookie();
|
|
109
|
+
if(signed.status()!==204||!cookie||stored!==cookie)throw Error('RELEASE_PRODUCTION_BROWSER_LOGIN_FAILED');
|
|
110
|
+
await page.waitForURL(target.coreOrigin+'/');
|
|
111
|
+
const instanceUrl=target.coreOrigin+'/api/instances/'+encodeURIComponent(id.instance);
|
|
112
|
+
const iframe=page.locator('.remote-business iframe');
|
|
113
|
+
const ownedFrame=page.frameLocator('.remote-business iframe');let submitted=0,restored=false;
|
|
114
|
+
const frame=checkbox?new Proxy(ownedFrame,{get(target,key){
|
|
115
|
+
if(key==='getByRole')return (role,options)=>{
|
|
116
|
+
if(role!=='checkbox')return target.getByRole(role,options);
|
|
117
|
+
if(options?.exact!==true||options.name!==checkbox.ariaLabel)throw Error('RELEASE_PRODUCTION_BROWSER_CHECKBOX_LABEL_MISMATCH');
|
|
118
|
+
// A recovered visible entity is tied to the previously verified fact,
|
|
119
|
+
// even when more than one accessible selector has the same label.
|
|
120
|
+
step='business-checkbox';
|
|
121
|
+
return target.locator('label').filter({hasText:checkbox.fingerprint,visible:true})
|
|
122
|
+
.locator('input[type="checkbox"][aria-label='+JSON.stringify(checkbox.ariaLabel)+']');
|
|
123
|
+
};
|
|
124
|
+
const value=Reflect.get(target,key,target);
|
|
125
|
+
return typeof value==='function'?value.bind(target):value;
|
|
126
|
+
}}):ownedFrame;
|
|
127
|
+
const open=async()=>{
|
|
128
|
+
// Set the locale before opening the owned view. Changing the iframe's
|
|
129
|
+
// fragment after it mounts can leave the previous bridge channel running.
|
|
130
|
+
await page.locator('main .business-card').first().waitFor();
|
|
131
|
+
const switchToEnglish=page.locator('main[lang="zh-CN"] .language');
|
|
132
|
+
if(await switchToEnglish.isVisible())await switchToEnglish.click();
|
|
133
|
+
// Candidate instances use the workbench's solution-ID label because the
|
|
134
|
+
// candidate manifest is deliberately absent from the live catalog.
|
|
135
|
+
const name=qualificationJobId?id.manifest.solutionId:id.manifest.display.en.name;
|
|
136
|
+
const cards=page.locator('main[lang="en"] .business-card').filter({has:page.getByRole('heading',{name,exact:true})});
|
|
137
|
+
const card=qualificationJobId?cards.filter({has:page.getByRole('button',{name:'Open',exact:true})}):cards;
|
|
138
|
+
const opened=page.waitForResponse(response=>response.url()===instanceUrl&&response.request().method()==='GET');
|
|
139
|
+
void opened.catch(()=>{});
|
|
140
|
+
await card.getByRole('button',{name:'Open',exact:true}).click();
|
|
141
|
+
if((await opened).status()!==200)throw Error('RELEASE_PRODUCTION_BROWSER_OPEN_FAILED');
|
|
142
|
+
await page.locator('.remote-business iframe[src]').waitFor();
|
|
143
|
+
const src=await iframe.getAttribute('src');
|
|
144
|
+
if(await iframe.getAttribute('sandbox')!=='allow-scripts allow-same-origin'||await iframe.getAttribute('referrerpolicy')!=='no-referrer'||!src?.startsWith(id.manifest.ui.url+'#'))throw Error('RELEASE_PRODUCTION_IFRAME_BOUNDARY_FAILED');
|
|
145
|
+
const parameters=new URLSearchParams(new URL(src).hash.slice(1));
|
|
146
|
+
if(parameters.get('locale')!=='en'||parameters.get('instanceId')!==id.instance||parameters.get('hostOrigin')!==core.origin)throw Error('RELEASE_PRODUCTION_IFRAME_BOUNDARY_FAILED');
|
|
147
|
+
};
|
|
148
|
+
step='iframe';await open();
|
|
149
|
+
const withStep=async(label,run)=>{
|
|
150
|
+
const previous=step;step=label;
|
|
151
|
+
const output=await run();
|
|
152
|
+
step=previous;return output;
|
|
153
|
+
};
|
|
154
|
+
const checkedFixture=Object.fromEntries(Object.entries(fixture).map(([name,value])=>[name,typeof value==='function'?function(...args){operation.guard();return value.apply(fixture,args);}:value]));
|
|
155
|
+
checkedFixture.query=(...args)=>withStep('business-public-query',()=>{operation.guard();return fixture.query(...args);});
|
|
156
|
+
checkedFixture.oracle={...fixture.oracle,query(...args){return withStep('business-oracle',()=>{operation.guard();return fixture.oracle.query(...args);});}};
|
|
157
|
+
const view={page,frame,async submit(button){
|
|
158
|
+
operation.guard();
|
|
159
|
+
if(priorSubmission&&!restored){
|
|
160
|
+
step='business-run-read';
|
|
161
|
+
const ref={runId:priorSubmission.runId,instanceId:id.instance};
|
|
162
|
+
const run=await checkedFixture.invoke(id,'getRun',{runId:ref.runId});
|
|
163
|
+
if(run?.runId!==ref.runId||run.instanceId!==ref.instanceId||run.releaseDigest!==id.manifest.releaseDigest||run.status!=='succeeded')throw Error('RELEASE_PRODUCTION_BROWSER_RECOVERY_UNPROVEN');
|
|
164
|
+
const proof=priorSubmission.commit;
|
|
165
|
+
if(!proof||proof.results!==1||proof.terminal!==1||proof.outbox!==1)throw Error('RELEASE_PRODUCTION_BROWSER_RECOVERY_UNPROVEN');
|
|
166
|
+
restored=true;
|
|
167
|
+
return ref;
|
|
168
|
+
}
|
|
169
|
+
step='business-submit';
|
|
170
|
+
const responsePromise=page.waitForResponse(response=>{if(response.url()!==instanceUrl+'/invoke'||response.request().method()!=='POST')return false;try{return response.request().postDataJSON()?.method==='submit';}catch{return false;}});void responsePromise.catch(()=>{});
|
|
171
|
+
await button.click();const response=await responsePromise;if(response.status()!==200)throw Error('RELEASE_PRODUCTION_BROWSER_SUBMIT_FAILED');
|
|
172
|
+
step='business-checkpoint';const ref=await response.json();await checkedFixture.trackRun(id,ref);
|
|
173
|
+
step='business-commit';await checkedFixture.awaitBrowserCommit(ref);submitted++;return ref;
|
|
174
|
+
}};
|
|
175
|
+
step='business-gesture';const data=await definition.prepare(checkedFixture,id,priorSubmission?.label??'browser-'+randomUUID());
|
|
176
|
+
await definition.drive(checkedFixture,id,data,view);
|
|
177
|
+
if(restored&&!submitted)await definition.reread(checkedFixture,id,data,view);
|
|
178
|
+
step='business-result';await definition.visible(checkedFixture,id,data,view);
|
|
179
|
+
step='screenshots';await writeEvidence('desktop.png',await page.screenshot({fullPage:false}),{signal});
|
|
180
|
+
step='reload';await page.reload({waitUntil:'domcontentloaded'});await open();await definition.reread(checkedFixture,id,data,view);await definition.visible(checkedFixture,id,data,view);
|
|
181
|
+
await page.setViewportSize({width:360,height:780});
|
|
182
|
+
if(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1)||await frame.locator('body').evaluate(body=>body.scrollWidth>innerWidth+1))throw Error('RELEASE_PRODUCTION_BROWSER_OVERFLOW');
|
|
183
|
+
await writeEvidence('mobile.png',await page.screenshot({fullPage:false}),{signal});
|
|
184
|
+
if(pageErrors.length||foreignOrigins.size||(!submitted&&!restored))throw Error('RELEASE_PRODUCTION_BROWSER_FAILED');
|
|
185
|
+
result={status:'PASS',actualCorePage:true,actualDistinctOriginIframe:true,actualUiSubmit:true,submissions:submitted+Number(restored),reload:true,mobileWidth:360};
|
|
186
|
+
});
|
|
187
|
+
}catch(error){failure=error;failed=true;}
|
|
188
|
+
finally{
|
|
189
|
+
retiring=true;
|
|
190
|
+
if(!operation.failed)await Promise.allSettled([...routes]);
|
|
191
|
+
try{await closeContext();}catch(error){errors.push(error);}
|
|
192
|
+
signal?.removeEventListener('abort',stop);
|
|
193
|
+
await Promise.allSettled([...routes]);for(const error of routeErrors)if(!failed||error!==failure)errors.push(error);
|
|
194
|
+
if(cookie)try{
|
|
195
|
+
const response=await releaseJson(target.coreOrigin+'/api/auth/logout',{method:'POST',headers:{cookie,origin:target.coreOrigin,'content-type':'application/json'},body:'{}'},{request});
|
|
196
|
+
const revoked=await releaseJson(target.coreOrigin+'/api/me',{headers:{cookie}},{request});
|
|
197
|
+
if(response.status!==204||revoked.status!==403||revoked.value?.code!=='NOT_AUTHORIZED')throw Error('RELEASE_PRODUCTION_BROWSER_LOGOUT_UNKNOWN');
|
|
198
|
+
}catch(error){errors.push(error);}
|
|
199
|
+
if(operation.failed&&(!failed||operation.firstError!==failure)&&!errors.includes(operation.firstError))errors.push(operation.firstError);
|
|
200
|
+
try{if(owned){const closure=await owned.close();if(closure?.status!=='closed'||typeof closure.sessionId!=='string'||!closure.sessionId)throw Error('RELEASE_PRODUCTION_BROWSER_SESSION_CLOSE_UNCONFIRMED');if(result)result.session=closure;}}catch(error){errors.push(error);}
|
|
201
|
+
if((failed||errors.length)&&browserHost.recordFailure){
|
|
202
|
+
const describe=(error,depth=0)=>{
|
|
203
|
+
const message=typeof error?.message==='string'?error.message:'';
|
|
204
|
+
const locator=/^(?:frameLocator|locator)\.(check|fill|waitFor|click|evaluate|isVisible):/.exec(message)?.[1];
|
|
205
|
+
const locatorCode=locator?'BROWSER_LOCATOR_'+locator.toUpperCase():undefined;
|
|
206
|
+
const code=/^[A-Z][A-Z0-9_]{1,100}$/.test(message)?message:error?.name==='TimeoutError'?'BROWSER_TIMEOUT':error?.code==='ERR_ASSERTION'||error?.name==='AssertionError'?'BROWSER_ASSERTION':error?.name==='TypeError'?'BROWSER_TYPE_ERROR':message.includes('strict mode violation')?'BROWSER_STRICT_SELECTOR':message.includes('did not change its checked state')?'BROWSER_CHECK_STATE_UNCHANGED':'BROWSER_UNCLASSIFIED';
|
|
207
|
+
const status=Number.isSafeInteger(error?.status)&&error.status>=400&&error.status<=599?['BROWSER_HTTP_'+error.status]:[];
|
|
208
|
+
const codes=[code,...status,...(locatorCode?[locatorCode]:[])];
|
|
209
|
+
return depth<2&&error instanceof AggregateError?[...codes,...error.errors.slice(0,4).flatMap(value=>describe(value,depth+1))]:codes;
|
|
210
|
+
};
|
|
211
|
+
try{await browserHost.recordFailure({step,login,codes:[...new Set([...(failed?describe(failure):[]),...errors.slice(0,4).flatMap(error=>describe(error))])].slice(0,16)});}catch(error){errors.push(error);}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if(errors.length)throw new AggregateError([...(failed?[failure]:[]),...errors],'RELEASE_PRODUCTION_BROWSER_CLOSE_UNKNOWN');if(failed)throw failure;return result;
|
|
215
|
+
}
|
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
export const isProductionAuthorizationRevision=value=>typeof value==='string'&&/^[1-9][0-9]{0,63}$/.test(value);
|
|
2
|
-
|
|
3
|
-
export async function acquireProductionInstance({session,principal,spaceId,release,links=[],onAcquired,refresh,observedInstance,qualificationJobId}){
|
|
4
|
-
let summary;
|
|
5
|
-
if(!qualificationJobId||observedInstance){
|
|
6
|
-
const current=(await session.call('/api/me/instances')).value;
|
|
7
|
-
const candidates=current.filter(item=>item.solutionId===release.solutionId&&item.spaceId===spaceId&&(!qualificationJobId||item.instanceId===observedInstance.id));
|
|
8
|
-
if(candidates.length>1)throw Error('RELEASE_PRODUCTION_INSTANCE_OWNERSHIP_UNKNOWN');
|
|
9
|
-
summary=candidates[0];
|
|
10
|
-
if(observedInstance&&(summary?.instanceId!==observedInstance.id||summary.enabled!==observedInstance.enabled||summary.authorizationRevision!==observedInstance.revision))throw Error('RELEASE_PRODUCTION_ACQUISITION_UNPROVEN');
|
|
11
|
-
}
|
|
12
|
-
if(!summary){
|
|
13
|
-
const scope=qualificationJobId?'/api/qualification/'+qualificationJobId:'/api';
|
|
14
|
-
const idempotencyKey='production-qualification-'+(qualificationJobId?qualificationJobId+'-':'')+release.solutionId;
|
|
15
|
-
summary=(await session.call(scope+'/spaces/'+encodeURIComponent(spaceId)+'/instances',{body:{solutionId:release.solutionId,expectedReleaseDigest:release.releaseDigest,idempotencyKey,links},expected:[201]})).value;
|
|
16
|
-
}
|
|
17
|
-
if(summary?.releaseDigest!==release.releaseDigest||summary.canManage!==true||summary.spaceId!==spaceId||summary.solutionId!==release.solutionId||typeof summary.instanceId!=='string'||!summary.instanceId||!isProductionAuthorizationRevision(summary.authorizationRevision))throw Error('RELEASE_PRODUCTION_INSTANCE_OWNERSHIP_UNKNOWN');
|
|
18
|
-
const id={session,principal,tenant:spaceId,instance:summary.instanceId,manifest:release};await onAcquired(id);
|
|
19
|
-
if(!summary.enabled){
|
|
20
|
-
let revision=summary.authorizationRevision;
|
|
21
|
-
if(links.length){
|
|
22
|
-
const changed=(await session.call('/api/instances/'+summary.instanceId+'/capabilities',{method:'PUT',body:{expectedAuthorizationRevision:revision,links}})).value;
|
|
23
|
-
if(!isProductionAuthorizationRevision(changed?.authorizationRevision)||BigInt(changed.authorizationRevision)!==BigInt(revision)+1n)throw Error('RELEASE_PRODUCTION_CAPABILITY_LINK_UNKNOWN');
|
|
24
|
-
revision=changed.authorizationRevision;
|
|
25
|
-
}
|
|
26
|
-
await session.call('/api/instances/'+summary.instanceId,{method:'PATCH',body:{enabled:true,expectedAuthorizationRevision:revision}});
|
|
27
|
-
}
|
|
28
|
-
await refresh(id);
|
|
29
|
-
return id;
|
|
30
|
-
}
|
|
31
|
-
export async function closeProductionInstances({ids,change,failure}){
|
|
32
|
-
const cleanup=[];
|
|
33
|
-
for(const id of ids.toReversed()){
|
|
34
|
-
try{
|
|
35
|
-
const all=(await id.session.call('/api/me/instances')).value,current=all.find(item=>item.instanceId===id.instance);
|
|
36
|
-
if(current?.enabled){id.context={...id.context,authorizationRevision:current.authorizationRevision};await change(id,false);}
|
|
37
|
-
}catch(error){cleanup.push(error);}
|
|
38
|
-
}
|
|
39
|
-
if(cleanup.length)throw new AggregateError([...(failure?[failure]:[]),...cleanup],'RELEASE_PRODUCTION_INSTANCE_CLOSE_UNKNOWN');
|
|
40
|
-
if(failure)throw failure;
|
|
41
|
-
}
|
|
1
|
+
export const isProductionAuthorizationRevision=value=>typeof value==='string'&&/^[1-9][0-9]{0,63}$/.test(value);
|
|
2
|
+
|
|
3
|
+
export async function acquireProductionInstance({session,principal,spaceId,release,links=[],onAcquired,refresh,observedInstance,qualificationJobId}){
|
|
4
|
+
let summary;
|
|
5
|
+
if(!qualificationJobId||observedInstance){
|
|
6
|
+
const current=(await session.call('/api/me/instances')).value;
|
|
7
|
+
const candidates=current.filter(item=>item.solutionId===release.solutionId&&item.spaceId===spaceId&&(!qualificationJobId||item.instanceId===observedInstance.id));
|
|
8
|
+
if(candidates.length>1)throw Error('RELEASE_PRODUCTION_INSTANCE_OWNERSHIP_UNKNOWN');
|
|
9
|
+
summary=candidates[0];
|
|
10
|
+
if(observedInstance&&(summary?.instanceId!==observedInstance.id||summary.enabled!==observedInstance.enabled||summary.authorizationRevision!==observedInstance.revision))throw Error('RELEASE_PRODUCTION_ACQUISITION_UNPROVEN');
|
|
11
|
+
}
|
|
12
|
+
if(!summary){
|
|
13
|
+
const scope=qualificationJobId?'/api/qualification/'+qualificationJobId:'/api';
|
|
14
|
+
const idempotencyKey='production-qualification-'+(qualificationJobId?qualificationJobId+'-':'')+release.solutionId;
|
|
15
|
+
summary=(await session.call(scope+'/spaces/'+encodeURIComponent(spaceId)+'/instances',{body:{solutionId:release.solutionId,expectedReleaseDigest:release.releaseDigest,idempotencyKey,links},expected:[201]})).value;
|
|
16
|
+
}
|
|
17
|
+
if(summary?.releaseDigest!==release.releaseDigest||summary.canManage!==true||summary.spaceId!==spaceId||summary.solutionId!==release.solutionId||typeof summary.instanceId!=='string'||!summary.instanceId||!isProductionAuthorizationRevision(summary.authorizationRevision))throw Error('RELEASE_PRODUCTION_INSTANCE_OWNERSHIP_UNKNOWN');
|
|
18
|
+
const id={session,principal,tenant:spaceId,instance:summary.instanceId,manifest:release};await onAcquired(id);
|
|
19
|
+
if(!summary.enabled){
|
|
20
|
+
let revision=summary.authorizationRevision;
|
|
21
|
+
if(links.length){
|
|
22
|
+
const changed=(await session.call('/api/instances/'+summary.instanceId+'/capabilities',{method:'PUT',body:{expectedAuthorizationRevision:revision,links}})).value;
|
|
23
|
+
if(!isProductionAuthorizationRevision(changed?.authorizationRevision)||BigInt(changed.authorizationRevision)!==BigInt(revision)+1n)throw Error('RELEASE_PRODUCTION_CAPABILITY_LINK_UNKNOWN');
|
|
24
|
+
revision=changed.authorizationRevision;
|
|
25
|
+
}
|
|
26
|
+
await session.call('/api/instances/'+summary.instanceId,{method:'PATCH',body:{enabled:true,expectedAuthorizationRevision:revision}});
|
|
27
|
+
}
|
|
28
|
+
await refresh(id);
|
|
29
|
+
return id;
|
|
30
|
+
}
|
|
31
|
+
export async function closeProductionInstances({ids,change,failure}){
|
|
32
|
+
const cleanup=[];
|
|
33
|
+
for(const id of ids.toReversed()){
|
|
34
|
+
try{
|
|
35
|
+
const all=(await id.session.call('/api/me/instances')).value,current=all.find(item=>item.instanceId===id.instance);
|
|
36
|
+
if(current?.enabled){id.context={...id.context,authorizationRevision:current.authorizationRevision};await change(id,false);}
|
|
37
|
+
}catch(error){cleanup.push(error);}
|
|
38
|
+
}
|
|
39
|
+
if(cleanup.length)throw new AggregateError([...(failure?[failure]:[]),...cleanup],'RELEASE_PRODUCTION_INSTANCE_CLOSE_UNKNOWN');
|
|
40
|
+
if(failure)throw failure;
|
|
41
|
+
}
|