Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/typescript-worker-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,3 +175,7 @@ After #259, Studio run 47372776920 job 145267060105 still returned generic HTTP
## First release package — qualified archive, not a rebuild

Studio main `511e669bd05fcd51ceb987587b1ceae2669c81eb` passed the synchronized qualification (run 47411892451, job 145317300197; all five main workflows green). The observed 503 no longer reproduced after #261, without establishing the historical root cause. DB evidence is time-bound and must be renewed before release execution. Independently downloaded build artifact 15880808630 (run 47411892432 attempt 1): wrapper SHA-256 `2bb08e5045cff8731925bfcba173a4392427389bbbb72eb3b6069e05e3b38fc6`, CRC valid, archive SHA-256 `188605ab0f72c24067258825fee9d23dcc4406f3fb56606ca6b07da18f4ed857`. The real GNU tar contains 16 entries, including the 5904304-byte bundled module and 12686130-byte source map. The new in-memory decoder was exercised against that actual archive under Node 22: exact module SHA-256 `dd0c2668ff6158878ec498156a917a74068892f8bb33dc940eff448d0f8308c8`, ten static assets (645061 bytes total). The existing authority verifier must first validate the original wrapper and manifest. The new internal reader bounds gzip expansion (32 MiB), accepted layout and file sizes; rejects ambiguous paths, unsupported tar types, duplicate entries and invalid checksums. No disk extraction, execution of downloaded JavaScript, or provider call. The original source map is retained separately; deployment must preserve exact module/asset bytes while replacing only the synthetic resource configuration using the existing qualified recipe. No runtime Worker deployment or asset-upload authorization is implied; a provider-side implementation, durable execution claim, renewed database proof and actual readback remain necessary.

## Static asset preparation and transfer

The fixed Studio staging adapter follows Cloudflare's documented direct upload protocol (https://developers.cloudflare.com/workers/static-assets/direct-upload/): register the complete manifest, upload only requested hash buckets, then retain the completion token internally for a separate version-upload operation. The hash follows the documented SHA-256(base64 bytes + extension), truncated to 32 hex characters; upstream full artifact verification is unchanged. Asset counts, paths, extensions, total bytes, provider bucket count and response sizes are bounded. The adapter rejects duplicate/unknown hashes, unsafe paths, redirects and ambiguous completion. It never accepts a caller-selected Worker, sends the account token to a redirect or logs/returns provider tokens in a public receipt. There are no automatic retries. Unit tests use local provider fixtures; no real asset upload or version creation is authorized by this change. The caller must enforce fresh evidence, fixed account, durable claim and absent or proven-owned staging Worker before invoking the adapter. Cloudflare's newer Worker size limits (64 MiB uncompressed on Free and Paid, September 2026: https://developers.cloudflare.com/changelog/post/2026-09-04-increased-worker-size-limit/) do not eliminate startup validation or AppFactory runtime memory/CPU limits. Actual Cloudflare execution remains unqualified.
127 changes: 127 additions & 0 deletions src/studio-staging-assets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
import type { StudioReleasePackage } from "./studio-staging-release-package";

// Fixed staging pilot, internal use only. An upload completion token is
// NOT a deployment authorization; never return it from a public route.
const WORKER="trigenys-studio-staging-api";
const MAX_TOTAL=8*1024*1024;
const MAX_BUCKETS=16;
const MAX_RESPONSE=128*1024;
const MAX_ENTRIES=256;
const TYPES:Readonly<Record<string,string>>=Object.freeze({
html:"text/html; charset=utf-8",svg:"image/svg+xml",js:"application/javascript",
css:"text/css; charset=utf-8",woff2:"font/woff2",png:"image/png",
webp:"image/webp",jpg:"image/jpeg",jpeg:"image/jpeg",ico:"image/x-icon",
});
const fail=():never=>{throw Error("STUDIO_RELEASE_ASSETS_UNQUALIFIED");};
const ensure=(value:unknown)=>{if(!value)fail();};
const record=(v:unknown):Record<string,unknown>=>{
if(!v||typeof v!=="object"||Array.isArray(v))return fail();
return v as Record<string,unknown>;
};
const hex=(bytes:ArrayBuffer)=>Array.from(new Uint8Array(bytes),n=>n.toString(16).padStart(2,"0")).join("");
function base64(bytes:Uint8Array):string{
let binary="";
for(let i=0;i<bytes.length;i+=8192)binary+=String.fromCharCode(...bytes.subarray(i,i+8192));
return btoa(binary);
}
const PATH=/^(?:index\.html|favicon\.svg|assets\/[A-Za-z0-9][A-Za-z0-9_.-]*\.(?:js|css|woff2|svg|png|webp|jpg|jpeg|ico))$/;
type Asset={hash:string;size:number;mime:string;encoded:string};
type Manifest=Record<string,{hash:string;size:number}>;
/** Provider hash convention: SHA-256(base64 bytes + extension), first 32 hex.
* Keep full artifact digest verification upstream. Same bytes with different
* MIME types must not be deduplicated as the same served asset.
*/
export async function planStudioAssets(pkg:StudioReleasePackage){
const manifest:Manifest=Object.create(null);
const byHash=new Map<string,Asset>();
ensure(pkg.assets.size>0&&pkg.assets.size<=MAX_ENTRIES&&pkg.assets.has("index.html"));
let total=0;
for(const [path,bytes] of [...pkg.assets].sort(([a],[b])=>a<b?-1:a>b?1:0)){
ensure(PATH.test(path)&&bytes.length>0&&bytes.length<=5*1024*1024);
total+=bytes.length;ensure(total<=MAX_TOTAL);
const ext=path.slice(path.lastIndexOf(".")+1),mime=TYPES[ext];
ensure(typeof mime==="string");
const encoded=base64(bytes);
const hash=hex(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(encoded+ext))).slice(0,32);
const prior=byHash.get(hash);
if(prior)ensure(prior.encoded===encoded&&prior.mime===mime&&prior.size===bytes.length);
else byHash.set(hash,{hash,size:bytes.length,mime:mime!,encoded});
manifest["/"+path]={hash,size:bytes.length};
}
return {manifest,byHash,total};
}

