Restore embedded DuneGit SSO and move workspace controls below content
This commit is contained in:
parent
dcd881061c
commit
6a9a0ffd67
7 changed files with 105 additions and 17 deletions
|
|
@ -30,16 +30,16 @@ export function mountNativeService(host,id,{fetcher=fetch,singleHeading=false,in
|
|||
const base=NATIVE_SERVICES[id];if(!base)throw Error('Unknown native service.');const spec={...base,url:nativeServiceURL(id,{initialTab,listingId,folder,composeMessage,wireTransfer}),...(typeof title==='string'?{title}:{} )};
|
||||
let active=true,controller=null,frame=null,hasSize=false,ownObserver=null;
|
||||
const status=el('p','Checking your workspace access…','cp-v2-news-status');status.setAttribute('role','status');
|
||||
const workspace=el('section',undefined,'cp-v2-native-workspace'),tools=el('div',undefined,'cp-v2-company-actions'),retry=el('button','Reload workspace');retry.type='button';tools.append(retry);workspace.append(status,tools);
|
||||
const container=el('div',undefined,'cp-v2-native-frame');workspace.append(container);
|
||||
const workspace=el('section',undefined,'cp-v2-native-workspace'),tools=el('div',undefined,'cp-v2-company-actions'),retry=el('button','Reload workspace');retry.type='button';tools.append(retry);workspace.append(status);
|
||||
const container=el('div',undefined,'cp-v2-native-frame');workspace.append(container,tools);
|
||||
const {root}=createCPV2Page({shellHost:singleHeading?host:null,title:spec.title,description:spec.description,artwork:id==='forum-admin'?'nav-boards-v2.webp':'nav-support-v2.webp',tabs:[{id:'native-workspace',label:spec.label,content:workspace}]});host.replaceChildren(root);
|
||||
const origin=new URL(spec.url).origin;
|
||||
const measure=()=>{if(active&&frame?.contentWindow){if(spec.selfResize&&origin===location.origin){try{const body=frame.contentDocument?.body;if(body){const height=Math.ceil(body.getBoundingClientRect().height+16);if(height>=100&&height<=200000){frame.style.height=Math.max(360,height)+'px';frame.setAttribute('scrolling','no');hasSize=true;status.textContent=spec.label+' · Embedded workspace connected.';}}}catch{}}frame.contentWindow.postMessage({type:'dune-embed-measure'},origin);if(spec.shop)frame.contentWindow.postMessage({type:'dune-shop-measure'},origin);}};
|
||||
const receive=event=>{if(!active||!frame)return;const height=nativeFrameHeight(event,frame,origin);if(height===null)return;frame.style.height=height+'px';frame.setAttribute('scrolling','no');hasSize=true;status.textContent=spec.label+' · Embedded workspace connected.';};
|
||||
const measure=()=>{if(active&&frame?.contentWindow){if(spec.selfResize&&origin===location.origin){try{const body=frame.contentDocument?.body;if(body){const height=Math.ceil(body.getBoundingClientRect().height+16);if(height>=100&&height<=200000){frame.style.height=Math.max(360,height)+'px';frame.setAttribute('scrolling','no');hasSize=true;status.hidden=true;}}}catch{}}frame.contentWindow.postMessage({type:'dune-embed-measure'},origin);if(spec.shop)frame.contentWindow.postMessage({type:'dune-shop-measure'},origin);}};
|
||||
const receive=event=>{if(!active||!frame)return;const height=nativeFrameHeight(event,frame,origin);if(height===null)return;frame.style.height=height+'px';frame.setAttribute('scrolling','no');hasSize=true;status.hidden=true;};
|
||||
window.addEventListener('message',receive);window.addEventListener('resize',measure);
|
||||
async function load(){controller?.abort();controller=new AbortController();const current=controller;const timeout=setTimeout(()=>current.abort(),15000);retry.disabled=true;ownObserver?.disconnect();ownObserver=null;container.replaceChildren();frame=null;hasSize=false;status.textContent='Checking current account permissions…';
|
||||
try{const response=await fetcher('/api/auth/session',{credentials:'same-origin',cache:'no-store',signal:current.signal});const data=await response.json();if(!active||current!==controller)return;if(!response.ok||!data.authenticated)throw Error('Sign in to open this workspace.');if(!nativeServiceAccess(data.user,spec))throw Error('Your account does not have permission to open '+spec.label+'.');frame=el('iframe');frame.title=spec.label;frame.referrerPolicy='strict-origin-when-cross-origin';if(spec.shop)frame.setAttribute('sandbox','allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation');let bootstrapping=!!spec.bootstrapUrl;frame.src=spec.bootstrapUrl||spec.url;frame.style.height='900px';frame.onload=()=>{if(!active)return;if(bootstrapping){bootstrapping=false;hasSize=false;frame.src=spec.url;return;}if(spec.selfResize&&origin===location.origin){try{const doc=frame.contentDocument;if(doc?.body){doc.documentElement.style.minHeight='0';doc.body.style.minHeight='0';doc.body.style.height='auto';ownObserver?.disconnect();ownObserver=new ResizeObserver(measure);ownObserver.observe(doc.body);}}catch{}}if(!hasSize)status.textContent='Native workspace loaded. Its own account and role checks remain authoritative.';measure();};container.append(frame);status.textContent='Opening your existing '+spec.label.toLowerCase()+' session…';}
|
||||
catch(error){if(active&¤t===controller)status.textContent=current.signal.aborted?'The access check timed out. Reload to try again.':error.message;}
|
||||
async function load(){controller?.abort();controller=new AbortController();const current=controller;const timeout=setTimeout(()=>current.abort(),15000);retry.disabled=true;ownObserver?.disconnect();ownObserver=null;container.replaceChildren();frame=null;hasSize=false;status.hidden=false;status.textContent='Checking current account permissions…';
|
||||
try{const response=await fetcher('/api/auth/session',{credentials:'same-origin',cache:'no-store',signal:current.signal});const data=await response.json();if(!active||current!==controller)return;if(!response.ok||!data.authenticated)throw Error('Sign in to open this workspace.');if(!nativeServiceAccess(data.user,spec))throw Error('Your account does not have permission to open '+spec.label+'.');frame=el('iframe');frame.title=spec.label;frame.referrerPolicy='strict-origin-when-cross-origin';if(spec.shop)frame.setAttribute('sandbox','allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation');let bootstrapping=!!spec.bootstrapUrl;frame.src=spec.bootstrapUrl||spec.url;frame.style.height='900px';frame.onload=()=>{if(!active)return;if(bootstrapping){bootstrapping=false;hasSize=false;frame.src=spec.url;return;}if(spec.selfResize&&origin===location.origin){try{const doc=frame.contentDocument;if(doc?.body){doc.documentElement.style.minHeight='0';doc.body.style.minHeight='0';doc.body.style.height='auto';ownObserver?.disconnect();ownObserver=new ResizeObserver(measure);ownObserver.observe(doc.body);}}catch{}}status.hidden=true;measure();};container.append(frame);status.textContent='Opening your existing '+spec.label.toLowerCase()+' session…';}
|
||||
catch(error){if(active&¤t===controller){status.hidden=false;status.textContent=current.signal.aborted?'The access check timed out. Reload to try again.':error.message;}}
|
||||
finally{clearTimeout(timeout);if(active&¤t===controller)retry.disabled=false;}
|
||||
}
|
||||
retry.onclick=()=>void load();void load();return()=>{active=false;controller?.abort();ownObserver?.disconnect();window.removeEventListener('message',receive);window.removeEventListener('resize',measure);if(frame)frame.src='about:blank';root.remove();};
|
||||
|
|
|
|||
|
|
@ -1,20 +1,25 @@
|
|||
import {request as httpRequest} from 'node:http';
|
||||
export function createForgejoProxy(settings){
|
||||
export function createForgejoProxy(settings,identityFor=async()=>null){
|
||||
if(!settings.FORGEJO_URL)return ()=>false;
|
||||
const upstream=new URL(settings.FORGEJO_URL),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com');
|
||||
if(upstream.protocol!=='http:'||!['127.0.0.1','localhost'].includes(upstream.hostname))throw Error('Forgejo must bind to localhost');
|
||||
return (req,res)=>{
|
||||
if(req.url==='/git'||req.url?.startsWith('/git?')){res.writeHead(308,{Location:'/git/'+(req.url.slice(4)||''),'Cache-Control':'no-store'});res.end();return true;}
|
||||
if(!req.url?.startsWith('/git/'))return false;
|
||||
if(!req.url?.startsWith('/git/')||req.url.split('?')[0].startsWith('/git/sso/'))return false;
|
||||
const authHeader=settings.FORGEJO_AUTH_HEADER?.toLowerCase();
|
||||
const headers={...req.headers,host:origin.host,'x-forwarded-proto':origin.protocol.slice(0,-1),'x-forwarded-host':origin.host,'x-forwarded-for':req.socket.remoteAddress};
|
||||
for(const key of Object.keys(headers))if(key.startsWith('oai-')||key.startsWith('x-internal-')||key.startsWith('x-webauth-')||['connection','upgrade','proxy-authorization'].includes(key))delete headers[key];
|
||||
if(headers.cookie)headers.cookie=headers.cookie.split(';').filter(c=>!c.trim().startsWith('__Host-dune_session=')).join(';');
|
||||
for(const key of Object.keys(headers))if(key===authHeader||key.startsWith('oai-')||key.startsWith('x-internal-')||key.startsWith('x-webauth-')||['connection','upgrade','proxy-authorization'].includes(key))delete headers[key];
|
||||
if(headers.cookie)headers.cookie=headers.cookie.split(';').filter(c=>!c.trim().startsWith('__Host-dune_')).join(';');
|
||||
req.setTimeout(300000);
|
||||
const request=httpRequest({hostname:upstream.hostname,port:upstream.port,method:req.method,path:req.url.slice(4),headers},response=>{
|
||||
const forward=()=>{const request=httpRequest({hostname:upstream.hostname,port:upstream.port,method:req.method,path:req.url.slice(4),headers},response=>{
|
||||
const out={...response.headers};delete out.connection;res.writeHead(response.statusCode||502,out);response.pipe(res);response.on('error',()=>res.destroy());
|
||||
});
|
||||
request.setTimeout(300000,()=>request.destroy());
|
||||
request.on('error',()=>{if(!res.headersSent)res.writeHead(502,{'Content-Type':'text/plain','Cache-Control':'no-store'});res.end('The code forge is temporarily unavailable.');});
|
||||
res.on('close',()=>{if(!res.writableEnded)request.destroy();});req.on('aborted',()=>request.destroy());req.pipe(request);return true;
|
||||
res.on('close',()=>{if(!res.writableEnded)request.destroy();});req.on('aborted',()=>request.destroy());req.pipe(request);};
|
||||
if(authHeader&&!req.headers.authorization&&!/\/git-(?:upload|receive)-pack(?:\?|$)|\.git(?:\/|\?|$)|^\/git\/(?:api|assets)\//.test(req.url)){
|
||||
Promise.resolve().then(()=>identityFor(req)).then(login=>{if(res.destroyed)return;if(login)headers[authHeader]=login;forward();}).catch(()=>{if(!res.headersSent)res.writeHead(503,{'Content-Type':'text/plain','Cache-Control':'no-store'});res.end('DuneGit sign-in is temporarily unavailable.');});
|
||||
}else forward();
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {createGitIdentityRoute,initializeGitIdentities,gitProxyIdentity} from './git-identity.mjs';
|
||||
import {createPublicExchange} from './exchange-public.mjs';
|
||||
import {publicBanCards,publicAppealCards,publicBanList,publicAccountBans} from './public-bans.mjs';
|
||||
import {initializeRanks,can} from './permissions.mjs';
|
||||
|
|
@ -21,6 +22,7 @@ const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-ori
|
|||
export function createApplication(db,settings={}) {
|
||||
const origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
|
||||
const auth=createAuth(db,origin);
|
||||
const gitIdentity=createGitIdentityRoute(db,settings,origin);
|
||||
const worldStatus=createWorldStatus(settings);
|
||||
const publicRoster=createPublicStaffRoster(db);
|
||||
const contact=createContact(settings);
|
||||
|
|
@ -29,6 +31,7 @@ export function createApplication(db,settings={}) {
|
|||
const publicNews=createPublicNews(db);const publicExchange=createPublicExchange(db,settings);
|
||||
return async function handle(request) {
|
||||
const url=new URL(request.url);
|
||||
if(url.pathname.startsWith('/git/sso/')||url.pathname==='/api/git/me')return gitIdentity(request);
|
||||
if(url.pathname==='/api/exchange/listings')return publicExchange(request);
|
||||
// Website articles use the editorial register, before the legacy Discord feed.
|
||||
if(url.pathname==='/api/news'||url.pathname.startsWith('/api/news/')||url.pathname==='/api/home/forum')return publicNews(request);
|
||||
|
|
@ -75,8 +78,11 @@ export function createApplication(db,settings={}) {
|
|||
};
|
||||
}
|
||||
export async function start(settings=process.env) {
|
||||
const db=await openDatabase(settings);await initializeRanks(db);await initializePublicRoster(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
|
||||
const forgejo=createForgejoProxy(settings);
|
||||
const db=await openDatabase(settings);await initializeRanks(db);await initializeGitIdentities(db);await initializePublicRoster(db);await initializeCompanyRegistry(db);await initializeShareLedger(db);const handle=createApplication(db,settings),origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin;
|
||||
let forgeHeader=settings.FORGEJO_AUTH_HEADER;
|
||||
if(!forgeHeader&&settings.FORGEJO_URL){const config=await readFile(settings.FORGEJO_CONFIG_FILE||'/home/dunerealms/apps/forgejo/custom/conf/app.ini','utf8');forgeHeader=config.match(/^REVERSE_PROXY_AUTHENTICATION_USER\s*=\s*(.+)$/mi)?.[1]?.trim();}
|
||||
if(settings.FORGEJO_URL&&!/^[A-Za-z0-9-]+$/.test(forgeHeader||''))throw Error('DuneGit proxy identity header is not configured.');
|
||||
const forgejo=createForgejoProxy({...settings,FORGEJO_AUTH_HEADER:forgeHeader},gitProxyIdentity(db,settings));
|
||||
const server=createServer(async(req,res)=>{
|
||||
try{
|
||||
if(forgejo(req,res))return;
|
||||
|
|
@ -84,7 +90,7 @@ export async function start(settings=process.env) {
|
|||
let bytes=0;const chunks=[];for await(const chunk of req){bytes+=chunk.length;if(bytes>65536){res.writeHead(413);res.end('Request too large');return;}chunks.push(chunk);}
|
||||
const path=req.url||'/';if(!path.startsWith('/')||path.startsWith('//')){res.writeHead(400);res.end('Bad request');return;}
|
||||
const request=new Request(origin+path,{method:req.method,headers:req.headers,body:['GET','HEAD'].includes(req.method)?undefined:Buffer.concat(chunks)});
|
||||
const result=await handle(request),outgoing=new Headers(security);for(const [key,value]of result.headers)outgoing.set(key,value);outgoing.set('Content-Security-Policy',security['Content-Security-Policy']);res.writeHead(result.status,Object.fromEntries(outgoing));res.end(Buffer.from(await result.arrayBuffer()));
|
||||
const result=await handle(request),outgoing=new Headers(security);for(const [key,value]of result.headers)outgoing.set(key,value);outgoing.set('Content-Security-Policy',path.startsWith('/git/sso/')?(result.headers.get('Content-Security-Policy')||security['Content-Security-Policy']):security['Content-Security-Policy']);res.writeHead(result.status,Object.fromEntries(outgoing));res.end(Buffer.from(await result.arrayBuffer()));
|
||||
}catch(error){console.error('Request failed:',error.code||error.name);if(!res.headersSent)res.writeHead(503,{'Content-Type':'application/json','Cache-Control':'no-store'});res.end(JSON.stringify({message:'The website is temporarily unavailable.'}));}
|
||||
});
|
||||
server.requestTimeout=300000;server.headersTimeout=10000;
|
||||
|
|
|
|||
43
website/ops/apply-git-embed-policy.py
Normal file
43
website/ops/apply-git-embed-policy.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Apply the CP-only DuneGit embedding policy to the current website upstream."""
|
||||
from pathlib import Path
|
||||
import datetime,fcntl,re,shutil,subprocess
|
||||
lock=open('/var/lib/dunerealms-ci-promote/safe-lock','a')
|
||||
fcntl.flock(lock,fcntl.LOCK_EX)
|
||||
p=Path('/etc/nginx/sites-enabled/dunerealms.com.conf')
|
||||
s=p.read_text()
|
||||
marker=' # DuneGit embedded workspace policy'
|
||||
if marker in s:
|
||||
print('DuneGit embedding policy already installed.')
|
||||
raise SystemExit(0)
|
||||
assert s.count(' location / {')==1
|
||||
port=re.search(r'proxy_pass\s+http://127\.0\.0\.1:(\d+)/;',s).group(1)
|
||||
block=''' # DuneGit embedded workspace policy
|
||||
location ^~ /git/ {
|
||||
proxy_pass http://127.0.0.1:PORT;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_hide_header X-Frame-Options;
|
||||
add_header Content-Security-Policy "frame-ancestors 'self' https://cp.dunerealms.com" always;
|
||||
add_header X-Content-Type-Options nosniff always;
|
||||
add_header Referrer-Policy strict-origin-when-cross-origin always;
|
||||
add_header Strict-Transport-Security "max-age=15552000" always;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
'''.replace('PORT',port)
|
||||
folder=Path('/var/lib/dunerealms-maintenance/git-embed-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'))
|
||||
folder.mkdir(mode=0o700)
|
||||
backup=folder/'dunerealms.com.conf';shutil.copy2(p,backup)
|
||||
p.write_text(s.replace(' location / {',block+' location / {',1))
|
||||
try:
|
||||
subprocess.run(['nginx','-t'],check=True,capture_output=True)
|
||||
subprocess.run(['nginx','-s','reload'],check=True,capture_output=True)
|
||||
except Exception:
|
||||
shutil.copy2(backup,p);subprocess.run(['nginx','-t'],check=True,capture_output=True);subprocess.run(['nginx','-s','reload'],check=True,capture_output=True)
|
||||
raise
|
||||
print('Installed DuneGit CP embedding policy; rollback:',backup)
|
||||
12
website/tests/cp-v2-workspace-chrome.test.mjs
Normal file
12
website/tests/cp-v2-workspace-chrome.test.mjs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {readFileSync} from 'node:fs';import {runInNewContext} from 'node:vm';
|
||||
test('all native workspaces put reload below content and hide routine status after load',async()=>{
|
||||
class Node{constructor(tag,text,cls){this.tag=tag;this.textContent=text;this.className=cls;this.children=[];this.style={};this.contentWindow={postMessage(){}};}append(...nodes){this.children.push(...nodes);}replaceChildren(...nodes){this.children=nodes;}setAttribute(){}remove(){}}
|
||||
const host=new Node('div'),window={addEventListener(){},removeEventListener(){}},el=(...args)=>new Node(...args);
|
||||
let source=readFileSync(new URL('../control-panel/public/cp-v2/cp-v2-native-services.mjs',import.meta.url),'utf8').replace(/^import[^\n]*\n/gm,'').replaceAll('export ','');
|
||||
const mount=runInNewContext(source+';mountNativeService',{canSubmitDevRequest:()=>false,createCPV2Page:({tabs})=>{const root=new Node('section');root.append(tabs[0].content);return {root};},el,window,location:{origin:'https://cp.dunerealms.com'},URL,AbortController,setTimeout,clearTimeout});
|
||||
const dispose=mount(host,'shared-inbox',{fetcher:async()=>({ok:true,json:async()=>({authenticated:true,user:{permissions:[]}})})});
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
const workspace=host.children[0].children[0];assert.equal(workspace.children.length,3);const [status,frameBox,tools]=workspace.children;assert.equal(frameBox.className,'cp-v2-native-frame');assert.equal(tools.children[0].textContent,'Reload workspace');assert.equal(status.hidden,false);
|
||||
frameBox.children[0].onload();assert.equal(status.hidden,true);assert.doesNotMatch(status.textContent,/Native workspace loaded|role checks remain authoritative/);
|
||||
tools.children[0].onclick();assert.equal(status.hidden,false);await new Promise(resolve=>setImmediate(resolve));dispose();
|
||||
});
|
||||
22
website/tests/forgejo-embed-sso.test.mjs
Normal file
22
website/tests/forgejo-embed-sso.test.mjs
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import test from 'node:test';import assert from 'node:assert/strict';import {createServer} from 'node:http';
|
||||
import {createForgejoProxy} from '../node/forgejo-proxy.mjs';
|
||||
import {createApplication} from '../node/server.mjs';
|
||||
const listen=s=>new Promise(r=>s.listen(0,'127.0.0.1',r));const close=s=>new Promise(r=>s.close(r));
|
||||
test('Forgejo proxy leaves central SSO routes to the application and injects only verified identities',async()=>{
|
||||
const upstream=createServer((req,res)=>res.end(JSON.stringify({identity:req.headers['x-dune-test-user'],auth:req.headers.authorization})));await listen(upstream);
|
||||
let lookups=0;const proxy=createForgejoProxy({FORGEJO_URL:'http://127.0.0.1:'+upstream.address().port,FORGEJO_AUTH_HEADER:'X-Dune-Test-User'},async()=>{lookups++;return 'verified_dev';});
|
||||
const server=createServer((req,res)=>{if(!proxy(req,res)){res.statusCode=404;res.end('central route');}});await listen(server);
|
||||
try{const root='http://127.0.0.1:'+server.address().port;
|
||||
assert.equal((await fetch(root+'/git/sso/start')).status,404);assert.equal(lookups,0);
|
||||
const page=await (await fetch(root+'/git/dev/MC',{headers:{'X-Dune-Test-User':'forged_owner'}})).json();assert.equal(page.identity,'verified_dev');assert.equal(lookups,1);
|
||||
const cli=await (await fetch(root+'/git/dev/MC.git/info/refs',{headers:{Authorization:'Basic existing','X-Dune-Test-User':'forged_owner'}})).json();assert.equal(cli.identity,undefined);assert.equal(cli.auth,'Basic existing');assert.equal(lookups,1);
|
||||
}finally{await close(server);await close(upstream);}
|
||||
});
|
||||
test('central application mounts existing Git SSO before fallback content and keeps sign-in state private',async()=>{
|
||||
const writes=[];const db={prepare(sql){return {bind(...args){return {async run(){writes.push({sql,args});return {meta:{changes:1}};},async first(){return null;},async all(){return {results:[]}}}}}}};
|
||||
const app=createApplication(db,{PUBLIC_ORIGIN:'https://www.dunerealms.com',CP_ORIGIN:'https://cp.dunerealms.com'});
|
||||
const response=await app(new Request('https://www.dunerealms.com/git/sso/start?return_to=%2Fgit%2Fdev%2FMC%2Factions'));
|
||||
assert.equal(response.status,302);const next=new URL(response.headers.get('location'));assert.equal(next.origin,'https://cp.dunerealms.com');assert.equal(next.pathname,'/sso/authorize');assert.equal(next.searchParams.get('client'),'git');assert.match(next.searchParams.get('state'),/^[A-Za-z0-9_-]{43}$/);
|
||||
assert.match(response.headers.get('set-cookie'),/Secure; HttpOnly; SameSite=Lax/);assert.match(response.headers.get('content-security-policy'),/frame-ancestors 'self' https:\/\/cp.dunerealms.com/);assert.equal(writes.length,2);assert.equal(writes[1].args[1],'/git/dev/MC/actions');
|
||||
const guest=await app(new Request('https://www.dunerealms.com/api/git/me'));assert.equal(guest.status,401);
|
||||
});
|
||||
|
|
@ -3,5 +3,5 @@ const listen=s=>new Promise(r=>s.listen(0,'127.0.0.1',r));const close=s=>new Pro
|
|||
test('Forgejo subpath streams git bodies, preserves auth, strips website identity and cookies',async()=>{
|
||||
const upstream=createServer((req,res)=>{let bytes=0;req.on('data',c=>bytes+=c.length);req.on('end',()=>{res.setHeader('Set-Cookie',['forgejo_session=test; Path=/git/; Secure']);res.end(JSON.stringify({path:req.url,auth:req.headers.authorization,cookie:req.headers.cookie,forged:req.headers['x-webauth-user'],bytes}));});});await listen(upstream);
|
||||
const proxy=createForgejoProxy({FORGEJO_URL:'http://127.0.0.1:'+upstream.address().port,PUBLIC_ORIGIN:'https://dunerealms.com'});const server=createServer((req,res)=>{if(!proxy(req,res)){res.statusCode=404;res.end();}});await listen(server);
|
||||
try{const base='http://127.0.0.1:'+server.address().port;const redirected=await fetch(base+'/git',{redirect:'manual'});assert.equal(redirected.status,308);assert.equal(redirected.headers.get('location'),'/git/');const r=await fetch(base+'/git/unimatrix/MC.git/git-receive-pack',{method:'POST',headers:{Authorization:'Basic test',Cookie:'__Host-dune_session=private; forgejo_session=abc','X-Webauth-User':'admin'},body:Buffer.alloc(90000)});const data=await r.json();assert.equal(data.path,'/unimatrix/MC.git/git-receive-pack');assert.equal(data.auth,'Basic test');assert.ok(!data.cookie.includes('private'));assert.equal(data.forged,undefined);assert.equal(data.bytes,90000);assert.match(r.headers.get('set-cookie'),/Path=\/git\//);}finally{await close(server);await close(upstream);}
|
||||
try{const base='http://127.0.0.1:'+server.address().port;const redirected=await fetch(base+'/git',{redirect:'manual'});assert.equal(redirected.status,308);assert.equal(redirected.headers.get('location'),'/git/');const r=await fetch(base+'/git/unimatrix/MC.git/git-receive-pack',{method:'POST',headers:{Authorization:'Basic test',Cookie:'__Host-dune_session=private; __Host-dune_git_session=private_git; forgejo_session=abc','X-Webauth-User':'admin'},body:Buffer.alloc(90000)});const data=await r.json();assert.equal(data.path,'/unimatrix/MC.git/git-receive-pack');assert.equal(data.auth,'Basic test');assert.ok(!data.cookie.includes('private'));assert.equal(data.forged,undefined);assert.equal(data.bytes,90000);assert.match(r.headers.get('set-cookie'),/Path=\/git\//);}finally{await close(server);await close(upstream);}
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff