// @requirements REQ-PRODUCT-PUBLICATION-INSPECTION // @requirements REQ-PRODUCT-RECORDING-INSPECTION REQ-PRODUCT-CF-ADMIN REQ-PRODUCT-A11Y REQ-PRODUCT-MOBILE import {checkDocumentPublication,normalizePublicationSource} from './publication-check.js'; import type {PublishedDocumentSource,PublicationCheck} from './publication-check.js'; import {normalizeAdminPresentation} from './presentation.js'; import {escapeHtml as e,renderWorkspaceShell} from './render.js'; import {boundedText,normalizeRecord} from './records.js'; import type {RecordingSelection,RecordingFamily} from './recording-selection.js'; import type {AdminPresentation,AdminWorker,ExecutionContextLike,JsonValue} from './types.js'; /** Fixed application intent, supplied by trusted host code rather than request parameters. */ export interface ExpectedRecordingSelection {id:string;artifactId:string;mode:'preview'|'production'} export interface RecordingSelectionComparison { status:'not-specified'|'matches'|'different'|'unconfigured'|'inactive'|'unavailable'; expected?:ExpectedRecordingSelection; differingFields?:('id'|'artifactId'|'mode')[]; } export interface RecordingInspectionTarget {id:string;title:string;family:RecordingFamily;siteId:string;scopeId:string;read(context:{signal:AbortSignal}):Promise;publication?:PublishedDocumentSource;expected?:ExpectedRecordingSelection} export interface RecordingInspectionGrant {targets:readonly RecordingInspectionTarget[];scopeLabel?:string} export interface RecordingInspectionOptions extends AdminPresentation { authorize(request:Request,env:Env,context?:ExecutionContextLike):RecordingInspectionGrant|null|Promise; basePath?:string;historyPath?:string;readTimeoutMs?:number; } const route=(v:unknown):v is string=>typeof v==='string'&&v.length<=250&&/^\/[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/u.test(v); const slug=(v:unknown):v is string=>typeof v==='string'&&/^[a-z][a-z0-9-]{0,119}$/u.test(v); const hash=(v:unknown):v is string=>typeof v==='string'&&/^[a-f0-9]{64}$/u.test(v); const text=(v:unknown,n:number):v is string=>boundedText(v,n)&&!!v.trim(); const object=(v:JsonValue|undefined):Record=>{if(!v||typeof v!=='object'||Array.isArray(v))throw Error('Invalid recording selection.');return v;}; const exact=(v:Record,keys:string[])=>Object.keys(v).length===keys.length&&keys.every(k=>Object.hasOwn(v,k)); const families:Record={consent:'Cookie choices',terms:'Terms agreement','form-permission':'Form permission'}; function expectedValue(value:unknown):ExpectedRecordingSelection { const v=object(normalizeRecord({id:'expected',data:value},1024).data); if(!exact(v,['id','artifactId','mode'])||!hash(v.id)||!hash(v.artifactId)||!['preview','production'].includes(String(v.mode)))throw Error('Invalid expected recording selection.'); return {id:v.id as string,artifactId:v.artifactId as string,mode:v.mode as ExpectedRecordingSelection['mode']}; } function compareSelection(expected:ExpectedRecordingSelection|undefined,selection:RecordingSelection|null):RecordingSelectionComparison { if(!expected)return {status:'not-specified'}; const copy={...expected}; if(!selection)return {status:'unavailable',expected:copy}; if(selection.status!=='selected')return {status:selection.status,expected:copy}; const differingFields=(['id','artifactId','mode'] as const).filter(key=>selection.selected![key]!==expected[key]); return {status:differingFields.length?'different':'matches',expected:copy,differingFields}; } function grantValue(value:RecordingInspectionGrant|null):RecordingInspectionGrant { if(!value||!Array.isArray(value.targets)||value.targets.length>12||value.scopeLabel!==undefined&&!text(value.scopeLabel,200))throw Error('Invalid recording inspection grant.'); const ids=new Set();return {...(value.scopeLabel===undefined?{}:{scopeLabel:value.scopeLabel}),targets:value.targets.map(t=>{if(!t||!slug(t.id)||ids.has(t.id)||!text(t.title,120)||!Object.hasOwn(families,t.family)||!slug(t.siteId)||!slug(t.scopeId)||typeof t.read!=='function')throw Error('Invalid recording inspection target.');ids.add(t.id);return {id:t.id,title:t.title,family:t.family,siteId:t.siteId,scopeId:t.scopeId,read:t.read,...(t.publication===undefined?{}:{publication:normalizePublicationSource(t.publication)}),...(t.expected===undefined?{}:{expected:expectedValue(t.expected)})};})}; } function selectionValue(raw:unknown,target:RecordingInspectionTarget):RecordingSelection { const s=object(normalizeRecord({id:'selection',data:raw},16384).data),hasRevision=Object.hasOwn(s,'activationRevision'); if(!exact(s,['schemaVersion','family','siteId','scopeId','status','selected',...(hasRevision?['activationRevision']:[])])||s.schemaVersion!==1||s.family!==target.family||s.siteId!==target.siteId||s.scopeId!==target.scopeId||!['selected','unconfigured','inactive'].includes(String(s.status)))throw Error('Mismatched recording selection.'); if(target.family==='form-permission'){if(!hasRevision||!Number.isSafeInteger(s.activationRevision)||Number(s.activationRevision)<(s.status==='unconfigured'?0:1)||s.status==='unconfigured'&&s.activationRevision!==0)throw Error('Invalid activation revision.');}else if(hasRevision)throw Error('Unexpected activation revision.'); if(s.status==='selected'){ const selected=object(s.selected),d=object(selected.document); if(!exact(selected,['id','artifactId','mode','document'])||!hash(selected.id)||!hash(selected.artifactId)||!['preview','production'].includes(String(selected.mode))||!exact(d,['title','version','effectiveDate','url','sha256'])||!text(d.title,300)||!text(d.version,200)||!hash(d.sha256)||typeof d.effectiveDate!=='string'||!/^\d{4}-\d{2}-\d{2}$/u.test(d.effectiveDate)||!Number.isFinite(Date.parse(d.effectiveDate))||new Date(d.effectiveDate).toISOString().slice(0,10)!==d.effectiveDate||d.url!==`/artifacts/${selected.artifactId}/${target.family==='terms'?'terms':'privacy'}.html`)throw Error('Invalid recording document.'); }else if(s.selected!==null)throw Error('Unexpected recording target.'); return s as unknown as RecordingSelection; } type PublicationObservation=Omit,'status'>&{status:PublicationCheck['status']|'not-requested'|'not-connected'|'selection-unavailable'|'no-selection'}; function comparisonMarkup(comparison:RecordingSelectionComparison,historyPath:string|undefined):string { if(!comparison.expected)return ''; const titles:Record={'not-specified':'No expected version supplied',matches:'Uses the expected version',different:'Another version is selected',unconfigured:'Expected version is not selected',inactive:'This scope is inactive',unavailable:'Expected version could not be compared'}; const explanations:Record={'not-specified':'This view reports the current backend selection only.',matches:'The selected descriptor, release and mode match the host’s expected version. Check the served copies and running page separately.',different:'The active version differs from the host’s expected selection. Review the expected release and the recording endpoint before changing activation.',unconfigured:'The host expects a version, but this scope has no activation record. Review its archive, registration and explicit activation in host code.',inactive:'The host expects a version, but no version is active here. Confirm whether this is intentional before changing activation.',unavailable:'A valid current selection could not be read. Check the reader and retained archive, then try again.'}; const fields={id:'descriptor',artifactId:'release',mode:'mode'}; return `

