Merge pull request 'Alpha1.0.0.6 — Automatic monthly bank statement archive' (#290) from dev/MC:dev/alpha-1.0.0.6-imperial-postbank into main

This commit is contained in:
Dev 2026-11-13 23:47:02 +01:00
commit 9abe41b277
12 changed files with 77 additions and 15 deletions

View file

@ -1,3 +1,4 @@
import {mountStatementArchive} from './cp-v2-postbank-statement-archive.mjs';
const transactionLabel=r=>r.state==='rejected'?'REJECTED':r.state==='queued'?'PENDING':r.direction==='credit'?'CREDIT':r.direction==='debit'?'DEBIT':'DEBIT / CREDIT';
import {element as el,createCPV2ContentPage} from './cp-v2-page-template.mjs';
import {createUserAPI} from './cp-v2-user-api.mjs';
@ -45,8 +46,6 @@ export function mountPostbankPayments(host,page,{fetcher=fetch,accountId=null}={
const accounts=options.accounts,filter=el('select');selectOption(filter,'All authorised accounts','');for(const a of accounts)selectOption(filter,accountLabel(a),a.id);
filter.value=selectedAccount;
const toolbar=el('form',undefined,'pb-ledger-toolbar'),query=el('input'),state=el('select'),from=el('input'),to=el('input'),apply=el('button','Search transactions');query.type='search';query.maxLength=80;query.placeholder='Reference, name or account number';selectOption(state,'All statuses','');for(const value of ['queued','posted','rejected'])selectOption(state,value[0].toUpperCase()+value.slice(1),value);from.type=to.type='date';from.min=to.min=new Date(Date.now()-30*86400000).toISOString().slice(0,10);from.max=to.max=new Date().toISOString().slice(0,10);apply.type='submit';toolbar.append(field('Account',filter),field('Search',query),field('Status',state),field('From · UTC',from),field('To · UTC',to),apply);frame.content.append(el('p','Search the last 30 days. Earlier posted transactions remain available in free monthly account statements.','pb-muted'),toolbar);toolbar.onsubmit=event=>{event.preventDefault();pageNumber=1;void show();};
const downloads=el('section',undefined,'pb-statement-download'),statementAccount=el('select'),month=el('input'),download=el('button','Download PDF statement'),downloadStatus=el('p');for(const a of accounts)selectOption(statementAccount,accountLabel(a),a.id);statementAccount.value=selectedAccount||accounts[0]?.id||'';month.type='month';month.required=true;const today=new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit'}).formatToParts(new Date()),monthParts=Object.fromEntries(today.filter(p=>p.type!=='literal').map(p=>[p.type,p.value]));month.value=month.max=monthParts.year+'-'+monthParts.month;month.min='2026-01';download.type='button';download.disabled=!accounts.length;downloads.append(el('h4','Monthly account statements'),el('p','Free PDF statements of posted transactions. Current-month downloads are provisional; previous months remain available.'),field('Statement account',statementAccount),field('Month',month),download,downloadStatus);frame.content.append(downloads);
download.onclick=async()=>{if(!month.reportValidity())return;download.disabled=true;downloadStatus.textContent='Preparing your statement…';try{const path='/api/bank/statements?'+new URLSearchParams({accountId:statementAccount.value,month:month.value}),response=await api.fetcher(path,{signal:AbortSignal.timeout(40000)});if(!response.ok){const data=await response.json();throw Error(data.message||'Statement unavailable.');}const blob=await response.blob();if(!active)return;const url=URL.createObjectURL(blob),link=el('a');link.href=url;link.download='Statement-'+statementAccount.value+'-'+month.value+'.pdf';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);downloadStatus.textContent='Your statement has been downloaded.';}catch(error){if(active)downloadStatus.textContent=error.message;}finally{if(active)download.disabled=false;}};
const records=el('div',undefined,'pb-ledger-records');frame.content.append(records);filter.onchange=()=>{selectedAccount=filter.value;pageNumber=1;history.replaceState(null,'','#bank/bank-statements'+(selectedAccount?'/'+selectedAccount:''));void show();};
async function show(){records.replaceChildren(el('p','Loading payment records…'));for(const n of toolbar.elements)n.disabled=true;try{const data=await api.request('/api/bank/activity?'+new URLSearchParams({page:String(pageNumber),...(selectedAccount?{accountId:selectedAccount}:{}),q:query.value,state:state.value,from:from.value,to:to.value}));if(!active)return;records.replaceChildren();if(!data.records.length)records.append(el('p','No payment records for this selection.'));
else{const scroll=el('div',undefined,'pb-ledger-scroll'),table=el('table',undefined,'pb-ledger'),head=el('thead'),hr=el('tr');for(const text of ['Date','Reference','From','To','Amount · DM','Status','Balance after'])hr.append(el('th',text));head.append(hr);table.append(head);const body=el('tbody');
@ -58,6 +57,7 @@ export function mountPostbankPayments(host,page,{fetcher=fetch,accountId=null}={
const nav=el('nav',undefined,'pb-ledger-pagination'),previous=el('button','Previous'),next=el('button','Next');previous.type=next.type='button';previous.disabled=pageNumber<=1;next.disabled=!data.hasMore;previous.onclick=()=>{pageNumber--;void show();};next.onclick=()=>{pageNumber++;void show();};nav.append(previous,el('span','Page '+pageNumber),next);records.append(nav);
}catch(error){if(active)records.replaceChildren(el('p',error.message));}finally{if(active)for(const n of toolbar.elements)n.disabled=false;}}
await show();
if(active)mountStatementArchive(frame.content,{api,accounts,accountId:selectedAccount,isActive:()=>active});
}
void load();return()=>{active=false;controller.abort();window.removeEventListener('beforeunload',beforeUnload);frame.root.remove();};
}

View file

@ -0,0 +1,15 @@
import {element as el} from './cp-v2-page-template.mjs';
const number=s=>s.match(/.{1,4}/g)?.join(' ')||s;
const monthLabel=month=>new Intl.DateTimeFormat('en-GB',{month:'long',year:'numeric',timeZone:'UTC'}).format(new Date(month+'-01T00:00:00Z'));
export function mountStatementArchive(host,{api,accounts,accountId,isActive=()=>true}){
const box=el('section',undefined,'pb-statement-archive'),header=el('header'),logo=el('img'),intro=el('div'),select=el('select'),list=el('div'),status=el('p',undefined,'pb-muted');let page=1,version=0;
logo.src='https://www.dunerealms.com/assets/imperial-postbank-v2.png';logo.alt='Imperial Postbank';intro.append(el('small','YOUR DOCUMENT VAULT'),el('h4','Account statements'),el('p','Issued automatically after each month closes. Free PDF statements, securely archived by account.'));header.append(intro,logo);
for(const a of accounts){const o=el('option',a.holder+' · '+a.name+' · '+number(a.number));o.value=a.id;select.append(o);}select.value=accountId||accounts[0]?.id||'';select.setAttribute('aria-label','Account statement archive');select.disabled=!accounts.length;
const field=el('label',undefined,'pb-transfer-field');field.append(el('span','Account'),select);box.append(header,field,list,status);host.append(box);
async function show(){const ticket=++version;list.replaceChildren(el('p','Loading archived statements…'));if(!select.value){list.replaceChildren(el('p','Activate an account to receive monthly statements.'));return;}try{const data=await api.request('/api/bank/statements/archive?'+new URLSearchParams({accountId:select.value,page:String(page)}));if(!isActive()||!box.isConnected||ticket!==version)return;list.replaceChildren();status.textContent='Next month-end: '+new Date(data.nextClosing-1).toLocaleDateString('en-GB',{timeZone:'Europe/Brussels'})+'. Statements appear here automatically after closing.';
if(!data.records.length)list.append(el('div','No closed-month statements yet. Your first statement will appear after the account’s first month-end.','pb-archive-empty'));
for(const r of data.records){const row=el('article',undefined,'pb-archive-document'),icon=el('span','PDF','pb-archive-document-icon'),details=el('div'),badge=el('span',r.state==='ready'?'Available':'Preparing','pb-archive-state');badge.dataset.state=r.state;details.append(el('strong',monthLabel(r.month)),el('small',r.state==='ready'?'Monthly account statement · '+Math.max(1,Math.ceil(r.size/1024))+' KB':'Automatic bank processing'));row.append(icon,details,badge);if(r.state==='ready'){const download=el('button','Download PDF');download.type='button';download.onclick=async()=>{download.disabled=true;status.textContent='Downloading your archived statement…';try{const response=await api.fetcher('/api/bank/statements?'+new URLSearchParams({accountId:data.account.id,month:r.month}));if(!response.ok){const error=await response.json();throw Error(error.message||'Download unavailable.');}const blob=await response.blob();if(!isActive())return;const url=URL.createObjectURL(blob),link=el('a');link.href=url;link.download='Statement-'+data.account.number+'-'+r.month+'.pdf';link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);status.textContent='Statement downloaded.';}catch(e){if(isActive())status.textContent=e.message;}finally{if(isActive())download.disabled=false;}};row.append(download);}list.append(row);}
if(page>1||data.hasMore){const nav=el('nav',undefined,'pb-ledger-pagination'),previous=el('button','Newer'),next=el('button','Older');previous.type=next.type='button';previous.disabled=page===1;next.disabled=!data.hasMore;previous.onclick=()=>{page--;void show();};next.onclick=()=>{page++;void show();};nav.append(previous,el('span','Page '+page),next);list.append(nav);}
}catch(e){if(isActive()&&ticket===version)list.replaceChildren(el('p',e.message));}}
select.onchange=()=>{page=1;void show();};void show();return box;
}

View file

@ -216,3 +216,4 @@
.pb-ledger-toolbar{display:grid;grid-template-columns:minmax(12rem,2fr) minmax(12rem,2fr) repeat(3,minmax(7rem,1fr));gap:12px;align-items:end;font-family:Arial,sans-serif}.pb-ledger-toolbar button{justify-self:start}.pb-statement-download{margin:24px 0;padding:24px;border:1px solid #7d8f70;border-left:4px solid #c6a95b;border-radius:14px;background:linear-gradient(120deg,#254b40,#142e26);font-family:Arial,sans-serif;display:grid;grid-template-columns:2fr 1fr auto;gap:16px;align-items:end}.pb-statement-download h4,.pb-statement-download>p{grid-column:1/-1;margin:0}.pb-statement-download select,.pb-statement-download input,.pb-ledger-toolbar input,.pb-ledger-toolbar select{min-width:0;width:100%;box-sizing:border-box}
.pb-ledger-toolbar{max-width:none}.pb-transaction-status[data-state=rejected]{padding:12px;border:1px solid #cc6a62;border-left:4px solid #ed877a;border-radius:9px;background:linear-gradient(125deg,#5d2929,#3b2024);min-width:135px;box-shadow:inset 0 1px #ffdbcf12}.pb-transaction-status[data-state=rejected] .pb-payment-state{color:#ffe5dc;background:#872e30;border-color:#e99786;font-weight:700}.pb-transaction-status[data-state=rejected] small{color:#ffe0d4;max-width:220px;line-height:1.5}
.pb-payment-state{text-transform:none}.pb-payment-state[data-state=posted][data-direction=debit]{color:#efb5a8;border-color:#c08e7a;background:#7e493821}.pb-payment-state[data-state=posted][data-direction=credit]{color:#b2ecc4;background:#42795429}
.pb-statement-archive{margin-top:30px;padding:26px;border:1px solid #819073;border-top:3px solid #c5ac67;border-radius:14px;background:linear-gradient(135deg,#24473b,#122c25);font-family:Arial,sans-serif;box-shadow:0 12px 28px #0002}.pb-statement-archive>header{display:flex;justify-content:space-between;align-items:center;gap:24px;padding-bottom:20px;border-bottom:1px solid #83977655;margin-bottom:20px}.pb-statement-archive header small{color:#ccba81;font-size:10px;font-weight:700;letter-spacing:.15em}.pb-statement-archive h4{font:700 23px Arial,sans-serif;margin:8px 0;color:#f2deb0}.pb-statement-archive header p{font-size:13px;color:#c3d0c2;line-height:1.6;margin:0}.pb-statement-archive header img{width:150px;height:55px;object-fit:contain}.pb-statement-archive>.pb-transfer-field{max-width:720px;margin-bottom:20px}.pb-archive-document{display:grid;grid-template-columns:44px minmax(0,1fr) auto auto;align-items:center;gap:18px;padding:17px 18px;margin-top:10px;border:1px solid #71917b77;border-radius:10px;background:#102a2388}.pb-archive-document-icon{font-size:10px;letter-spacing:.08em;font-weight:700;color:#e3cf93;padding:16px 5px;text-align:center;border:1px solid #b9a36d;border-radius:5px;background:#d7ba5520}.pb-archive-document strong{color:#eee4c7;font-size:14px}.pb-archive-document small{display:block;color:#adbfaf;font-size:11px;margin-top:6px}.pb-archive-state{font-size:10px;border:1px solid #728a76;border-radius:20px;padding:5px 10px;color:#d9c99c}.pb-archive-state[data-state=ready]{color:#b2e4c0;border-color:#79ac86;background:#629b6b1c}.pb-archive-empty{padding:24px;border:1px dashed #8b9b7c;border-radius:10px;color:#c5d0bc;font-size:13px;line-height:1.7}.pb-statement-archive>.pb-muted{font-size:11px;margin-top:18px;color:#b7c8b5}

View file

@ -243,7 +243,7 @@ export function createPanel(db,settings={},dependencies={}){
if(!['GET','HEAD'].includes(request.method))return new Response('Method not allowed',{status:405});
if(path.startsWith('/assets/')&&sharedAssets.has(path.slice(8))){const file=path.slice(8);return new Response(request.method==='HEAD'?null:await readFile(new URL('../web/assets/'+file,import.meta.url)),{headers:{'Content-Type':file.endsWith('.svg')?'image/svg+xml':file.endsWith('.png')?'image/png':'image/webp','Cache-Control':'public, max-age=3600'}});}
// V2 shell is public; private data and writes retain their authenticated API gates.
if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){
if(['/','/index.html','/v2','/v2/','/v2/cp-v2-politics-pages.mjs','/v2/cp-v2-auth.mjs','/v2/cp-v2-access.mjs','/v2/citizens-registry.mjs','/v2/cp-v2-page-template.mjs','/v2/imperial-permissions.mjs','/v2/honours-seals.mjs','/v2/cp-v2-planned-pages.mjs','/v2/cp-v2-choam-pages.mjs','/v2/cp-v2-bureau-pages.mjs','/v2/cp-v2-service-pages.mjs','/v2/cp-v2-newsroom.mjs','/v2/cp-v2-moderation.mjs','/v2/cp-v2-native-services.mjs','/v2/cp-v2-exchange-authority.mjs','/v2/cp-v2-crysknife.mjs','/v2/cp-v2-post-menu.mjs','/v2/cp-v2-postbank-foundation.mjs','/v2/cp-v2-postbank-payments.mjs','/v2/cp-v2-postbank-admin.mjs','/v2/cp-v2-postbank-beneficiaries.mjs','/v2/cp-v2-postbank-statement-archive.mjs','/v2/cp-v2-bank-pages.mjs','/v2/cp-v2-post-pages.mjs','/v2/cp-v2-rewards.mjs','/v2/cp-v2-user-commerce.mjs','/v2/cp-v2-user-pages.mjs','/v2/cp-v2-user-api.mjs','/v2/cp-v2-security.mjs','/v2/cp-v2-passport.mjs','/v2/cp-v2-personal-records.mjs','/v2/cp-v2-design-pages.mjs','/v2/cp-v2-design-catalog.mjs','/v2/cp-v2-forge-pages.mjs','/v2/cp-v2-hosting.mjs','/v2/cp-v2-community-treasury.mjs','/v2/cp-v2-item-register.mjs','/v2/cp-v2-kit-directorate.mjs','/v2/cp-v2-campaigns.mjs','/v2/cp-v2-imperial-revenue.mjs','/v2/cp-v2-read-register.mjs','/v2/cp-v2-bureau-data.mjs','/v2/cp-v2-company-actions.mjs','/v2/v2.css','/v2/v2.js'].includes(path)){
const moduleFile=path.endsWith('.mjs')||path.endsWith('.js');
const file=path.endsWith('.mjs')?path.slice('/v2/'.length):path.endsWith('.js')?'v2.js':path.endsWith('.css')?'v2.css':'index.html';
return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/'+file,import.meta.url)),{headers:{'Content-Type':moduleFile?'text/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});

View file

@ -1,5 +1,4 @@
import {PostbankStatements} from './postbank-statements.mjs';
import {dirname,join} from 'node:path';
import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs';
import {PostbankBeneficiaries} from './postbank-beneficiaries.mjs';
import {PostbankAdmin} from './postbank-admin.mjs';
import {createPostbankPayments,standardCycle} from './postbank-payments.mjs';
@ -12,21 +11,26 @@ export function createPostbankApi(central,bank,settings={},deps={}){
const service=bank?new PostbankService(bank,authority,deps):null,payments=createPostbankPayments(central,bank,{...deps,authority});
const admin=bank?new PostbankAdmin(bank,central,authority,deps):null;
const beneficiaries=bank?new PostbankBeneficiaries(bank,deps):null;
const statements=bank?new PostbankStatements(bank,payments,{...deps,cacheDir:settings.POSTBANK_STATEMENT_CACHE||(settings.POSTBANK_DB_CONFIG?join(dirname(settings.POSTBANK_DB_CONFIG),'postbank-statements'):null),python:settings.POSTBANK_PYTHON,logo:settings.POSTBANK_STATEMENT_LOGO}):null;
const statements=bank?new PostbankStatementArchive(bank,payments,{...deps,...statementSettings(settings)}):null;
const lookups=new Map(),transferAttempts=new Map();
const reply=(data,status=200)=>Response.json(data,{status,headers:{'Cache-Control':'private, no-store',Vary:'Cookie'}});
return async request=>{
const url=new URL(request.url),path=url.pathname;
const user=await auth(request);if(!user)return reply({message:'Sign in to use Imperial Postbank.'},401);
if(!service)return reply({message:'The independent bank database is not linked yet.',state:'not_linked'},503);
if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
if(!['/api/bank/recipients','/api/bank/activity','/api/bank/statements','/api/bank/statements/archive'].includes(path)&&!path.startsWith('/api/bank/admin/')&&url.search)return reply({message:'Banking identity and account overrides are not accepted.'},400);
if(path==='/api/bank/statements/archive'){
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
if([...url.searchParams.keys()].some(k=>!['accountId','page'].includes(k))||url.searchParams.getAll('accountId').length!==1||url.searchParams.getAll('page').length>1)return reply({message:'Select an archive account.'},400);
try{const accountId=url.searchParams.get('accountId'),data=await statements.list(user,{accountId,page:url.searchParams.get('page')||1}),fresh=await auth(request);if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed.'},403);return reply(data);}catch(error){return reply({message:error.status?error.message:'The statement archive could not be loaded.'},error.status||503);}
}
if(path==='/api/bank/statements'){
if(request.method!=='GET')return reply({message:'Method not allowed.'},405);
if([...url.searchParams.keys()].some(k=>!['accountId','month'].includes(k))||['accountId','month'].some(k=>url.searchParams.getAll(k).length!==1))return reply({message:'Choose one account and month.'},400);
try{const accountId=url.searchParams.get('accountId'),result=await statements.download(user,{accountId,month:url.searchParams.get('month')}),fresh=await auth(request);
if(!fresh||fresh.id!==user.id||!(await payments.accounts(fresh)).some(a=>a.id===accountId))return reply({message:'Your account access changed. Reload the workspace.'},403);
return new Response(result.pdf,{headers:{'Content-Type':'application/pdf','Content-Disposition':'attachment; filename="'+result.filename+'"','Cache-Control':'private, no-store',Vary:'Cookie','X-Content-Type-Options':'nosniff'}});
}catch(error){return reply({message:error.status?error.message:'Your statement could not be generated. Please retry shortly.'},error.status||503);}
}catch(error){return reply({message:error.status?error.message:'Your archived statement could not be downloaded. Please retry shortly.'},error.status||503);}
}
if(path==='/api/bank/beneficiaries'&&request.method==='GET'){
try{const data=await beneficiaries.list(user),fresh=await auth(request);if(!fresh||fresh.id!==user.id)return reply({message:'Your session changed. Reload the workspace.'},403);return reply(data);}catch{return reply({message:'Saved beneficiaries could not be confirmed.'},503);}

View file

@ -1,4 +1,5 @@
export const POSTBANK_CONTRACTS=Object.freeze({
statements:{title:'Monthly account statement archive',state:'active',request:{method:'GET',path:'/api/bank/statements/archive',fields:['accountId','page']},response:{records:'closed months with ready/preparing status and download metadata'},note:'The trusted bank ticker automatically seeds and prepares closed-month PDF statements. Users only list and download already archived files through GET /api/bank/statements?accountId=...&month=.... No user generation endpoint. Brussels month boundaries; ledger history remains preserved. Recoverable worker claims, 25 statements per tick and one-minute continuation while a backlog remains.'},
server:{title:'Game server link',state:'not_linked',request:{method:'POST',path:'/api/bank/integrations/game/payments',fields:['requestId','sourceAccount','targetNumber','amount','reference','mode','gameReceipt']},response:{paymentId:'unique payment reference',state:'queued | posted | rejected'},note:'Future trusted server-to-server payment instructions only. The central bank authorises, reserves and posts; Java must not duplicate accounting or own bank balances. Standard instructions follow the same four-hour Brussels windows; instant instructions post immediately within bank limits. requestId is retained on retries and fulfilment waits for a confirmed posted bank result. No game link or request is enabled by this placeholder. Server credentials must never be supplied by a browser.'},
mandates:{title:'Account authorisations',state:'planned',request:{method:'POST',path:'/api/bank/authorisations',fields:['accountNumber','clientNumber','permissions','startsAt','expiresAt','confirmed']},response:{authorisationId:'new authorisation reference',state:'active | pending'},note:'Creation, editing and revocation of mandates are deferred. Existing imported authority remains checked by the central API.'},
investments:{title:'Securities service',state:'planned',request:{method:'POST',path:'/api/bank/investments/orders',fields:['requestId','securitiesAccount','settlementAccount','instrument','side','quantity','confirmed']},response:{orderId:'unique order reference',state:'accepted | rejected'},note:'No trading request is sent. Civic/Public and all 979 funding or settlement accounts are forbidden. Personal eligibility does not grant access to official money.'},

View file

@ -14,7 +14,7 @@ export async function openPostbankDatabase(settings){
// Apply only missing indexes to this independent bank database. Concurrent worker
// startup can race CREATE INDEX; a duplicate-name result is safe to ignore.
export const POSTBANK_INDEXES=[['pb_orders','pb_orders_source_period','source_id,created_at,id'],['pb_orders','pb_orders_target_period','target_id,created_at,id'],['pb_orders','pb_orders_queue_period','state,mode,created_at,id'],['pb_entries','pb_entries_account_period','account_id,created_at,id']];
export const POSTBANK_INDEXES=[['pb_statement_archives','pb_statement_worker_due','state,retry_at,lease_until,month,account_id'],['pb_orders','pb_orders_source_period','source_id,created_at,id'],['pb_orders','pb_orders_target_period','target_id,created_at,id'],['pb_orders','pb_orders_queue_period','state,mode,created_at,id'],['pb_entries','pb_entries_account_period','account_id,created_at,id']];
export async function ensurePostbankIndexes(db){
for(const [table,name,columns]of POSTBANK_INDEXES){const found=await db.first('SELECT INDEX_NAME FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND INDEX_NAME=? LIMIT 1',[table,name]);if(found)continue;try{await db.query(`CREATE INDEX ${name} ON ${table} (${columns})`);}catch(error){if(error.code!=='ER_DUP_KEYNAME'&&error.errno!==1061)throw error;}}
}

View file

@ -1,3 +1,4 @@
import {PostbankStatementArchive,statementSettings} from './postbank-statement-archive.mjs';
import {createHash,randomUUID} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
import {PACKAGES,minorAmount,money,validBankNumber} from './postbank-catalogue.mjs';
@ -136,12 +137,12 @@ export function standardCycle(now=Date.now()){
return {cutoff:localTimeUTC(p.year,p.month,p.day,hour),nextAt:localTimeUTC(nextLocal.getUTCFullYear(),nextLocal.getUTCMonth()+1,nextLocal.getUTCDate(),nextLocal.getUTCHours())};
}
export function startPostbankQueue(central,bank,settings){
if(settings.POSTBANK_ENABLED!=='true'||!bank)return ()=>{};const service=createPostbankPayments(central,bank);let timer=null,stopped=false;
const schedule=()=>{if(stopped)return;timer=setTimeout(()=>void run(),Math.max(1000,standardCycle().nextAt-Date.now()));timer.unref();};
if(settings.POSTBANK_ENABLED!=='true'||!bank)return ()=>{};const service=createPostbankPayments(central,bank);const archives=new PostbankStatementArchive(bank,null,statementSettings(settings));let timer=null,stopped=false,archiveBacklog=false,lastArchiveSeed=0;
const schedule=()=>{if(stopped)return;timer=setTimeout(()=>void run(),Math.max(1000,Math.min(standardCycle().nextAt-Date.now(),archiveBacklog?60000:Infinity)));timer.unref();};
async function run(){
const cutoff=standardCycle().cutoff,skip=[];
try{while(!stopped){const result=await service.processQueue({cutoff,skip});if(result.failed){skip.push(...result.failedIds);console.error('Postbank queued payment reconciliation needs attention.');}if(result.attempted<25||skip.length>975)break;await new Promise(resolve=>setTimeout(resolve,1000));}}
catch{console.error('Postbank scheduled settlement needs attention.');}finally{schedule();}
catch{console.error('Postbank scheduled settlement needs attention.');}finally{try{if(Date.now()-lastArchiveSeed>3600000){await archives.seed();lastArchiveSeed=Date.now();}const result=await archives.process();archiveBacklog=result.attempted===25;if(result.failed)console.error('Postbank automatic statement archive needs attention.');}catch{console.error('Postbank statement ticker failed.');}schedule();}
}
// Recover only instructions belonging to the most recent settlement cutoff.
// New instructions after that cutoff continue waiting for the next four-hour window.

View file

@ -83,3 +83,11 @@ CREATE TABLE IF NOT EXISTS pb_beneficiaries (
CREATE TABLE IF NOT EXISTS pb_contact_locks (
owner_id CHAR(36) PRIMARY KEY
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS pb_statement_archives (
account_id BIGINT UNSIGNED NOT NULL, month CHAR(7) NOT NULL,
state VARCHAR(16) NOT NULL DEFAULT 'pending', claim_token CHAR(36) NULL,
lease_until BIGINT NOT NULL DEFAULT 0, retry_at BIGINT NOT NULL DEFAULT 0,
file_key VARCHAR(80) NULL, file_hash CHAR(64) NULL, file_size BIGINT NOT NULL DEFAULT 0,
created_at BIGINT NOT NULL, generated_at BIGINT NULL,
PRIMARY KEY(account_id,month), FOREIGN KEY(account_id) REFERENCES pb_accounts(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View file

@ -0,0 +1,21 @@
import {readFile} from 'node:fs/promises';
import {join,dirname} from 'node:path';
import {createHash,randomUUID} from 'node:crypto';
import {BankError} from './postbank-service.mjs';
import {PostbankStatements,statementMonth} from './postbank-statements.mjs';
export const statementSettings=settings=>({cacheDir:settings.POSTBANK_STATEMENT_CACHE||(settings.POSTBANK_DB_CONFIG?join(dirname(settings.POSTBANK_DB_CONFIG),'postbank-statements'):null),python:settings.POSTBANK_PYTHON,logo:settings.POSTBANK_STATEMENT_LOGO});
const monthOf=time=>{const p=Object.fromEntries(new Intl.DateTimeFormat('en-CA',{timeZone:'Europe/Brussels',year:'numeric',month:'2-digit'}).formatToParts(new Date(time)).filter(p=>p.type!=='literal').map(p=>[p.type,p.value]));return p.year+'-'+p.month;};
const nextMonth=month=>{const [y,m]=month.split('-').map(Number),d=new Date(Date.UTC(y,m,1));return d.toISOString().slice(0,7);};
export class PostbankStatementArchive{
constructor(db,payments,options={}){this.db=db;this.payments=payments;this.clock=options.clock||Date.now;this.cacheDir=options.cacheDir;this.renderer=options.renderer||new PostbankStatements(db,null,options);}
async account(user,accountId){if(typeof accountId!=='string'||!/^\d{1,12}$/.test(accountId))throw new BankError('Select an account.');const account=(await this.payments.accounts(user)).find(a=>a.id===accountId);if(!account)throw new BankError('You cannot view this account.',403);return account;}
async list(user,{accountId,page=1}){const account=await this.account(user,accountId);page=Number(page);if(!Number.isInteger(page)||page<1||page>999)throw new BankError('Select a valid archive page.');const current=monthOf(this.clock()),rows=await this.db.query('SELECT month,state,generated_at,file_size FROM pb_statement_archives WHERE account_id=? AND month<? ORDER BY month DESC LIMIT 13 OFFSET '+((page-1)*12),[accountId,current]);return {account:{id:account.id,number:account.number,name:account.name},records:rows.slice(0,12).map(r=>({month:r.month,state:r.state==='ready'?'ready':'preparing',generatedAt:r.generated_at?Number(r.generated_at):null,size:Number(r.file_size)})),hasMore:rows.length>12,page,nextClosing:statementMonth(current,this.clock()).end};}
// Downloads only read an already archived file. Never render or enqueue here.
async download(user,{accountId,month}){const account=await this.account(user,accountId),period=statementMonth(month,this.clock());if(period.provisional)throw new BankError('This month has not closed yet.',409);const row=await this.db.first("SELECT file_key,file_hash,file_size FROM pb_statement_archives WHERE account_id=? AND month=? AND state='ready'",[accountId,month]);if(!row)throw new BankError('This statement is not yet available. The bank prepares statements automatically after month-end.',404);if(!this.cacheDir||!/^[a-f0-9]{64}\.pdf$/.test(row.file_key||''))throw new BankError('Archived statement unavailable. Contact bank administration.',503);let pdf;try{pdf=await readFile(join(this.cacheDir,row.file_key));}catch{throw new BankError('Archived statement unavailable. Contact bank administration.',503);}if(pdf.length!==Number(row.file_size)||createHash('sha256').update(pdf).digest('hex')!==row.file_hash)throw new BankError('Archived statement integrity check failed.',503);return {pdf,filename:'Statement-'+account.number+'-'+month+'.pdf'};}
// Trusted bank ticker only: account identity comes solely from the bank database.
async seed(){const now=this.clock(),current=monthOf(now),first=await this.db.first('SELECT MIN(created_at) first_at FROM pb_accounts WHERE client_number IS NOT NULL');if(first?.first_at===null||first?.first_at===undefined)return;let month=monthOf(Number(first.first_at));if(month<'2026-01')month='2026-01';for(;month<current;month=nextMonth(month)){const period=statementMonth(month,now);await this.db.query("INSERT INTO pb_statement_archives(account_id,month,state,created_at) SELECT id,?,'pending',? FROM pb_accounts WHERE client_number IS NOT NULL AND created_at<? ON DUPLICATE KEY UPDATE account_id=VALUES(account_id)",[month,now,period.end]);}}
async process({limit=25}={}){if(!this.cacheDir)return {attempted:0,completed:0,failed:0};let attempted=0,completed=0,failed=0;while(attempted<limit){const now=this.clock(),claim=await this.db.transaction(async tx=>{const row=await tx.first("SELECT account_id,month FROM pb_statement_archives WHERE ((state IN ('pending','failed') AND retry_at<=?) OR (state='processing' AND lease_until<?)) ORDER BY month,account_id LIMIT 1 FOR UPDATE",[now,now]);if(!row)return null;const token=randomUUID();await tx.query("UPDATE pb_statement_archives SET state='processing',claim_token=?,lease_until=? WHERE account_id=? AND month=?",[token,now+120000,row.account_id,row.month]);return {...row,token};});if(!claim)break;attempted++;
try{const result=await this.renderer.prepare(String(claim.account_id),claim.month),hash=createHash('sha256').update(result.pdf).digest('hex');await this.db.query("UPDATE pb_statement_archives SET state='ready',file_key=?,file_hash=?,file_size=?,generated_at=?,claim_token=NULL,lease_until=0 WHERE account_id=? AND month=? AND claim_token=?",[result.fileKey,hash,result.pdf.length,this.clock(),claim.account_id,claim.month,claim.token]);completed++;}
catch{await this.db.query("UPDATE pb_statement_archives SET state='failed',retry_at=?,claim_token=NULL,lease_until=0 WHERE account_id=? AND month=? AND claim_token=?",[this.clock()+4*3600000,claim.account_id,claim.month,claim.token]);failed++;}
}return {attempted,completed,failed};}
}

View file

@ -32,6 +32,15 @@ export class PostbankStatements{
async download(user,{accountId,month}){
if(typeof accountId!=='string'||!/^\d{1,12}$/.test(accountId))throw new BankError('Choose an account for your statement.');
const period=statementMonth(month,this.clock()),accounts=await this.payments.accounts(user),account=accounts.find(a=>a.id===accountId);if(!account)throw new BankError('You cannot view this account.',403);
return this.build(account,period);
}
async prepare(accountId,month){
const period=statementMonth(month,this.clock());if(period.provisional)throw new BankError('Only closed months can be archived.',409);
const account=await this.db.first('SELECT a.account_number number,a.display_name name,e.display_name holder FROM pb_accounts a JOIN pb_clients c ON c.client_number=a.client_number JOIN pb_entities e ON e.id=c.entity_id WHERE a.id=?',[accountId]);if(!account)throw new BankError('Account not found.',404);
return this.build({...account,id:String(accountId)},period);
}
async build(account,period){
const accountId=account.id,month=period.month;
const snapshot=await this.db.transaction(async tx=>{
const row=await tx.first('SELECT created_at FROM pb_accounts WHERE id=?',[accountId]);if(!row||Number(row.created_at)>=period.end)throw new BankError('This account did not exist during that month.',404);
const opening=await tx.first('SELECT balance_after_minor,id FROM pb_entries WHERE account_id=? AND created_at<? ORDER BY created_at DESC,id DESC LIMIT 1',[accountId,period.start]);
@ -41,7 +50,7 @@ export class PostbankStatements{
// Cache fingerprints include ledger endpoints and holder details; no private URL is exposed.
const signature=createHash('sha256').update(JSON.stringify(['statement-v1',account.number,account.name,account.holder,period.month,snapshot])).digest('hex');
const cached=!period.provisional&&this.cacheDir?join(this.cacheDir,signature+'.pdf'):null;
if(cached){try{const pdf=await readFile(cached);if(pdf.subarray(0,5).toString()==='%PDF-')return {pdf,filename:'Statement-'+account.number+'-'+month+'.pdf'};}catch(e){if(e.code!=='ENOENT')throw e;}}
if(cached){try{const pdf=await readFile(cached);if(pdf.subarray(0,5).toString()==='%PDF-')return {pdf,fileKey:signature+'.pdf',filename:'Statement-'+account.number+'-'+month+'.pdf'};}catch(e){if(e.code!=='ENOENT')throw e;}}
const rows=await this.db.query('SELECT e.id,e.created_at,e.amount_minor,e.balance_after_minor,o.id payment_id,o.memo,s.account_number source_number,t.account_number target_number,COALESCE(es.display_name,s.display_name) source_name,COALESCE(et.display_name,t.display_name) target_name FROM pb_entries e JOIN pb_orders o ON o.id=e.order_id JOIN pb_accounts s ON s.id=o.source_id LEFT JOIN pb_clients cs ON cs.client_number=s.client_number LEFT JOIN pb_entities es ON es.id=cs.entity_id JOIN pb_accounts t ON t.id=o.target_id LEFT JOIN pb_clients ct ON ct.client_number=t.client_number LEFT JOIN pb_entities et ON et.id=ct.entity_id WHERE e.account_id=? AND e.created_at>=? AND e.created_at<? AND e.id<=? ORDER BY e.created_at,e.id LIMIT 10001',[accountId,period.start,period.end,snapshot.lastId]);
if(rows.length>10000)throw new BankError('This month exceeds the online statement limit. Contact bank administration for a complete export.',409);
const data={account:{holder:account.holder,number:account.number,name:account.name},month,provisional:period.provisional,generatedAt:this.clock(),opening:snapshot.opening,closing:snapshot.closing,entries:rows.map(r=>({id:String(r.id),date:Number(r.created_at),paymentId:r.payment_id,reference:r.memo,from:{name:r.source_name,number:r.source_number},to:{name:r.target_name,number:r.target_number},amount:money(r.amount_minor),balance:money(r.balance_after_minor)}))};
@ -51,6 +60,6 @@ export class PostbankStatements{
const cents=value=>BigInt(value.replace('.',''));if(cents(data.opening)+total!==cents(data.closing))throw new BankError('Statement balances need reconciliation. Contact bank administration.',409);
const pdf=await this.renderPDF(data);
if(cached){await mkdir(this.cacheDir,{recursive:true,mode:0o700});const temp=cached+'.'+randomUUID()+'.tmp';try{await writeFile(temp,pdf,{mode:0o600,flag:'wx'});await rename(temp,cached);}finally{await unlink(temp).catch(()=>{});}}
return {pdf,filename:'Statement-'+account.number+'-'+month+'.pdf'};
return {pdf,fileKey:signature+'.pdf',filename:'Statement-'+account.number+'-'+month+'.pdf'};
}
}

View file

@ -1,3 +1,4 @@
import {PostbankStatementArchive} from '../node/postbank-statement-archive.mjs';
import test from 'node:test';import assert from 'node:assert/strict';import {randomUUID} from 'node:crypto';import {mkdtemp,rm} from 'node:fs/promises';import {tmpdir} from 'node:os';import {join} from 'node:path';
import {BankFixture} from './postbank-fixture.mjs';import {PostbankService} from '../node/postbank-service.mjs';import {PostbankPayments} from '../node/postbank-payments.mjs';import {PostbankBeneficiaries} from '../node/postbank-beneficiaries.mjs';import {PostbankStatements,statementMonth} from '../node/postbank-statements.mjs';import {createPostbankApi} from '../node/postbank-api.mjs';import {BANK_VERSION} from '../node/postbank-catalogue.mjs';
const now=Date.parse('2026-11-13T20:00:00Z');
@ -7,4 +8,5 @@ test('revoked contact session rolls back the edit and dormant accounts are not s
async function seed(f){const [current,savings]=f.accounts,at=Date.parse('2026-10-15T12:00:00Z'),id=randomUUID();await f.db.query('INSERT INTO pb_orders(id,actor_id,source_id,target_id,fingerprint,amount_minor,memo,mode,state,created_at,posted_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)',[id,f.users[0].id,savings.id,current.id,'0'.repeat(64),10000,'Fixture opening','system','posted',at,at]);for(const [account,amount,balance]of [[current.id,10000,10000],[savings.id,-10000,-10000]]){await f.db.query('INSERT INTO pb_entries(order_id,account_id,amount_minor,balance_after_minor,created_at) VALUES(?,?,?,?,?)',[id,account,amount,balance,at]);await f.db.query('UPDATE pb_accounts SET balance_minor=? WHERE id=?',[balance,account]);}return {current,savings};}
test('interactive history is bounded to 30 days and filters are literal without deleting old entries',async()=>{const f=await setup();try{const {current,savings}=await seed(f);await f.payments.transfer(f.users[0],{requestId:randomUUID(),sourceAccount:String(current.id),targetNumber:savings.account_number,amount:'10.00',reference:'November transfer','mode':'instant',confirmed:false});assert.equal((await f.payments.activity(f.users[0],{q:'November'})).records.length,1);assert.equal((await f.payments.activity(f.users[0],{q:'%'})).records.length,0);assert.equal((await f.payments.activity(f.users[0],{state:'queued'})).records.length,0);await f.db.query('UPDATE pb_orders SET created_at=? WHERE memo=?',[now-31*86400000,'Fixture opening']);assert.equal((await f.payments.activity(f.users[0])).records.length,1);assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_entries')).n,4);await assert.rejects(f.payments.activity(f.users[0],{from:'2026-02-30'}));await assert.rejects(f.payments.activity(f.users[0],{to:'2026-01-01'}));}finally{f.db.close();}});
test('monthly statements use posting dates, preserve opening/closing balances, cache closed months and enforce access',async()=>{const f=await setup(),dir=await mkdtemp(join(tmpdir(),'pb-statement-test-'));try{const {current,savings}=await seed(f);await f.payments.transfer(f.users[0],{requestId:randomUUID(),sourceAccount:String(current.id),targetNumber:savings.account_number,amount:'10.00',reference:'November transfer',mode:'instant',confirmed:false});const payloads=[],statements=new PostbankStatements(f.db,f.payments,{clock:()=>now,cacheDir:dir,renderPDF:async data=>{payloads.push(data);return Buffer.from('%PDF-fixture');}});await statements.download(f.users[0],{accountId:String(current.id),month:'2026-10'});assert.equal(payloads[0].opening,'0.00');assert.equal(payloads[0].closing,'100.00');assert.equal(payloads[0].entries.length,1);await statements.download(f.users[0],{accountId:String(current.id),month:'2026-10'});assert.equal(payloads.length,1);await statements.download(f.users[0],{accountId:String(current.id),month:'2026-11'});assert.equal(payloads[1].provisional,true);assert.equal(payloads[1].opening,'100.00');assert.equal(payloads[1].closing,'90.00');await assert.rejects(statements.download(f.users[1],{accountId:String(current.id),month:'2026-10'}),e=>e.status===403);await assert.rejects(statements.download(f.users[0],{accountId:String(current.id),month:'2026-09'}),e=>e.status===404);assert.equal(statementMonth('2026-10',now).start,Date.parse('2026-09-30T22:00:00Z'));assert.equal(statementMonth('2026-11',now).start,Date.parse('2026-10-31T23:00:00Z'));}finally{f.db.close();await rm(dir,{recursive:true,force:true});}});
test('PDF API returns private download headers and rechecks account access after rendering',async()=>{const f=await setup();try{const {current}=await seed(f);let actor=f.users[0];const deps={clock:()=>now,authority:f.authority,authenticate:async()=>actor,renderPDF:async()=>Buffer.from('%PDF-fixture')};const api=createPostbankApi(null,f.db,{},deps),url='https://cp.dunerealms.com/api/bank/statements?accountId='+current.id+'&month=2026-10',response=await api(new Request(url));assert.equal(response.status,200);assert.equal(response.headers.get('content-type'),'application/pdf');assert.equal(response.headers.get('cache-control'),'private, no-store');const revoked=createPostbankApi(null,f.db,{}, {...deps,renderPDF:async()=>{actor=f.users[1];return Buffer.from('%PDF-fixture');}});assert.equal((await revoked(new Request(url))).status,403);assert.equal((await api(new Request(url+'&actor=other'))).status,400);}finally{f.db.close();}});
test('bank ticker builds closed-month archives; reads and downloads cannot generate statements',async()=>{const f=await setup(),dir=await mkdtemp(join(tmpdir(),'pb-auto-archive-'));try{const {current}=await seed(f);let rendered=0;const renderPDF=async()=>{rendered++;return Buffer.from('%PDF-fixture');},archive=new PostbankStatementArchive(f.db,f.payments,{clock:()=>now,cacheDir:dir,renderPDF});await assert.rejects(archive.download(f.users[0],{accountId:String(current.id),month:'2026-10'}),e=>e.status===404);assert.equal(rendered,0);assert.equal((await archive.list(f.users[0],{accountId:String(current.id)})).records.length,0);await archive.seed();await archive.seed();assert.equal((await f.db.first('SELECT COUNT(*) n FROM pb_statement_archives')).n,4);const results=await Promise.all([archive.process(),archive.process()]);assert.equal(results.reduce((s,r)=>s+r.completed,0),4);assert.equal(rendered,4);const list=await archive.list(f.users[0],{accountId:String(current.id)});assert.equal(list.records[0].month,'2026-10');assert.equal(list.records[0].state,'ready');await archive.download(f.users[0],{accountId:String(current.id),month:'2026-10'});assert.equal(rendered,4);await assert.rejects(archive.download(f.users[0],{accountId:String(current.id),month:'2026-11'}),e=>e.status===409);await assert.rejects(archive.list(f.users[1],{accountId:String(current.id)}),e=>e.status===403);assert.equal((await archive.process()).completed,0);}finally{f.db.close();await rm(dir,{recursive:true,force:true});}});
test('archive failures retry on a bank tick, interrupted claims recover, API downloads stay private',async()=>{const f=await setup(),dir=await mkdtemp(join(tmpdir(),'pb-archive-retry-'));try{const {current}=await seed(f);let clock=now,broken=true,renders=0;const renderer=new PostbankStatements(f.db,null,{clock:()=>clock,cacheDir:dir,renderPDF:async()=>{renders++;if(broken)throw Error('fixture failure');return Buffer.from('%PDF-fixture');}}),archive=new PostbankStatementArchive(f.db,f.payments,{clock:()=>clock,cacheDir:dir,renderer});await archive.seed();assert.equal((await archive.process({limit:1})).failed,1);broken=false;await f.db.query("UPDATE pb_statement_archives SET state='processing',lease_until=?,claim_token=? WHERE account_id=?",[clock-1,randomUUID(),f.accounts[1].id]);clock+=4*3600000+1;assert.equal((await archive.process()).completed,4);const settings={POSTBANK_STATEMENT_CACHE:dir};let actor=f.users[0];const deps={clock:()=>clock,authority:f.authority,authenticate:async()=>actor,renderPDF:async()=>{throw Error('HTTP MUST NOT RENDER');}},api=createPostbankApi(null,f.db,settings,deps),url='https://cp.dunerealms.com/api/bank/statements?accountId='+current.id+'&month=2026-10';const response=await api(new Request(url));assert.equal(response.status,200);assert.equal(response.headers.get('content-type'),'application/pdf');assert.equal(response.headers.get('cache-control'),'private, no-store');const archiveURL='https://cp.dunerealms.com/api/bank/statements/archive?accountId='+current.id;assert.equal((await api(new Request(archiveURL))).status,200);actor=f.users[1];assert.equal((await api(new Request(url))).status,403);assert.equal((await api(new Request(archiveURL))).status,403);assert.equal((await api(new Request(url+'&actor=other'))).status,400);assert.equal(renders,5);}finally{f.db.close();await rm(dir,{recursive:true,force:true});}});