function parseBuckets(raw:unknown,known:ReadonlyMap<string,Asset>):string[][]{
if(!Array.isArray(raw)||raw.length>MAX_BUCKETS) return fail();
const used=new Set<string>();
const result:string[][]=[];
for(const bucket of raw){
if(!Array.isArray(bucket)||bucket.length===0||bucket.length>known.size)return fail();
const validated:string[]=[];
for(const hash of bucket){
if(typeof hash!=="string"||!known.has(hash)||used.has(hash))return fail();
used.add(hash);validated.push(hash);
}
result.push(validated);
}
return result;
}
async function responseResult(response:Response,expected:number){
ensure(response.status===expected&&response.body!==null);
const reader=response.body!.getReader();
const decoder=new TextDecoder("utf-8",{fatal:true});
let size=0,raw="";
try{
for(;;){
const {done,value}=await reader.read();
if(done)break;
size+=value.length;ensure(size<=MAX_RESPONSE);
raw+=decoder.decode(value,{stream:true});
}
raw+=decoder.decode();
}finally{await reader.cancel().catch(()=>undefined);reader.releaseLock();}
const parsed=record(JSON.parse(raw));
ensure(parsed.success===true);
return record(parsed.result);
}
function token(value:unknown):string{
if(typeof value!=="string"||value.length>16384||
!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value))return fail();
return value;
}

/** Requires prior fixed-target release authorization and durable claim in caller.
* Only uploads the already validated assets, never a Worker version or deployment.
* No retries after uncertain provider effects. No token, body or URL in errors.
*/
export async function uploadStudioAssets(pkg:StudioReleasePackage,env:{
accountId:string;apiToken:string;fetcher:typeof fetch;
}){
try{
ensure(/^[a-f0-9]{32}$/.test(env.accountId)&&env.apiToken.length>0);
const plan=await planStudioAssets(pkg);
const base="https://api.cloudflare.com/client/v4/accounts/"+env.accountId+"/workers";
const session=await responseResult(await env.fetcher(base+"/scripts/"+WORKER+"/assets-upload-session",{
method:"POST",headers:{authorization:"Bearer "+env.apiToken,"content-type":"application/json"},
body:JSON.stringify({manifest:plan.manifest}),redirect:"manual",signal:AbortSignal.timeout(20000)
}),200);
const buckets=parseBuckets(session.buckets,plan.byHash);
const uploadJwt=token(session.jwt);
let completion=buckets.length===0?uploadJwt:undefined;
for(let i=0;i<buckets.length;i++){
const body=new FormData();
for(const hash of buckets[i]!){
const asset=plan.byHash.get(hash)!;
body.append(hash,new Blob([asset.encoded],{type:asset.mime}),hash);
}
const last=i===buckets.length-1;
const result=await responseResult(await env.fetcher(base+"/assets/upload?base64=true",{
method:"POST",headers:{authorization:"Bearer "+uploadJwt},body,
redirect:"manual",signal:AbortSignal.timeout(30000)
}),last?201:200);
if(last)completion=token(result.jwt);
}
if(!completion)return fail();
return {completion,assetCount:Object.keys(plan.manifest).length,bytes:plan.total};
}catch{throw Error("STUDIO_RELEASE_ASSETS_UNQUALIFIED");}
}
63 changes: 63 additions & 0 deletions test/typescript-staging-recipe.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,66 @@ test("release package refuses unsupported layout, duplicate names, missing files
const malformed=releaseTar();malformed[0]^=1;
await assert.rejects(decodeStudioReleasePackage(gzipSync(malformed)),/STUDIO_RELEASE_PACKAGE_INVALID/);
});