${titles[comparison.status]}

${explanations[comparison.status]}

${comparison.differingFields?.length?`

Different: ${comparison.differingFields.map(key=>fields[key]).join(', ')}.

`:''}
Expected selection references
${[['Descriptor ID',comparison.expected.id],['Release artifact',comparison.expected.artifactId],['Release mode',comparison.expected.mode]].map(([k,v])=>`
${e(k!)}
${e(v!)}
`).join('')}
${historyPath?`Review expected release `:''}
`; } function publicationMarkup(p:PublicationObservation|undefined):string { if(!p)return ''; const titles:Record={matched:'HTML bytes match',different:'Different HTML copy',missing:'Document not found',unavailable:'Check unavailable','not-requested':'Not checked','not-connected':'No check connected','selection-unavailable':'Selection unavailable','no-selection':'No document selected'}; const descriptions:Record={matched:'The configured reader returned the retained document’s exact bytes.',different:'The returned HTML differs from the selected retained document. Check the pinned deployment and any response transformations.',missing:'The configured reader returned HTTP 404 or 410 for the pinned document.',unavailable:'The reader did not return a complete bounded HTML response. Check its connection and try again.','not-requested':'Use Check document copies to compare the selected document with this reader.','not-connected':'The host has not connected a document reader for this scope.','selection-unavailable':'The retained selection could not be verified, so no document was fetched.','no-selection':'No active document is selected here, so no document was fetched.'}; return `

