|
| 1 | +// Authenticated operator-only adapter; never included in the public Worker. |
| 2 | +// Credentials are consumed only by an explicitly confirmed remote apply command. |
| 3 | +import {AwsClient} from 'aws4fetch'; |
| 4 | +export function remoteBindings(target,credentials,transport=fetch) { |
| 5 | + if(!credentials.d1Token||!credentials.r2AccessKeyId||!credentials.r2SecretAccessKey)throw Error('Remote apply requires privately configured D1 API and bucket-scoped R2 credentials'); |
| 6 | + const queryUrl=`https://api.cloudflare.com/client/v4/accounts/${target.accountId}/d1/database/${target.databaseId}/query`; |
| 7 | + let verified; |
| 8 | + async function verifyBindings() { |
| 9 | + verified??=(async()=>{ |
| 10 | + const response=await transport(`https://api.cloudflare.com/client/v4/accounts/${target.accountId}/workers/scripts/${target.workerName}/settings`,{headers:{Authorization:'Bearer '+credentials.d1Token},signal:AbortSignal.timeout(30000)}); |
| 11 | + if(!response.ok)throw Error('Cannot verify deployed Worker bindings; no import performed'); |
| 12 | + const data=await response.json(),bindings=data.result?.bindings; |
| 13 | + if(!data.success||!Array.isArray(bindings)||!bindings.some(b=>b.name==='DB'&&b.type==='d1'&&b.id===target.databaseId)||!bindings.some(b=>b.name==='PACKAGES'&&b.type==='r2_bucket'&&b.bucket_name===target.bucket))throw Error('Reviewed target does not match deployed Worker D1/R2 bindings; no import performed'); |
| 14 | + })(); |
| 15 | + return verified; |
| 16 | + } |
| 17 | + async function query(sql,params=[]) { |
| 18 | + await verifyBindings(); |
| 19 | + const response=await transport(queryUrl,{method:'POST',headers:{Authorization:'Bearer '+credentials.d1Token,'Content-Type':'application/json'},body:JSON.stringify({sql,params}),signal:AbortSignal.timeout(30000)}); |
| 20 | + if(!response.ok)throw Error('Authenticated D1 query failed (HTTP '+response.status+'); inspect target/permissions'); |
| 21 | + const data=await response.json(); |
| 22 | + if(!data.success||data.result?.length!==1||!data.result[0].success)throw Error('D1 statement rejected; inspect registry conflicts/schema before retrying'); |
| 23 | + return data.result[0]; |
| 24 | + } |
| 25 | + function prepare(sql,params=[]) {return {bind:(...values)=>prepare(sql,values),all:()=>query(sql,params),run:()=>query(sql,params),first:async column=>{const row=(await query(sql,params)).results[0];return row?(column?row[column]:row):null;}};} |
| 26 | + const signer=new AwsClient({accessKeyId:credentials.r2AccessKeyId,secretAccessKey:credentials.r2SecretAccessKey,service:'s3',region:'auto',retries:0}); |
| 27 | + async function object(method,key,body) { |
| 28 | + await verifyBindings(); |
| 29 | + if(!/^packages\/sha256\/[a-f0-9]{64}$/.test(key))throw Error('Unexpected official object key'); |
| 30 | + const url=`https://${target.accountId}.r2.cloudflarestorage.com/${target.bucket}/${key}`; |
| 31 | + const signed=await signer.sign(url,{method,body,headers:method==='PUT'?{'If-None-Match':'*','Content-Type':'application/vnd.codegraph.extension+json'}:{}}); |
| 32 | + return transport(signed,{signal:AbortSignal.timeout(30000)}); |
| 33 | + } |
| 34 | + return {db:{prepare},bucket:{ |
| 35 | + async get(key){const response=await object('GET',key);if(response.status===404)return null;if(!response.ok)throw Error('Authenticated R2 read failed (HTTP '+response.status+')');return {arrayBuffer:()=>response.arrayBuffer()};}, |
| 36 | + async put(key,bytes,options){if(options?.onlyIf?.etagDoesNotMatch!=='*')throw Error('R2 official import requires conditional creation');const response=await object('PUT',key,bytes);if(response.status===412)return null;if(!response.ok)throw Error('Authenticated R2 conditional upload failed (HTTP '+response.status+')');return {};} |
| 37 | + }}; |
| 38 | +} |
0 commit comments