const {planStudioAssets,uploadStudioAssets}=await import(data(compile(fs.readFileSync("src/studio-staging-assets.ts","utf8"))));
const assetPackage=()=>({module:new Uint8Array([1]),sourceMap:new Uint8Array([2]),assets:new Map([
["index.html",Buffer.from("identical")],["assets/index-fixture.js",Buffer.from("identical")],
["assets/other.js",Buffer.from("identical")]
])});
const fixtureJwt="fixture.upload.token",completionJwt="fixture.complete.token";
test("Studio asset manifest uses documented hash convention and MIME-safe deduplication",async()=>{
const plan=await planStudioAssets(assetPackage());
const expected=(await buildHash(Buffer.from(Buffer.from("identical").toString("base64")+"js"))).slice(0,32);
assert.equal(plan.manifest["/assets/index-fixture.js"].hash,expected);
assert.equal(plan.manifest["/assets/other.js"].hash,expected);
assert.notEqual(plan.manifest["/index.html"].hash,expected);
assert.equal(plan.byHash.size,2);
assert.equal(Object.keys(plan.manifest).length,3);
assert.equal(plan.total,27);
});
test("Studio asset uploader follows fixed target, known buckets and final completion receipt",async()=>{
const pkg=assetPackage(),plan=await planStudioAssets(pkg),hashes=[...plan.byHash.keys()],calls=[];
const fetcher=async(url,init)=>{
calls.push({url,init});
assert.equal(init.redirect,"manual");
if(calls.length===1){
assert.ok(url.endsWith("/scripts/trigenys-studio-staging-api/assets-upload-session"));
assert.deepEqual(JSON.parse(init.body).manifest,JSON.parse(JSON.stringify(plan.manifest)));
assert.equal(init.headers.authorization,"Bearer fixture-api");
return Response.json({success:true,result:{jwt:fixtureJwt,buckets:hashes.map(h=>[h])}});
}
assert.ok(url.endsWith("/workers/assets/upload?base64=true"));
assert.equal(init.headers.authorization,"Bearer "+fixtureJwt);
const hash=hashes[calls.length-2],part=init.body.get(hash);
assert.equal(await part.text(),plan.byHash.get(hash).encoded);
assert.equal(part.type,plan.byHash.get(hash).mime);
return Response.json({success:true,result:calls.length===3?{jwt:completionJwt}:{}},{status:calls.length===3?201:200});
};
const result=await uploadStudioAssets(pkg,{accountId:"a".repeat(32),apiToken:"fixture-api",fetcher});
assert.equal(result.completion,completionJwt);
assert.equal(result.assetCount,3);
assert.equal(calls.length,3);
});
test("asset uploader fails closed before content uploads for duplicate or foreign bucket hashes",async()=>{
const pkg=assetPackage(),plan=await planStudioAssets(pkg),hash=[...plan.byHash.keys()][0];
for(const buckets of [[[hash],[hash]],[["unknown"]],[[]]]){
let calls=0;
await assert.rejects(uploadStudioAssets(pkg,{accountId:"a".repeat(32),apiToken:"fixture",fetcher:async()=>{
calls++;return Response.json({success:true,result:{jwt:fixtureJwt,buckets}});
}}),/STUDIO_RELEASE_ASSETS_UNQUALIFIED/);
assert.equal(calls,1);
}
const result=await uploadStudioAssets(pkg,{accountId:"a".repeat(32),apiToken:"fixture",fetcher:async()=>Response.json({success:true,result:{jwt:completionJwt,buckets:[]}})});
assert.equal(result.completion,completionJwt);
});
test("asset uploader rejects redirects, uncertain completion and unsafe paths without retry",async()=>{
const pkg=assetPackage(),plan=await planStudioAssets(pkg),hash=[...plan.byHash.keys()][0];
let calls=0;
await assert.rejects(uploadStudioAssets(pkg,{accountId:"a".repeat(32),apiToken:"fixture",fetcher:async()=>{
calls++;return calls===1?Response.json({success:true,result:{jwt:fixtureJwt,buckets:[[hash]]}}):new Response(null,{status:302,headers:{location:"https://example.invalid"}});
}}),/STUDIO_RELEASE_ASSETS_UNQUALIFIED/);
assert.equal(calls,2);
pkg.assets.set("assets/../escape.js",Buffer.from("invalid"));
await assert.rejects(planStudioAssets(pkg),/STUDIO_RELEASE_ASSETS_UNQUALIFIED/);
});