${titles[p.status]}

${descriptions[p.status]}

${p.source?`

${e(p.source.label)} · ${e(p.source.origin)}

`:''}${p.checkedAt?`

Checked ${p.bytes===undefined?'':' · '+p.bytes+' bytes'}

`:''}${p.url?`
Copy check references
${[['Requested URL',p.url],['Expected SHA-256',p.expectedSha256],['Returned SHA-256',p.actualSha256],['HTTP status',p.httpStatus?.toString()],['Check limit or failure',p.reason]].filter(([,v])=>v!==undefined).map(([k,v])=>`
${e(k!)}
${e(v!)}
`).join('')}
`:''}
`; } const comparisonCss=`.recording-expectation{margin-top:1.2rem;padding:1rem 0 0;border-top:1px solid #e5e5e8}.recording-expectation h3{font-size:.85rem;margin:0 0 .5rem;letter-spacing:-.015em}.recording-expectation p{margin:.35rem 0}.recording-expectation[data-comparison=different] h3,.recording-expectation[data-comparison=inactive] h3,.recording-expectation[data-comparison=unconfigured] h3{color:#85601d}.recording-expectation .recording-source{font-size:.75rem;color:#65656f}.recording-expectation details dl{margin-bottom:.5rem}@media(forced-colors:active){.recording-expectation h3{color:CanvasText!important}.recording-expectation{border-color:CanvasText}}`; const css=`.recording-check-action{display:inline-flex;align-items:center;min-height:44px;padding:.7rem 1rem;border:1px solid #d8d6de;border-radius:7px;background:#fff;color:#302c39;font-size:.85rem;font-weight:600;text-decoration:none}.recording-check-action:focus-visible{outline:3px solid #76638f;outline-offset:4px}.recording-check-note{font-size:.78rem}.recording-publication{margin-top:1.2rem;padding-top:1rem;border-top:1px solid #e5e5e8}.recording-publication h3{font-size:.85rem;margin:0 0 .5rem;letter-spacing:-.015em}.recording-publication p{margin:.35rem 0}.recording-publication .recording-source{font-size:.7rem;color:#65656f;overflow-wrap:anywhere}.recording-publication[data-status=different] h3,.recording-publication[data-status=missing] h3{color:#85601d}.recording-intro{max-width:48rem;margin:0 0 2rem}.recording-intro h1{margin:.5rem 0 1rem}.recording-intro>p{color:#65656f;line-height:1.75}.recording-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem}.recording-item{min-width:0;padding:1.5rem;border:1px solid #e5e5e8;border-radius:10px;background:#fff}.recording-item header{display:flex;justify-content:space-between;align-items:start;gap:1rem}.recording-item h2{font-size:1.1rem;line-height:1.45;letter-spacing:-.025em;margin:.3rem 0 1rem}.recording-item p{font-size:.875rem;line-height:1.7}.recording-status{flex:0 0 auto;padding:.3rem .6rem;border:1px solid #dfdce8;border-radius:5px;font-size:.7rem;color:#51446e;background:#f5f3f9}.recording-status.unavailable{color:#81571b;background:#fbf7ef;border-color:#e9ddc7}.recording-item dl{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:1rem;margin:1.2rem 0}.recording-item dt{font-size:.72rem;color:#65656f;margin-bottom:.35rem}.recording-item dd{margin:0;font-size:.85rem;overflow-wrap:anywhere}.recording-item details{margin:1rem 0 0;border:0;border-top:1px solid #e5e5e8;padding:.8rem 0 0;border-radius:0;background:none}.recording-item summary{cursor:pointer;min-height:44px;font-size:.8rem;display:list-item}.recording-item code{font-size:.75rem;overflow-wrap:anywhere;white-space:normal}.recording-item .recording-history{min-height:44px;display:inline-flex;align-items:center;font-size:.8rem;margin-top:.5rem}.recording-notes{margin-top:1.8rem;max-width:60rem;color:#65656f;font-size:.8rem;line-height:1.8}.recording-notes time{white-space:nowrap}@media(max-width:850px){.recording-grid{grid-template-columns:1fr}.recording-item{padding:1.2rem}.recording-item header{flex-wrap:wrap}.recording-item details dl{grid-template-columns:1fr}}@media(forced-colors:active){.recording-item,.recording-status{border-color:CanvasText;color:CanvasText;background:Canvas}}`; /** Fixed trusted readers only. No request can select a namespace, site, scope or visitor. */ export function createRecordingInspectionWorker(options:RecordingInspectionOptions):AdminWorker{ if(!options||typeof options.authorize!=='function')throw Error('Recording inspection needs host authorization.');const basePath=options.basePath??'/admin/notabenda/recording',historyPath=options.historyPath;if(!route(basePath)||historyPath!==undefined&&!route(historyPath))throw Error('Use clean inspection paths.');const timeout=options.readTimeoutMs??5000;if(!Number.isInteger(timeout)||timeout<1000||timeout>30000)throw Error('Use a read timeout of 1000–30000 milliseconds.');const authorize=options.authorize,presentation=normalizeAdminPresentation(options); return {async fetch(request,env,context){ const headers=new Headers({'Content-Type':'text/plain; charset=utf-8','Cache-Control':'private, no-store','Pragma':'no-cache','Vary':'Cookie, Authorization','Referrer-Policy':'no-referrer','X-Content-Type-Options':'nosniff','X-Frame-Options':'DENY','X-Robots-Tag':'noindex, nofollow','Content-Security-Policy':"default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'"}),reply=(body:string,status:number)=>new Response(request.method==='HEAD'?null:body,{status,headers}); let grant:RecordingInspectionGrant;try{grant=grantValue(await authorize(request,env,context));}catch{return reply('Access denied.',403);} if(!['GET','HEAD'].includes(request.method)){headers.set('Allow','GET, HEAD');return reply('Method not allowed.',405);}if(request.url.length>4096)return reply('Request is too long.',414);const url=new URL(request.url);if(![basePath,basePath+'/'].includes(url.pathname))return reply('Not found.',404);if([...url.searchParams.keys()].some(k=>!['format','publication'].includes(k))||url.searchParams.getAll('format').length>1||url.searchParams.has('format')&&url.searchParams.get('format')!=='json'||url.searchParams.getAll('publication').length>1||url.searchParams.has('publication')&&url.searchParams.get('publication')!=='check')return reply('Invalid inspection request.',400); const publicationRequested=url.searchParams.get('publication')==='check'; const observations=await Promise.all(grant.targets.map(async target=>{ const abort=new AbortController();let timer:ReturnType|undefined; const timedOut=new Promise(resolve=>{timer=setTimeout(()=>{abort.abort();resolve(null);},timeout);}); const read=Promise.resolve().then(()=>target.read({signal:abort.signal})).then(raw=>selectionValue(raw,target)).catch(()=>null); const selection=await Promise.race([read,timedOut]);if(timer!==undefined)clearTimeout(timer); let publication:PublicationObservation|undefined; if(target.publication||publicationRequested){ if(!target.publication)publication={status:'not-connected'}; else if(!publicationRequested)publication={status:'not-requested',source:{origin:target.publication.origin,label:target.publication.label}}; else if(!selection)publication={status:'selection-unavailable'}; else if(!selection.selected)publication={status:'no-selection'}; else publication=await checkDocumentPublication({path:selection.selected.document.url,sha256:selection.selected.document.sha256},{...target.publication,timeoutMs:timeout,signal:request.signal}); } return {target:{id:target.id,title:target.title,family:target.family,siteId:target.siteId,scopeId:target.scopeId},selection,comparison:compareSelection(target.expected,selection),...(publication?{publication}:{})}; })); const observedAt=new Date().toISOString();if(url.searchParams.get('format')==='json'){headers.set('Content-Type','application/json; charset=utf-8');return reply(JSON.stringify({schemaVersion:1,kind:'notabenda-recording-inspection',observedAt,observations,boundaries:{changesSelection:false,readsVisitorState:false,verifiesPublication:false,verifiesEnforcement:false,legalReview:false,publicationChecksRequested:publicationRequested,verifiesPublicRouting:false,verifiesExpectedArchive:false}}),200);} const cards=observations.map(({target,selection:s,comparison,publication})=>{const selected=s?.selected,status=s===null||s===undefined?'Check unavailable':s.status==='selected'?'Selected':s.status==='inactive'?'Inactive':'Not configured';return `

${e(families[target.family])}

${e(target.title)}

${status}

${!s?'The current selection could not be checked. Check the host reader and retained archive before relying on this result.':s.status==='unconfigured'?'No selection has been configured in this host scope. An archived release or registered descriptor does not select one.':s.status==='inactive'?'The host has no active selection here. Historical records remain separate.':e(selected!.document.title)}

${comparisonMarkup(comparison,historyPath)}
Site
${e(target.siteId)}
${target.family==='form-permission'?'Permission':'Scope'}
${e(target.scopeId)}
${selected?`
Document version
${e(selected.document.version)} · ${e(selected.document.effectiveDate)}
Release mode
${selected.mode==='preview'?'Developer preview':'Production descriptor'}
`:''}${s?.activationRevision===undefined?'':`
Activation revision
${s.activationRevision}
`}
${selected?`
Document and recording references

${e(selected.document.title)}

${[['Descriptor ID',selected.id],['Release artifact',selected.artifactId],['Pinned document path',selected.document.url],['Document SHA-256',selected.document.sha256]].map(([label,value])=>`
${e(label!)}
${e(value!)}
`).join('')}
${publicationMarkup(publication)}${historyPath?`Find this release in history `:''}`:publicationMarkup(publication)}
`;}).join(''); const nonce=crypto.randomUUID().replaceAll('-','');headers.set('Content-Type','text/html; charset=utf-8');headers.set('Content-Security-Policy',headers.get('Content-Security-Policy')!.replace("default-src 'none';",`default-src 'none'; style-src 'nonce-${nonce}';`));const body=`

${e(grant.scopeLabel??'Recording configuration')}

Recording setup

Check which cookie notices, terms and form offers the backend currently selects. Compare them with any expected versions supplied by the host. Only configured sites and scopes appear here.

${grant.targets.some(t=>t.publication)?`${publicationRequested?'Check document copies again':'Check document copies'}

Fetch the pinned documents through the host-configured readers and compare their HTML bytes. No saved choices or recording settings are changed.

`:''}
${cards?`
${cards}
`:'

No recording scopes are configured for this view. Connect the notices and offers used by your recording endpoints.

'}

Checked at . Expected references describe host intent; their archives are not independently verified by this comparison. Each scope is read independently; this is not a single workspace snapshot. An active selection is not evidence of publication, installation, a person’s permission or legal compliance. Served-copy results describe the configured reader at the time shown; an asset binding can bypass public routing. This view changes nothing and does not read anyone’s saved choices.

`;return reply(renderWorkspaceShell(body,{...presentation,basePath,title:'Recording setup',scopeLabel:grant.scopeLabel??'Recording configuration',nonce},``,'recording-inspection-page'),200); }}; }