@funfab/cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # FunFab CLI
2
+ Manage your FunFab games from a terminal, or let an agent
3
+ do it for you with a token.
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ ## Install
6
+ Needs Node.js 22 or newer.
7
+
8
+ ```sh
9
+ npx @funfab/cli@0.1.0 --help
10
+ npm install --global --save-exact @funfab/cli@0.1.0
11
+ ```
12
+
13
+ ## Sign in
14
+ ```sh
15
+ funfab login
16
+ ```
17
+ Your browser opens. Check that the code matches your
18
+ terminal, then confirm.
19
+
20
+ ## Check and change a game
21
+ ```sh
22
+ funfab game list
23
+ funfab game status emote-defense
24
+ funfab game stop emote-defense --reason "Balancing pass"
25
+ ```
26
+
27
+ Changes ask you in the terminal first. Add --yes to skip
28
+ the question. High-stakes changes, like creating an agent
29
+ token or turning on FunFab sign-in for a game, also ask you
30
+ to confirm it's you in your browser, once an hour.
31
+
32
+ ## Let an agent work for you
33
+ Coming soon.
34
+ 1. Create a token that allows only what the agent needs:
35
+ funfab token create emote-defense --name "Balancing agent" --allow stop-start
36
+ 2. Give the agent the file the command printed:
37
+ export FUNFAB_TOKEN_FILE=~/.config/funfab/tokens/preview/…
38
+ 3. The agent runs funfab commands. It can do only what the
39
+ token allows, and every change is logged and sent to
40
+ the game's owner.
41
+
42
+ Stop it at any time:
43
+ ```sh
44
+ funfab token revoke emote-defense "Balancing agent"
45
+ ```
46
+
47
+ An agent can't use your own sign-in. Changes run without a
48
+ terminal are refused, even with --yes.
49
+
50
+ ## For scripts
51
+ Add --json to any command. Exit codes: 0 done, 1 failed,
52
+ 2 wrong command or setting, 3 needs a person,
53
+ 4 and 5 pauses during submit.
54
+
55
+ ## Versions
56
+ This is a trial (0.x). Pin an exact version. The previous
57
+ version keeps working for 90 days after a new one.
58
+
59
+ ## Help
60
+ ```sh
61
+ funfab --help
62
+ funfab game stop --help
63
+ ```
@@ -0,0 +1,96 @@
1
+ import {createInterface} from 'node:readline/promises'
2
+ import {setTimeout as delay} from 'node:timers/promises'
3
+
4
+ export const terminalRequired=Object.freeze({error:'terminal_required',nextAction:{kind:'command',command:'funfab token create'}})
5
+ export const terminalMessage='This change needs a person at a terminal. Run the command yourself in a terminal.'
6
+ const unavailable=()=>{throw Error('account_unavailable')}
7
+
8
+ export function createApprovals({call,output,openBrowser,asJson=false,yes=false,tokenAdvice,input=process.stdin,out=process.stdout,now=Date.now,sleep=delay}) {
9
+ const terminal=Boolean(input.isTTY&&out.isTTY)
10
+ const emit=(value,message)=>output({...value,...(!asJson?{message}:{})})
11
+ const next=url=>({kind:'open_url',url})
12
+ function requireTerminal() {
13
+ if(!terminal||(asJson&&!yes))throw Object.assign(Error('terminal_required'),{...terminalRequired,display:asJson?undefined:terminalMessage+(tokenAdvice?'\n'+tokenAdvice:''),exit:3})
14
+ }
15
+ async function question(prompt,gameId) {
16
+ requireTerminal()
17
+ if(asJson&&gameId)throw Object.assign(Error('terminal_required'),{...terminalRequired,exit:3})
18
+ if(yes&&!gameId)return true
19
+ const rl=createInterface({input,output:out,crlfDelay:Infinity})
20
+ try {
21
+ if(!yes&&(await rl.question(prompt+' '))!=='y') {emit({status:'cancelled'},'Nothing changed.');return false}
22
+ if(gameId&&(await rl.question(`Type ${gameId} to confirm: `))!==gameId) {emit({status:'cancelled'},`That didn't match ${gameId}. Nothing changed.`);return false}
23
+ return true
24
+ } catch(error) {if(error.name!=='AbortError')throw error;emit({status:'cancelled'},'Nothing changed.');return false}
25
+ finally {rl.close()}
26
+ }
27
+ async function wait(ticket,pause,{activation=false,opened=false,signIn=false,signal}={}) {
28
+ const {confirmationUrl:url,requestId,code,interval=5,expiresAt}=pause
29
+ let target
30
+ try {target=new URL(url)} catch {return unavailable()}
31
+ if(!(target.protocol==='https:'||(target.protocol==='http:'&&['127.0.0.1','localhost','[::1]'].includes(target.hostname))))return unavailable()
32
+ if(!/^[A-Za-z0-9_-]{43}$/.test(requestId??'')||!/^[A-Z0-9]{4}$/.test(code??'')||!Number.isInteger(interval)||interval<5||!Number.isFinite(Date.parse(expiresAt)))return unavailable()
33
+ const safe={status:activation?'activation_needed':'sudo_needed',confirmationUrl:url,requestId,code,interval,expiresAt,nextAction:next(url)}
34
+ if(asJson||!terminal) {output(safe);process.exitCode=3;return false}
35
+ const browserOpened=opened||await openBrowser(url)
36
+ emit(safe,browserOpened?`Opening your browser${signIn?' to sign in':''}. Check that the code matches: ${code}`:`Open this address in your browser. Check that the code matches: ${code}`)
37
+ if(!browserOpened)emit(safe,url)
38
+ emit({status:safe.status},'Waiting for you to confirm… (Ctrl-C to stop)')
39
+ const controller=new AbortController(),cancel=()=>controller.abort()
40
+ process.once('SIGINT',cancel)
41
+ const combined=signal?AbortSignal.any([signal,controller.signal]):controller.signal
42
+ const localDeadline=now()+600000,deadline=Math.min(localDeadline,Date.parse(expiresAt));let seconds=interval,expired=false
43
+ try {
44
+ while(now()<deadline&&!combined.aborted) {
45
+ await sleep(Math.min(seconds*1000,Math.max(0,deadline-now())),undefined,{signal:combined})
46
+ if(now()>=deadline||combined.aborted)break
47
+ let state
48
+ try {state=await call('confirmation-status',{requestId},ticket,AbortSignal.any([combined,AbortSignal.timeout(Math.max(1,deadline-now()))]))}
49
+ catch(error) {
50
+ if(error.message==='slow_down'){seconds+=5;continue}
51
+ if(['TypeError','TimeoutError'].includes(error.name)){seconds*=2;continue}
52
+ if(error.message==='authorization_required')error.noSignIn=true
53
+ throw error
54
+ }
55
+ if(combined.aborted||now()>=deadline)break
56
+ if(!state||!['pending','confirmed','cancelled','expired'].includes(state.status)||state.code!==code||!Number.isInteger(state.interval??5)||(state.interval??5)<5||!Number.isFinite(Date.parse(state.expiresAt)))return unavailable()
57
+ if(state.status==='confirmed') {emit({status:'confirmed'},activation?'Confirmed.':"Confirmed. High-stakes commands won't ask again for an hour.");return true}
58
+ if(state.status==='cancelled') {emit({status:'cancelled'},'You chose "No, this isn\'t me" in your browser. Nothing changed.');process.exitCode=1;return false}
59
+ if(state.status==='expired'){expired=true;break}
60
+ seconds=Math.max(seconds,state.interval??5)
61
+ }
62
+ } catch(error) {if(!combined.aborted)throw error}
63
+ finally {process.removeListener('SIGINT',cancel)}
64
+ if(combined.aborted) {emit({status:'cancelled',nextAction:{kind:'command',command:'funfab '+process.argv.slice(2).map(arg=>"'"+arg.replaceAll("'", "'\\''")+"'").join(' ')}},'Stopped waiting. Nothing changed. The browser request expires on its own.');process.exitCode=3;return false}
65
+ if(!expired&&localDeadline<Date.parse(expiresAt)&&now()>=localDeadline) {emit(safe,`Check that the code matches: ${code}\n${url}`);process.exitCode=3;return false}
66
+ emit({error:'confirmation_expired',nextAction:{kind:'command',command:'funfab '+process.argv.slice(2).map(arg=>"'"+arg.replaceAll("'", "'\\''")+"'").join(' ')}},"You didn't confirm in your browser in time. Nothing changed. Run the command again to try again.")
67
+ process.exitCode=1;return false
68
+ }
69
+ async function write(path,body,saved,{prompt,destructive,needs}={}) {
70
+ requireTerminal()
71
+ if(!await question(prompt,destructive))return null
72
+ const approvedIn=yes?'yes':'terminal',input={...body,approvedIn}
73
+ let result=await call(path,input,saved.ticket)
74
+ if(result.status==='activation_needed') {
75
+ if(!await wait(saved.ticket,result,{activation:true}))return null
76
+ result=await call(path,input,saved.ticket)
77
+ }
78
+ if(result.status==='sudo_needed') {
79
+ if(needs&&!asJson)emit({status:'sudo_needed'},needs)
80
+ if(!await wait(saved.ticket,result))return null
81
+ // The pause proves that no write ran. This is the one first execution, not a
82
+ // transport retry. A thrown/uncertain sent write is never retried here.
83
+ result=await call(path,input,saved.ticket)
84
+ if(['sudo_needed','activation_needed'].includes(result.status)) {emit(result,result.confirmationUrl);process.exitCode=3;return null}
85
+ }
86
+ return result
87
+ }
88
+ return {requireTerminal,question,wait,write,approvedIn:yes?'yes':'terminal'}
89
+ }
90
+
91
+ export function alignedRows(headers,rows) {
92
+ if(!rows.length)return ''
93
+ const values=(headers?[headers,...rows]:rows).map(row=>row.map(value=>String(value??'')))
94
+ const widths=(headers??rows[0]).map((_,i)=>Math.max(...values.map(row=>row[i].length)))
95
+ return values.map(row=>row.map((cell,i)=>i<row.length-1?cell.padEnd(widths[i]+2):cell).join('')).join('\n')
96
+ }
@@ -0,0 +1,43 @@
1
+ import {createHash, randomBytes, timingSafeEqual} from 'node:crypto'
2
+
3
+ export const CALLBACKS = Object.freeze([
4
+ 'http://127.0.0.1:54391/callback',
5
+ 'http://127.0.0.1:54392/callback',
6
+ ])
7
+ const lifetime = 10 * 60 * 1000
8
+ const nonce = () => randomBytes(32).toString('base64url')
9
+
10
+ // Attempt state stays in the process: a callback is accepted once, only while
11
+ // the attempt is live, whether it arrived on loopback or was pasted by hand.
12
+ export function createAttempt({redirectUri, now=Date.now} = {}) {
13
+ if (!CALLBACKS.includes(redirectUri)) throw new Error('invalid_redirect')
14
+ const verifier=nonce(), state=nonce(), expiresAt=now()+lifetime
15
+ let used=false
16
+ return Object.freeze({
17
+ redirectUri, verifier, state, expiresAt,
18
+ challenge:createHash('sha256').update(verifier).digest('base64url'),
19
+ accept(value) {
20
+ if (used || now() >= expiresAt || typeof value !== 'string' || value.length > 8192) throw new Error('invalid_callback')
21
+ let url
22
+ try { url=new URL(value) } catch { throw new Error('invalid_callback') }
23
+ const expected=new URL(redirectUri)
24
+ if (url.origin!==expected.origin || url.pathname!==expected.pathname || url.hash || url.username || url.password ||
25
+ [...url.searchParams.keys()].some(k=>!['code','state'].includes(k)) ||
26
+ url.searchParams.getAll('code').length!==1 || url.searchParams.getAll('state').length!==1) throw new Error('invalid_callback')
27
+ const candidate=url.searchParams.get('state'), code=url.searchParams.get('code')
28
+ const a=Buffer.from(candidate), b=Buffer.from(state)
29
+ if (a.length!==b.length || !timingSafeEqual(a,b) || !code || code.length>4096) throw new Error('invalid_callback')
30
+ used=true
31
+ return code
32
+ },
33
+ })
34
+ }
35
+
36
+ export function authorizationURL({authOrigin,clientId,attempt}) {
37
+ const origin=new URL(authOrigin)
38
+ if (origin.origin!==authOrigin || !['https:','http:'].includes(origin.protocol) ||
39
+ (origin.protocol==='http:' && !['localhost','127.0.0.1','[::1]'].includes(origin.hostname))) throw new Error('invalid_configuration')
40
+ const url=new URL('/auth/v1/oauth/authorize',origin)
41
+ url.search=new URLSearchParams({client_id:clientId,redirect_uri:attempt.redirectUri,response_type:'code',scope:'email offline_access',state:attempt.state,code_challenge_method:'S256',code_challenge:attempt.challenge}).toString()
42
+ return url.href
43
+ }
package/cli/funfab.mjs ADDED
@@ -0,0 +1,420 @@
1
+ #!/usr/bin/env node
2
+ import {submitHelp} from './submit-help.mjs'
3
+ import {createServer} from 'node:http'
4
+ import {spawn} from 'node:child_process'
5
+ import {createInterface} from 'node:readline/promises'
6
+ import {Writable} from 'node:stream'
7
+ import {mkdir,readFile,open,rename,unlink,chmod,lstat} from 'node:fs/promises'
8
+ import {randomBytes,randomUUID} from 'node:crypto'
9
+ import {homedir} from 'node:os'
10
+ import {join,dirname,resolve} from 'node:path'
11
+ import {submitInput,submitCopy} from '../validation/submit.mjs'
12
+ import {probeSubmitGate} from './submit-probe.mjs'
13
+ import {CALLBACKS,createAttempt,authorizationURL} from './attempt.mjs'
14
+ import {tokenCommands,tokenIntent,runToken} from './tokens.mjs'
15
+ import {createApprovals,terminalMessage,alignedRows} from './approvals.mjs'
16
+
17
+ if(Number(process.versions.node.split('.')[0])<22) {
18
+ console.error('FunFab needs Node.js 22 or newer. Upgrade Node.js, then run funfab again.')
19
+ process.exit(2)
20
+ }
21
+ const argv=process.argv.slice(2), asJson=argv.includes('--json'), noBrowser=argv.includes('--no-browser'), yes=argv.includes('--yes')
22
+ const keyIndex=argv.indexOf('--key-file'), keyFile=keyIndex<0?undefined:argv[keyIndex+1]
23
+ const args=argv.filter((x,i)=>!['--json','--no-browser','--help','--version','--yes'].includes(x)&&(keyIndex<0||(i!==keyIndex&&i!==keyIndex+1)))
24
+ const output=value=>console.log(asJson?JSON.stringify(value):value.message??JSON.stringify(value))
25
+ const commandAction=command=>({kind:'command',command})
26
+ const person=instruction=>({kind:'person',instruction})
27
+ const operator=instruction=>({kind:'operator',instruction})
28
+ const edit=(field,value,instruction)=>({kind:'edit_field',field,...(value===undefined?{}:{value}),instruction})
29
+ const problem=(error,message,nextAction,exit=1)=>Object.assign(Error(error),{display:message,nextAction,exit})
30
+ const fail=(error,message,nextAction,code=1,reason)=>{output({error,...(reason?{reason}:{}),...(asJson&&error==='terminal_required'?{}:{message}),nextAction});process.exitCode=code}
31
+ const root=join(process.env.XDG_CONFIG_HOME||homedir(),'.funfab'), file=join(root,'cli.json')
32
+ const apiOrigin=process.env.FUNFAB_CLI_API_URL??'https://api-preview.funfab.io'
33
+ const commands=[
34
+ ...tokenCommands.map(c=>({...c,run:tokenCommand})),
35
+ {command:'whoami',arguments:'',description:'Show your account, confirmation and session limits',example:'funfab whoami',next:'Run funfab login to start a new confirmation if still waiting.',run:whoami,count:1},
36
+ {command:'logout',arguments:'',description:'Sign out on this computer and end this CLI session',example:'funfab logout',run:logout,count:1},
37
+ {command:'login',arguments:'',description:'Sign in to the FunFab Developer CLI',example:'funfab login',next:'Confirm your sign-in in the browser.',run:login,count:1},
38
+ ...['list','status','check','requests'].map(read=>({command:`game ${read}`,arguments:read==='list'?'':read==='requests'?'GAME [--before REQUEST] | GAME --answer REQUEST --approve|--decline --reason TEXT [--expires TIME|never]':'GAME',description:{list:'List games you can inspect',status:'Show game status and real access',check:'Show recorded setup steps',requests:'Show pending requests, or answer one; decisions stay in history; remove an allow-list entry separately'}[read],example:`funfab game ${read}${read==='list'?'':' my-game'}`,run:gameRead,count:read==='list'?2:3})),
39
+ ...['set-status','stop','start','allow','block'].map(action=>({command:`game ${action}`,arguments:`GAME${action==='set-status'?' internal|playtest':['allow','block'].includes(action)?' ACCOUNT':''} --reason TEXT${['allow','block'].includes(action)?' [--expires TIME|never] [--remove]':''}`,description:{'set-status':'Move to Internal, or to Playtest on Production; listing stays a separate fact',stop:'Stop game; rooms already running end within 5 minutes',start:'Start game; ended rooms do not come back',allow:'Add to the allow list; daily room limits stay unchanged; undo with --remove',block:'Add to the block list; undo with --remove; removing creates no allow-list entry'}[action],example:`funfab game ${action} my-game${action==='set-status'?' internal':['allow','block'].includes(action)?' ACCOUNT':''} --reason 'Reason'`,next:'Answer the question in your terminal.',run:gameWrite})),
40
+ ...['show','hide'].map(action=>({command:`title ${action}`,arguments:'TITLE --reason TEXT',description:action==='hide'?'Hide title from the list; launching through the game is unchanged; undo with show':'Show title with its stored declaration; undo with hide',example:`funfab title ${action} my-title --reason 'Reason'`,next:'Answer the question in your terminal.',run:gameWrite})),
41
+ {command:'game init' ,arguments:'FILE',description:'Write a new submission file offline, without signing in',example:'funfab game init submission.json',next:'Fill in the fields, then run funfab game submit FILE.',run:init,count:3},
42
+ {command:'game submit',arguments:'FILE',description:'Submit a caller-owned stream game on Preview',example:'funfab game submit submission.json',next:'Connect the shown address, install the sign-in key, then confirm the checks in the same file.',run:submit,count:3},
43
+ {command:'game admit',arguments:'GAME on|off GATE_EVIDENCE CLEANUP_EVIDENCE',description:'Turn FunFab sign-in on or off for a game',example:"funfab game admit my-game on 'Gate tested' 'No player data kept'",next:'Answer the question in your terminal.',run:admit,count:6},
44
+ {command:'help',arguments:'',description:'Show every command and option',example:'funfab --help'}
45
+ ]
46
+ const command=commands.find(c=>args.slice(0,c.command.split(' ').length).join(' ')===c.command)
47
+ let tokenUsage=false
48
+ if(command?.run===tokenCommand) {try {tokenIntent(args,{asJson,terminal:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});tokenUsage=true} catch {}}
49
+ let writeUsage=false
50
+ if(command?.run===gameWrite||command?.command==='game requests'&&args.includes('--answer')) {
51
+ try {writeIntent();writeUsage=true} catch {}
52
+ }
53
+ const isWrite=command?.run===gameWrite||command?.command==='game requests'&&args.includes('--answer')
54
+ const help={commands:commands.map(({run,count,...entry})=>entry),flags:{'--help':'Show help for this command','--version':'Show the version','--json':'Print JSON','--yes':'Skip the question from a terminal','--no-browser':'Print the link instead of opening a browser','--key-file PATH':'Write the sign-in key to a new private file'},settings:{FUNFAB_CLI_API_URL:'Accounts API HTTPS origin; default https://api-preview.funfab.io'},exitCodes:{0:'Done',1:'Failed',2:'Check the command or settings',3:'Needs a person or browser confirmation',4:'Connect the game address, then run the same command again',5:'Install the game sign-in key, then run the same command again'}}
55
+ const fieldGuide={
56
+ game:'Registration details: fill in the game ID, name, charging, data stores and host target before submitting.',
57
+ title:'Catalog identity and launchPath: fill in before submitting.',
58
+ contentDeclaration:'Inside title: answer every content question and name host controls before submitting.',
59
+ deployment:'Set build to the inspected deployment commit before submitting; update it when the build changes.',
60
+ addressReady:'Start false; set true after connecting the shown address record.',
61
+ credentialInstalled:'Start false; set true after installing the delivered sign-in key privately.',
62
+ checks:'Add the evidence and confirmedChecks at the final step.'
63
+ }
64
+ const informational=!argv.length||argv.includes('--help')||args[0]==='help'||argv.includes('--version')
65
+ if(informational) {
66
+ if(argv.includes('--version')) {const {version}=JSON.parse(await readFile(new URL('../package.json',import.meta.url),'utf8'));output({version,message:version})}
67
+ else {
68
+ const entries=command&&command.command!=='help'?[help.commands.find(c=>c.command===command.command)]:help.commands
69
+ const fields=command?.command==='game submit'?fieldGuide:undefined
70
+ output({...help,commands:entries,...(fields?{fieldGuide:fields,submitHelp}:{}),message:['FunFab Developer CLI',...entries.flatMap(c=>[` funfab ${c.command} ${c.arguments} — ${c.description}`,` Example: ${c.example}`,...(c.next?[` Next: ${c.next}`]:[])]),...(fields?Object.entries(fields).map(([k,v])=>` ${k}: ${v}`):[]),...(fields?[submitHelp]:[]),...Object.entries(help.flags).map(([k,v])=>` ${k}: ${v}`),...Object.entries(help.settings).map(([k,v])=>` ${k}: ${v}`),...Object.entries(help.exitCodes).map(([k,v])=>` Exit ${k}: ${v}`)].join('\n')})
71
+ if(!argv.length)process.exitCode=2
72
+ }
73
+ }
74
+ let usageOK=true
75
+ if(!informational&&(!command?.run||(command.run===tokenCommand?!tokenUsage:isWrite?!writeUsage:!(args.length===command.count||(command.command==='game requests'&&args.length===5&&args[3]==='--before'))||(command.command==='game admit'&&!['on','off'].includes(args[3]))||args.some((x,i)=>x.startsWith('--')&&!(command.command==='game requests'&&i===3&&x==='--before')))||(keyIndex>=0&&(!keyFile||keyFile.startsWith('--')||command.command!=='game submit'||argv.lastIndexOf('--key-file')!==keyIndex)))) {
76
+ usageOK=false;fail('command_invalid','Check the command and its arguments. Run funfab --help for examples.',commandAction('funfab --help'),2)
77
+ }
78
+ let api
79
+ if(!informational&&usageOK&&command.command!=='game init') try {const u=new URL(apiOrigin);if(u.origin!==apiOrigin||!(u.protocol==='https:'||(u.protocol==='http:'&&['127.0.0.1','localhost','[::1]'].includes(u.hostname))))throw Error();api=u.origin} catch {if(command.command!=='logout')fail('configuration_invalid','The API address is invalid. Set FUNFAB_CLI_API_URL to an HTTPS origin, or remove it to use Preview.',person('Set FUNFAB_CLI_API_URL to an HTTPS origin, or remove the override.'),2)}
80
+ const save=async value=>{
81
+ try {
82
+ await mkdir(root,{recursive:true,mode:0o700}); await chmod(root,0o700)
83
+ const temp=join(root,`.cli-${randomBytes(16).toString('hex')}`)
84
+ let handle
85
+ try {
86
+ handle=await open(temp,'wx',0o600)
87
+ await handle.writeFile(JSON.stringify(value)); await handle.close(); handle=null
88
+ await rename(temp,file)
89
+ } finally {if(handle) await handle.close(); await unlink(temp).catch(()=>{})}
90
+ } catch {throw problem('cli_state_unwritable','The saved sign-in could not be written. Make the CLI state folder writable, then run funfab login.',person('Make the CLI state folder writable, then run funfab login.'))}
91
+ }
92
+ const load=async()=>{
93
+ let raw
94
+ try {raw=await readFile(file,'utf8')} catch(error) {
95
+ if(error.code==='ENOENT')throw problem('authorization_required',"You're not signed in. Run funfab login.",commandAction('funfab login'))
96
+ throw problem('cli_state_unreadable','The saved sign-in cannot be read. Check the CLI state file permissions, then run funfab login.',person('Check the CLI state file permissions, then run funfab login.'))
97
+ }
98
+ try {const saved=JSON.parse(raw);if(!saved||typeof saved.ticket!=='string'||!saved.ticket)throw Error();return saved} catch {throw problem('cli_state_corrupt','The saved sign-in is damaged. Run funfab login to replace it.',commandAction('funfab login'))}
99
+ }
100
+ async function call(path,body,ticket,signal) {
101
+ const response=await fetch(`${api}/api/cli/${path}`,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json'}),...(ticket?{Authorization:`Bearer ${ticket}`}:{})},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:signal?AbortSignal.any([signal,AbortSignal.timeout(10000)]):AbortSignal.timeout(path==='submit'?180000:10000)})
102
+ const data=await response.json();if(!response.ok) throw Object.assign(Error(data.error??'account_unavailable'),(path.startsWith('game/')||path.startsWith('token/')||path==='confirm-request')&&['game_request_invalid','game_request_conflict'].includes(data.error)&&['input_invalid','cursor_invalid','expiry_elapsed','consumed','answered','invalidated'].includes(data.reason)?{reason:data.reason}:{});return data
103
+ }
104
+ const terminal=Boolean(process.stdin.isTTY&&process.stdout.isTTY&&!asJson)
105
+ const personWrite=isWrite||['game submit','game admit','token create','token revoke','token kill-switch'].includes(command?.command)
106
+ const tokenTick=args[0]==='game'?({'set-status':'status',stop:'stop-start',start:'stop-start',allow:'access',block:'access',requests:args.includes('--answer')?'access':null}[args[1]]):null
107
+ const tokenAdvice=tokenTick&&/^[a-z0-9]+(-[a-z0-9]+)*$/.test(args[2]??'')?`To let an agent or script do it, create a token: funfab token create ${args[2]} --name \"…\" --allow ${tokenTick}`:undefined
108
+ const approvals=createApprovals({call,output,tokenAdvice,openBrowser:async url=>!noBrowser&&await openBrowser(url),asJson,yes})
109
+ const interactiveBrowser=terminal&&!noBrowser
110
+ const browserCommand=process.platform==='darwin'?'open':process.platform==='win32'?null:'xdg-open'
111
+ function openBrowser(url) {
112
+ const command=browserCommand
113
+ try {
114
+ if(typeof url!=='string')return Promise.resolve(false)
115
+ const target=new URL(url)
116
+ if(target.protocol!=='https:'&&!(target.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(target.hostname)))return Promise.resolve(false)
117
+ } catch {return Promise.resolve(false)}
118
+ if(!command)return Promise.resolve(false)
119
+ return new Promise(resolve=>{
120
+ const child=spawn(command,[url],{stdio:'ignore',detached:true})
121
+ const finish=opened=>{clearTimeout(timer);resolve(opened)}
122
+ // A desktop launcher must not keep an approval-needed command running.
123
+ const timer=setTimeout(()=>finish(false),2000)
124
+ child.once('error',()=>finish(false));child.once('exit',code=>finish(code===0));child.unref()
125
+ })
126
+ }
127
+ async function browserStep(url,manual,opening,completed=()=>false,copy) {
128
+ if(interactiveBrowser&&browserCommand) {
129
+ if(opening)output({message:opening})
130
+ if(await openBrowser(url)||completed())return true
131
+ output({message:copy?copy.browserFailed:'The browser did not open automatically.'})
132
+ }
133
+ output(manual)
134
+ return false
135
+ }
136
+ async function confirmation(pause) {
137
+ const saved=await load()
138
+ return approvals.wait(saved.ticket,pause,{activation:true})
139
+ }
140
+ async function listen() {
141
+ for(const redirectUri of CALLBACKS) {
142
+ const server=createServer(), port=Number(new URL(redirectUri).port)
143
+ try { await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',()=>{server.removeListener('error',reject);resolve()})});return {server,redirectUri} } catch {server.close()}
144
+ }
145
+ throw Error('loopback_unavailable')
146
+ }
147
+ async function login() {
148
+ let previous
149
+ try {previous=await load()} catch {}
150
+ const {server,redirectUri}=await listen(), attempt=createAttempt({redirectUri})
151
+ let callbackResponse, readline, pasteCallback
152
+ try {
153
+ const config=await call('config'), url=authorizationURL({authOrigin:config.authOrigin,clientId:config.clientId,attempt})
154
+ const pending=new Promise((resolve,reject)=>{
155
+ const timer=setTimeout(()=>{readline?.close();reject(Error('attempt_expired'))},600000)
156
+ server.on('request',(req,res)=>{
157
+ try {const code=attempt.accept(`http://127.0.0.1:${server.address().port}${req.url}`);clearTimeout(timer);readline?.close();callbackResponse=res;resolve(code)}
158
+ catch {res.writeHead(400,{'Content-Type':'text/plain','Cache-Control':'no-store'});res.end('Invalid or expired sign-in request.')}
159
+ })
160
+ if(terminal) {
161
+ const silent=new Writable({write(_chunk,_encoding,done){done()}})
162
+ const rl=readline=createInterface({input:process.stdin,output:silent,terminal:true,crlfDelay:Infinity})
163
+ ;(async()=>{
164
+ while(!rl.closed) {
165
+ const value=await rl.question('')
166
+ if(!value.trim())continue
167
+ try {const code=attempt.accept(value.trim());clearTimeout(timer);resolve(code);rl.close();return}
168
+ catch {process.stderr.write('Invalid or expired callback. Paste the complete final address from this sign-in, or start funfab login again.\n')}
169
+ }
170
+ })().catch(()=>{})
171
+ }
172
+ pasteCallback=()=>{if(terminal&&!callbackResponse)process.stderr.write('If this is a remote machine, paste the final callback address: ')}
173
+ })
174
+ const opening=browserStep(url,{message:`Opening your browser to sign in. If it doesn't open, go to: ${url}`,status:'sign_in_needed',authorizationUrl:url,nextAction:{kind:'open_url',url}},undefined,()=>Boolean(callbackResponse)).then(opened=>{if(!opened)pasteCallback()})
175
+ const code=await pending
176
+ const exchange=await call('exchange',{code,verifier:attempt.verifier,redirectUri})
177
+ const confirmation=await call('activation',{},exchange.ticket)
178
+ await save({ticket:exchange.ticket})
179
+ // Retire only after a replacement is safely saved; an interrupted sign-in
180
+ // before exchange leaves the previous session working. Cleanup failure is
181
+ // reported, while the new saved sign-in remains recoverable.
182
+ if(previous)try {const ended=await call('logout',{},previous.ticket);if(ended.ended!==true)throw Error('account_unavailable')}catch(error){if(error.message!=='authorization_required')throw error}
183
+ if(callbackResponse){callbackResponse.writeHead(303,{Location:confirmation.confirmationUrl,'Cache-Control':'no-store','Referrer-Policy':'no-referrer'});callbackResponse.end()}
184
+ await opening
185
+ const confirmed=await approvals.wait(exchange.ticket,confirmation,{activation:true,opened:interactiveBrowser&&Boolean(callbackResponse),signIn:true})
186
+ if(confirmed){
187
+ const own=await call('whoami',{},exchange.ticket);output({status:'signed_in',...(!asJson?{message:`Signed in as ${own.displayName??own.email??'FunFab account'}.${command.command==='login'?'':' Continuing…'}`}:{})})}
188
+ return confirmed
189
+ } finally {if(callbackResponse&&!callbackResponse.writableEnded) {callbackResponse.writeHead(503,{'Cache-Control':'no-store','Content-Type':'text/plain'});callbackResponse.end('Sign-in could not be completed. Return to the terminal.')} readline?.close();server.close()}
190
+ }
191
+ async function whoami() {
192
+ const saved=await load(), result=await call('whoami',{},saved.ticket)
193
+ let remaining=result.inactivityTimeoutSeconds
194
+ const inactivity=[['hour',3600],['minute',60],['second',1]].flatMap(([unit,seconds])=>{const count=Math.floor(remaining/seconds);remaining%=seconds;return count?[`${count} ${unit}${count===1?'':'s'}`]:[]}).join(', ')
195
+ const expiry=new Date(result.expiresAt).toLocaleString(undefined,{dateStyle:'medium',timeStyle:'short'})
196
+ output({...result,message:`${result.displayName??'FunFab account'}\n${result.confirmed?'Confirmed':'Waiting for your confirmation. Run funfab login to start a new confirmation.'}\nSession expires: ${expiry}\nInactivity limit: ${inactivity}`,...(!result.confirmed?{nextAction:commandAction('funfab login')}:{})})
197
+ }
198
+ async function logout() {
199
+ let saved,exists=true,ended=false
200
+ try {saved=await load()} catch(error) {if(error.message==='authorization_required')exists=false}
201
+ if(saved)try {ended=(await call('logout',{},saved.ticket)).ended===true} catch {}
202
+ try {await unlink(file)} catch(error) {if(error.code!=='ENOENT')throw problem('cli_state_unwritable','The saved sign-in could not be removed. Make the CLI state folder writable, then run funfab logout.',person('Make the CLI state folder writable, then run funfab logout.'))}
203
+ output({ended,message:!exists?"You're not signed in":ended?'Signed out':"Signed out on this computer; the server session couldn't be confirmed as ended"})
204
+ }
205
+ function starter() {
206
+ return {requestId:randomUUID(),mode:'pass',game:{game_id:'',environment:'preview',hosting:'stream',name:'',per_play_cost:null,daily_room_quota:null,retains_account_data:null,store_ids:[]},title:{id:'',name:'',launchPath:'',contentDeclaration:{streamInput:null,hostControls:'',sexualContent:null,strongViolence:null,drugs:null,gambling:null,strongLanguage:null,realMoney:null,childDirected:null}},deployment:{build:''},addressReady:false,credentialInstalled:false}
207
+ }
208
+ async function init() {
209
+ let handle
210
+ try {
211
+ handle=await open(args[2],'wx')
212
+ await handle.writeFile(JSON.stringify(starter(),null,2)+'\n')
213
+ } catch(error) {
214
+ const exists=error.code==='EEXIST'
215
+ throw problem(exists?'game_init_exists':'game_init_unwritable',exists?'The submission file already exists. Choose a new FILE; existing files and links are never overwritten.':'The submission file could not be written. Check FILE and its folder permissions.',person(exists?'Choose a new FILE path.':'Choose a writable FILE path in an existing folder.'),2)
216
+ } finally {if(handle)await handle.close()}
217
+ output({file:args[2],message:`Created ${args[2]}. Fill in the fields, then run funfab game submit ${args[2]}.`,nextAction:edit('game.name',undefined,'Fill in the game name, then the remaining submission fields.')})
218
+ }
219
+ async function submit() {
220
+ let copy=submitCopy('Your game'), body, keyPath, keyFolder
221
+ try {
222
+ let raw
223
+ try {raw=await readFile(args[2],'utf8')} catch(error) {throw problem('game_submit_input_invalid',error.code==='ENOENT'?'The submission file was not found. Check FILE and run the same command again.':'The submission file cannot be read. Check its permissions and run the same command again.',person('Check the submission file path and permissions.'),2)}
224
+ try {body=JSON.parse(raw)} catch {throw problem('game_submit_input_invalid','The submission file is not valid JSON. Fix its JSON syntax, then run the same command again.',person('Fix the JSON syntax in the submission file.'),2)}
225
+ const {target}=submitInput(body), saved=await load()
226
+ copy=submitCopy(target.name)
227
+ const toFile=!process.stdout.isTTY||asJson||keyFile!==undefined
228
+ const registered=saved.submission?.requestId===body.requestId&&typeof saved.submission.clientId==='string'&&saved.submission.clientId.length>0
229
+ if(toFile) {
230
+ keyPath=resolve(keyFile??join(root,'keys',`${target.game_id}-${body.requestId}.key`));keyFolder=dirname(keyPath)
231
+ if([file,args[2]].some(path=>resolve(path)===keyPath))throw problem('key_file_invalid','Choose a new key file separate from the submission and saved sign-in.',person('Choose a different --key-file path.'),2)
232
+ if(body.addressReady&&body.game.dnsTarget) {
233
+ try {
234
+ // A saved registration can resume with its already delivered key file.
235
+ // For a new registration, reject every existing entry, including links.
236
+ if(!registered) {
237
+ let existing
238
+ try {existing=await lstat(keyPath)} catch(error) {if(error.code!=='ENOENT')throw error}
239
+ if(existing)throw problem('key_file_exists','The key file already exists. Choose a new --key-file path before submitting.',person('Choose a new --key-file path; existing files and links are never overwritten.'),2)
240
+ }
241
+ if(!keyFile) {await mkdir(keyFolder,{recursive:true,mode:0o700});const state=await lstat(keyFolder);if(!state.isDirectory()||state.isSymbolicLink()||(process.getuid&&state.uid!==process.getuid()))throw Error();await chmod(keyFolder,0o700)}
242
+ const probe=join(keyFolder,`.write-${randomBytes(16).toString('hex')}`), handle=await open(probe,'wx',0o600)
243
+ await handle.close();await unlink(probe)
244
+ } catch(error) {if(error.display)throw error;throw problem('key_file_unwritable','The key folder is not writable. Choose a writable private folder with --key-file before submitting.',person('Choose a writable private folder with --key-file.'),2)}
245
+ }
246
+ }
247
+ const emit=async result=>{
248
+ if(result.status==='activation_needed') {if(await confirmation(result))await submit();return}
249
+ if(result.clientId) {saved.submission={requestId:body.requestId,clientId:result.clientId};await save(saved).catch(()=>{})}
250
+ const {gameCredential,...safe}=result
251
+ let delivered
252
+ if(gameCredential) {
253
+ if(toFile) {
254
+ try {const handle=await open(keyPath,'wx',0o600);try {await handle.chmod(0o600);await handle.writeFile(gameCredential+'\n');await handle.sync()} finally {await handle.close()};delivered=keyPath}
255
+ catch {fail('game_submit_refused','The game was registered, but its sign-in key could not be saved. Ask an authorized operator to replace the key through the existing rotation.',operator('Replace the game sign-in key through the existing rotation.'));return}
256
+ } else console.log(gameCredential)
257
+ }
258
+ let message=safe.message,nextAction
259
+ if(result.status==='address_needed') {message=copy.address;nextAction=edit('addressReady',true,'Add the shown address record, set game.dnsTarget if needed, then run the same command.');if(!asJson&&safe.addressRecord)message+='\n'+safe.addressRecord}
260
+ if(result.status==='key_needed') {message=copy.key;nextAction=edit('credentialInstalled',true,'Install the key privately at the game host, then run the same command.');if(delivered)message+=` Key file: ${delivered}`}
261
+ if(result.status==='operator_needed')nextAction=operator('Inspect this registration before continuing.')
262
+ output({...safe,...(delivered?{keyFile:delivered}:{}),message,...(nextAction?{nextAction}:{})})
263
+ process.exitCode={complete:0,address_needed:4,key_needed:5,operator_needed:1}[result.status]??1
264
+ }
265
+ if(!await approvals.question(`Turn on FunFab sign-in for ${target.name}? [y/N]`))return
266
+ const reference=await call('submit',{...body,credentialInstalled:false,approvedIn:approvals.approvedIn},saved.ticket)
267
+ if(reference.status!=='key_needed'||reference.gameCredential||!body.credentialInstalled) {await emit(reference);return}
268
+ if(reference.clientId) {saved.submission={requestId:body.requestId,clientId:reference.clientId};await save(saved).catch(()=>{})}
269
+ if(body.credentialInstalled&&body.checks?.gate?.method==='anonymous_https') {
270
+ const config=await call('config')
271
+ body.checks.gate=await probeSubmitGate({target,title:body.title,deployment:body.deployment,clientId:saved.submission?.requestId===body.requestId?saved.submission.clientId:null,authorizationEndpoint:new URL('/auth/v1/oauth/authorize',config.authOrigin).href})
272
+ }
273
+ await emit(await call('submit',{...body,approvedIn:approvals.approvedIn},saved.ticket))
274
+ } catch(error) {
275
+ if(error.display||['authorization_required',...Object.keys(refusals)].includes(error.message))throw error
276
+ if(error.field) {fail('game_submit_input_invalid',`Check ${error.field}: expected ${error.expected}. Correct this field, then run the same command.`,edit(error.field,undefined,`Expected ${error.expected}.`),2);return}
277
+ if(['game_submit_input_invalid','game_target_unverified'].includes(error.message)) {fail('game_submit_input_invalid',copy.invalid,person('Check the submission fields and all content answers.'),2);return}
278
+ const checks=error.message==='game_submit_checks_required'
279
+ const missing=['confirmedChecks','retention.passed','retention.evidence','viewerDeletion.passed','viewerDeletion.evidence','accountsTokens.passed','accountsTokens.gateVersion','accountsTokens.code','accountsTokens.migrations','accountsTokens.removedWriters','hostSafety.schemaVersion','hostSafety.gameId','hostSafety.build','hostSafety.checkVersion','hostSafety.result','hostSafety.surfaces','gate.gameId','gate.host','gate.build','gate.result','gate.method','gate.attested','gate.evidence'].filter(path=>!path.split('.').reduce((value,k)=>value?.[k],body?.checks)).map(k=>'checks.'+k)
280
+ const message=error.reason?`${error.reason} Correct the gate check, then run the same command.`:checks?copy.checks+(missing.length?' Missing: '+missing.join(', ')+'.':''):copy.refused
281
+ fail(checks?'game_submit_checks_required':'game_submit_refused',message,checks?edit(error.field??'checks',undefined,error.reason??'Confirm the checks for the inspected build.'):person('Check your sign-in, staff access, ownership and Preview settings.'))
282
+ }
283
+ }
284
+ async function gameRead() {
285
+ if(args[1]==='requests'&&args.includes('--answer'))return gameWrite()
286
+ const read=args[1], saved=await load()
287
+ let result
288
+ try {result=await call(`game/${read}`,read==='list'?{}:{game:args[2],...(args[3]?{before:args[4]}:{})},saved.ticket)}
289
+ catch(error) {
290
+ const retry=`funfab game requests '${String(args[2]??'').replaceAll("'", "'\\''")}'`
291
+ if(error.message==='game_request_invalid')throw Object.assign(problem(error.message,error.reason==='cursor_invalid'?'That page of requests is no longer available. Run the command again without --before.':'Check the game name and command arguments.',error.reason==='cursor_invalid'?commandAction(retry):commandAction(`funfab game ${read} --help`),error.reason==='cursor_invalid'?1:2),{reason:error.reason})
292
+ if(error.message==='game_permission_denied')throw problem(error.message,'You do not have permission to read this game data.',person('Ask the game owner or an authorized staff member for access.'))
293
+ if(error.message==='game_not_found')throw problem(error.message,'The game was not found. Check its name in the game list.',commandAction('funfab game list'))
294
+ throw error
295
+ }
296
+ if(result.status==='activation_needed'){if(await confirmation(result))return gameRead();return}
297
+ const steps=read==='check'?result.steps.map(s=>({...s,nextAction:s.nextAction?(['cleanup','signups','admission'].includes(s.step)?operator:person)(s.nextAction):null})):undefined
298
+ const nextAction=read==='requests'&&result.next?commandAction(`funfab game requests ${result.game.gameId} --before ${result.next}`):read==='check'?steps.find(s=>s.nextAction)?.nextAction:null
299
+ const label=game=>`${game.name} — ${game.environment==='preview'?'Preview':'Production'}\n${game.displayStatus} · ${{hidden:'hidden',experimental:'listed',featured:'featured'}[game.listing]}\n${game.accessText}`
300
+ let message=read==='list'?`${result.environment==='preview'?'Preview':'Production'}\n${result.games.map(label).join('\n\n')||'No games.'}`:label(result.game??result)
301
+ if(!asJson&&read==='list')message=result.games.length?`${result.environment==='preview'?'Preview':'Production'}\n`+alignedRows(['Game','Status','Access'],result.games.map(g=>[g.name,g.displayStatus,g.accessText])):'No games.'
302
+ if(read==='check')message+='\n'+result.steps.map(s=>`${s.message}${s.nextAction?' '+s.nextAction:''}`).join('\n')
303
+ if(read==='requests')message+='\n'+(result.requests.map(r=>`${r.account.displayName??'FunFab account'} (account created ${r.account.createdAt.slice(0,10)}) — requested ${r.createdAt.slice(0,10)}`).join('\n')||'No pending access requests.')+(result.next?`\nMore requests: ${nextAction.command}`:'')
304
+ if(!asJson&&read==='requests')message=result.requests.length?label(result.game)+'\n'+alignedRows(['Account','Account created','Requested'],result.requests.map(r=>[r.account.displayName??'FunFab account',r.account.createdAt.slice(0,10),r.createdAt.slice(0,10)]))+(result.next?`\nMore requests: ${nextAction.command}`:''):'No pending access requests.'
305
+ output({...result,...(steps?{steps}:{}),message,...(nextAction?{nextAction}:{})})
306
+ }
307
+ function writeIntent() {
308
+ const title=args[0]==='title', answer=args[1]==='requests'
309
+ const base=title||answer?3:['set-status','allow','block'].includes(args[1])?4:3
310
+ const intent={action:title?`title-${args[1]}`:answer?'request-decide':args[1]==='set-status'?(args[3]==='internal'?'dev':args[3]==='playtest'?'live':undefined):({stop:'off',start:'on',allow:'grant',block:'block'}[args[1]]),selector:args[2]}
311
+ if(!intent.action||!intent.selector||(!title&&['allow','block'].includes(args[1])&&!args[3]))throw Error('usage')
312
+ if(!title&&['allow','block'].includes(args[1]))intent.accountId=args[3]
313
+ const flags=new Map()
314
+ for(let i=base;i<args.length;i++) {
315
+ const flag=args[i], boolean=['--remove','--approve','--decline'].includes(flag)
316
+ if(flags.has(flag)||!['--reason','--expires','--answer','--remove','--approve','--decline'].includes(flag))throw Error('usage')
317
+ if(!boolean&&(!args[i+1]||args[i+1].startsWith('--')))throw Error('usage')
318
+ flags.set(flag,boolean?true:args[++i])
319
+ }
320
+ intent.reason=flags.get('--reason')
321
+ if(!intent.reason?.trim()||intent.reason.trim().length>1000)throw Error('usage')
322
+ if(flags.has('--remove')&&!['allow','block'].includes(args[1])||['--answer','--approve','--decline'].some(f=>flags.has(f))&&!answer)throw Error('usage')
323
+ if(intent.accountId&&!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(intent.accountId))throw Error('usage')
324
+ if(['grant','block'].includes(intent.action))intent.active=!flags.has('--remove')
325
+ if(answer) {
326
+ if(!flags.get('--answer')||flags.has('--approve')===flags.has('--decline')||!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(flags.get('--answer')))throw Error('usage')
327
+ intent.request=flags.get('--answer');intent.decision=flags.has('--approve')?'grant':'decline'
328
+ }
329
+ if(flags.has('--expires')) {
330
+ const value=flags.get('--expires')
331
+ if(!(intent.active||answer&&intent.decision==='grant'))throw Error('usage')
332
+ if(value!=='never'&&(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(?:Z|\+00:00)$/.test(value)||!Number.isFinite(Date.parse(value))))throw Error('usage')
333
+ intent.expiresAt=value==='never'?null:new Date(value).toISOString()
334
+ }
335
+ return intent
336
+ }
337
+ async function tokenCommand() {
338
+ await runToken(tokenIntent(args,{asJson,terminal}),{api,call,load,save,output,approvals,asJson})
339
+ }
340
+
341
+ async function gameWrite() {
342
+ const intent=writeIntent(),saved=await load()
343
+ let game,selected
344
+ const read=async(path,body)=>{
345
+ const value=await call(path,body,saved.ticket)
346
+ if(value.status==='activation_needed') {if(await confirmation(value))return call(path,body,saved.ticket);return null}
347
+ return value
348
+ }
349
+ if(intent.action.startsWith('title-')) {
350
+ const list=await read('game/list',{});if(!list)return
351
+ const titles=list.games.flatMap(g=>g.titles.filter(t=>t.retiredAt===null).map(t=>({game:g,title:t})))
352
+ let matches=titles.filter(t=>t.title.titleId===intent.selector)
353
+ if(!matches.length)matches=titles.filter(t=>t.title.name===intent.selector)
354
+ if(matches.length!==1)throw problem('game_request_invalid','Choose one current title by its exact name or ID.',commandAction('funfab game list'),2)
355
+ game=matches[0].game;selected=matches[0].title
356
+ } else {game=await read('game/status',{game:intent.selector});if(!game)return}
357
+ const {selector,...fields}=intent
358
+ const operation={...fields,game:game.gameId,environment:game.environment,revision:game.revision,affectedTitles:selected?[selected]:game.titles,mutationId:randomUUID()}
359
+ if(selected)Object.assign(operation,{title:selected.titleId,expectedShown:selected.shown,expectedRetiredAt:null})
360
+ let account
361
+ if(intent.action==='request-decide') {const requests=await read('game/requests',{game:game.gameId});if(!requests)return;account=requests.requests.find(r=>r.id===intent.request)?.account}
362
+ if(intent.accountId) {
363
+ const lookup=await read('game/lookup',{game:game.gameId,accountId:intent.accountId});if(!lookup)return
364
+ operation.accessRevision=lookup[intent.action].revision;account=lookup.targetAccount??lookup.account
365
+ }
366
+ const name=account?.displayName??'this FunFab account',g=game.name
367
+ const variant=intent.action==='grant'?(intent.active?'grant':'revoke'):intent.action==='block'?(intent.active?'block':'lift'):intent.action==='request-decide'?'request-'+intent.decision:intent.action
368
+ const questions={off:`Stop ${g}? Players can't start or join rooms.\nRooms already running end within 5 minutes.`,on:`Start ${g}? ${g} can be played again within 5 minutes. Rooms that ended don't come back.`,live:`Move ${g} to Playtest? After: Playtest, people on the allow list.`,dev:`Move ${g} to Internal? After: Internal, team only. The allow list is kept, but it won't do anything until the game moves back to Playtest.`,grant:`Add ${name} to ${g}'s allow list? Their daily room limits don't change.`,revoke:`Remove ${name} from ${g}'s allow list? If ${g} isn't open to everyone, ${name} won't be able to host it any more.`,block:`Add ${name} to ${g}'s block list? A room they're already running ends within 5 minutes.`,lift:`Remove ${name} from ${g}'s block list? Whether ${name} can host now depends on the game's access and its allow list.`,'request-grant':`Approve ${name}'s request to host ${g}? Their daily room limits don't change.`,'request-decline':`Decline ${name}'s request to host ${g}? They can ask again after 7 days.`,'title-show':`Show ${selected?.name} in the games list? Game access still decides who can host ${g}.`,'title-hide':`Hide ${selected?.name} from the games list? This doesn't stop people launching it through ${g}.`}
369
+ if(!asJson)output({message:`${game.environment==='preview'?'Preview':'Production'} · ${g}`})
370
+ const response=await approvals.write('game/action',{operation},saved,{prompt:questions[variant]+' [y/N]',destructive:game.environment==='production'&&['off','block','revoke','title-hide','request-decline'].includes(variant)?game.gameId:undefined})
371
+ if(!response)return
372
+ const result=response.result
373
+ const undo={off:`funfab game start ${game.gameId} --reason "…"`,on:`funfab game stop ${game.gameId} --reason "…"`,live:`funfab game set-status ${game.gameId} internal --reason TEXT`,dev:game.environment==='production'?`funfab game set-status ${game.gameId} playtest --reason TEXT`:null,grant:`funfab game allow ${game.gameId} ${intent.accountId} --remove --reason TEXT`,revoke:`funfab game allow ${game.gameId} ${intent.accountId} --reason TEXT [--expires TIME|never]`,block:`funfab game block ${game.gameId} ${intent.accountId} --remove --reason TEXT`,lift:`funfab game block ${game.gameId} ${intent.accountId} --reason TEXT [--expires TIME|never]`,'title-show':`funfab title hide ${selected?.titleId} --reason TEXT`,'title-hide':`funfab title show ${selected?.titleId} --reason TEXT`}[variant]
374
+ const messages={off:'Stopped.',on:'Started.',live:'Moved to Playtest.',dev:'Moved to Internal.',grant:'Added to the allow list.',revoke:'Removed from the allow list.',block:'Added to the block list.',lift:'Removed from the block list.','request-grant':'Request approved.','request-decline':'Request declined.','title-show':'Shown on the Games page.','title-hide':'Hidden from the Games page.'}
375
+ output({...result,...(!asJson?{message:messages[variant]+(undo?'\nTo undo: '+undo:'')}:{}),nextAction:commandAction(`funfab game status ${game.gameId}`)})
376
+ }
377
+
378
+ async function admit() {
379
+ const saved=await load(),game=await call('game/status',{game:args[2]},saved.ticket)
380
+ if(game.status==='activation_needed'){if(await confirmation(game))return admit();return}
381
+ const operation={action:'admit',game:game.gameId,enabled:args[3]==='on',gateEvidence:args[4],cleanupEvidence:args[5]}
382
+ const result=await approvals.write('admit',{operation,mutationId:randomUUID()},saved,{prompt:`Turn ${operation.enabled?'on':'off'} FunFab sign-in for ${game.name}? [y/N]`,needs:operation.enabled?`Turning on FunFab sign-in for ${game.name} needs you to confirm it's you.`:undefined})
383
+ if(result)output({...result,...(!asJson?{message:`FunFab sign-in turned ${operation.enabled?'on':'off'}.\nTo undo: funfab game admit ${game.gameId} ${operation.enabled?'off':'on'} GATE_EVIDENCE CLEANUP_EVIDENCE`}:{}),status:'updated'})
384
+ }
385
+ const refusals={
386
+ game_permission_denied:['You need staff access and must own this game.',person('Ask an authorized operator to check your staff access and game ownership.')],
387
+ game_submit_preview_only:['Game submission is available only on Preview.',person('Use the Preview accounts API for this submission.')],
388
+ game_environment_mismatch:['This game belongs to another environment.',person('Use the accounts API for the game’s environment.')],
389
+ game_admission_prerequisite:['The game is not ready for sign-in. Complete its submission and required checks, then try again.',person('Complete the game submission and required checks.')],
390
+ game_request_conflict:['This request ID was already used for a different submission.',edit('requestId',undefined,'Use a new request ID for a different submission.')],
391
+ game_revision_conflict:['The game changed since this submission was prepared.',person('Read the current game revision and prepare the submission again.')],
392
+ game_title_id_conflict:['This title ID is already in use.',edit('title.id',undefined,'Choose an available title ID or use the existing title through its authorized owner.')],
393
+ game_shared_enrollment_required:['This shared title needs an existing enrollment.',person('Ask an authorized operator to arrange the shared-title enrollment.')],
394
+ account_unavailable:['The account service could not complete this command. Try again later; ask an operator if it continues.',operator('Inspect the account service if this continues.')]
395
+ }
396
+ async function report(error,offer=true) {
397
+ const known={
398
+ terminal_required:[terminalMessage,commandAction('funfab token create')],
399
+ authorization_required:['Your sign-in has expired. To sign in again, run funfab login.',commandAction('funfab login')],
400
+ loopback_unavailable:['The local sign-in ports are busy. Close another sign-in attempt, then run funfab login.',commandAction('funfab login')],
401
+ attempt_expired:['Sign-in took too long. Run funfab login to start again.',commandAction('funfab login')],
402
+ ...refusals,
403
+ game_action_unavailable:['This action is not switched on here. Ask an operator.',operator('Ask an operator about availability for this action.')],
404
+ game_request_invalid:['Check the command arguments and current game state.',commandAction('funfab --help')],
405
+ accounts_request_invalid:['Check the command arguments and current game state.',commandAction('funfab --help')],
406
+ game_not_found:['The game was not found. Check its name in the game list.',commandAction('funfab game list')],
407
+ ...(isWrite?{game_environment_mismatch:['This command belongs to another environment.',operator('Use the accounts API for the matching game environment.')],game_revision_conflict:['Check the command arguments and current game state.',commandAction(args[0]==='title'?'funfab game list':`funfab game status ${args[2]}`)],game_request_conflict:['Check the command arguments and current game state.',commandAction(args[0]==='title'?'funfab game list':`funfab game status ${args[2]}`)]}:{}),
408
+ ...Object.fromEntries(['game_signups_closed','game_submission_required','game_switch_off_held','game_live_production_only','game_title_declaration_required','game_staff_cannot_be_blocked','game_account_not_found'].map(code=>[code,[{game_signups_closed:'Game sign-ups are closed.',game_submission_required:'This game needs approval before it can be opened.',game_switch_off_held:'A hold prevents starting this game.',game_live_production_only:'Moving a game to Playtest is available only on Production.',game_title_declaration_required:'This title needs a valid content declaration.',game_staff_cannot_be_blocked:'Staff accounts cannot be blocked.',game_account_not_found:'The target account is unavailable.'}[code],(code==='game_signups_closed'?operator:person)('Ask the authorized owner or operator to resolve this before creating another confirmation.')]])),
409
+ game_permission_denied:command.command==='game submit'?refusals.game_permission_denied:['You cannot change this game. Ask its owner or a staff member for help.',person('Ask the game owner or a staff member for help.')]
410
+ }
411
+ const entry=known[error.message]??['The command could not be completed. Ask an authorized operator to inspect it before continuing.',operator('Inspect the failed command before continuing.')]
412
+ fail(error.display?error.message:known[error.message]?error.message:'command_failed',error.display??entry[0],error.nextAction??entry[1],error.exit??(isWrite&&['accounts_request_invalid','game_request_invalid'].includes(error.message)?2:1),error.reason)
413
+ if(offer&&terminal&&!error.noSignIn&&error.message==='authorization_required') {
414
+ const rl=createInterface({input:process.stdin,output:process.stdout})
415
+ let answer
416
+ try {answer=await rl.question('Press Enter to sign in now, or anything else to stop. ')} finally {rl.close()}
417
+ if(answer==='') {process.exitCode=0;try {if(await login()){await command.run()}} catch(next) {await report(next,false)}}
418
+ }
419
+ }
420
+ if(api||(!informational&&usageOK&&['logout','game init'].includes(command.command)))try {if(personWrite)approvals.requireTerminal();await command.run()} catch(error) {await report(error)}
@@ -0,0 +1 @@
1
+ export const submitHelp = "## Start a submission\n\nRun `funfab game init my-game.json`. This works offline without signing in and creates a new file with a fresh `requestId`; existing files and links are refused. Keep that request ID for every rerun of this submission. Fill in the placeholders, then run `funfab game submit my-game.json`. The first unfilled field is reported with a correction step. Run `funfab game submit --help` for the field guide.\n\n- `game`: set `game_id`, `name`, `per_play_cost` (whether each play costs money), `retains_account_data` (whether the game keeps account-linked data), and `store_ids` (the game's stores, or an empty array if none). Set `daily_room_quota` when charging per play; otherwise leave it null. Keep `environment: \"preview\"` and `hosting: \"stream\"`. Fill `dnsTarget` with the host target when connecting the address.\n- `title`: set `id`, the displayed `name`, and `launchPath`, the path people use to launch the game.\n- `title.contentDeclaration`: replace each null with an honest content answer; `streamInput` means viewer input can appear on stream. `hostControls` names how the host hides inputs and blocks viewers. The other questions cover sexual content, strong violence, drugs, gambling, strong language, real money and whether the game is aimed at children. Child-directed games need a separate owner decision.\n- `deployment.build`: the commit of the deployment you inspected. Update it if the inspected build changes.\n- `addressReady` and `credentialInstalled`: start false. Submit tells you when to connect the address and install the sign-in key; set each true only after doing that step.\n- `mode`: keep `\"pass\"`. Add `checks` only at the final step, using the checklist below. Never put a sign-in key or ticket in this file.\n\n## Evidence checklist\n\nCollect evidence for the inspected build, then add `checks` to the same file. Use @funfab/sdk/schemas/host-safety for the host-safety result format. Examples below are fictional notes, not evidence to copy as a passing result. Replace `<inspected commit>` with the actual build and confirm only what you tested.\n\n| `checks` part | What it proves | Who produces it | How to get it | Example value |\n| --- | --- | --- | --- | --- |\n| `retention` | Account-linked data can be deleted, or none is kept. | Developer | Review stored data and exercise deletion; record the result or explain why no account data is retained. | `{\"passed\":true,\"evidence\":\"Deletion rehearsal removed the fixture account data\"}` |\n| `viewerDeletion` | A viewer has a working way to request deletion. | Developer | Exercise the viewer deletion route (initially support email) and record the result. | `{\"passed\":true,\"evidence\":\"Support email deletion rehearsal completed\"}` |\n| `accountsTokens` | The game uses the shared sign-in gate and has removed old account/token storage and writers. | Developer using the game's code and migration history | Inspect the gate version, code, migrations and removed writers; record each separately. | `{\"passed\":true,\"gateVersion\":\"ticket-v1\",\"code\":\"Gate integration inspected at build\",\"migrations\":\"Legacy token tables removed\",\"removedWriters\":\"Old token writers removed\"}` |\n| `gate` | The inspected game sends unsigned visitors through the expected sign-in gate. | CLI's anonymous HTTPS gate probe, or developer using existing probe output | For `anonymous_https`, supply the game, host and build binding; the final rerun replaces the gate entry with its probe result. For `attested_probe`, run the existing probe first and reference its output. | `{\"gameId\":\"example-game\",\"host\":\"example-game-preview.funfab.io\",\"build\":\"<inspected commit>\",\"result\":\"gated\",\"method\":\"attested_probe\",\"attested\":true,\"evidence\":\"Probe output: unsigned entry gated at inspected build\"}` |\n| `hostSafety` | Every inspected stream surface filters names and supports viewer blocks. | Game-owned LIVE safety producer (Reverie's tools) | Run the producer for this deployment and copy its attested result, including all inspected surfaces. | `{\"schemaVersion\":1,\"gameId\":\"example-game\",\"build\":\"<inspected commit>\",\"checkVersion\":\"live-v1\",\"result\":\"pass\",\"surfaces\":[{\"surface\":\"host\",\"nameFiltering\":true,\"viewerBlocks\":true}]}` |\n| `confirmedChecks` | You have reviewed the collected evidence for this build. | Developer | Review all five results above, then explicitly confirm at the final step. | `true` |\n\n`funfab game submit submission.json [--json]` is the caller-owned stream prototype\nsubmission on Preview. It works from this repository without CardForge. Sign in and\nactivate the CLI first. A staff member or super-admin owns every game they submit;\nthere is no alternate-owner option. Production refuses the call even if the file\nclaims Preview. \n\nKeep one structured file (correctable before registration) and its UUID `requestId` for every explicit rerun. Supply\n`mode: \"pass\"` (the temporary ticket-mode wire value), `game`, `title` with every\ncontent answer and a non-null validated `launchPath`, and `deployment: {\"build\":\n\"<inspected 40-character commit>\"}`. `game` uses the existing registration fields:\n`game_id`, `environment: \"preview\"`, `hosting: \"stream\"`, `name`, `per_play_cost`,\n`daily_room_quota` when needed, `retains_account_data`, `store_ids`, and `dnsTarget`\nwhen the person has attached the host and received its target. A non-shared store\nmay hold non-account data. Shared/reserved stores, reused stores and retired IDs\nremain refused. The title's `contentDeclaration` answers `streamInput`,\n`hostControls`, `sexualContent`, `strongViolence`, `drugs`, `gambling`,\n`strongLanguage`, `realMoney`, and `childDirected`. All answers are required;\nstream-visible inputs require named host controls. Child-directed games wait for\na separate owner decision; this command has no exception switch.\n\nFirst run with `addressReady: false`. Exit **4** asks the person to connect the\naddress record. Add its declared `dnsTarget`, set `addressReady: true`, then rerun.\nRegistration commits the game, title, encrypted native secret, sign-in-key hash,\naudit and progress together. Exit **5** delivers the sign-in key once. It appears on screen only when stdout is a terminal and `--json` is absent. Otherwise it is written to `<state folder>/keys/<game_id>-<requestId>.key`; JSON and redirected output return only the path. `--key-file PATH` always selects file delivery. The default keys folder is owner-only (0700), the file is owner-only (0600), and existing files are never overwritten. Its folder must be writable and its path must not already exist (including links) before a new registration call. Choose another `--key-file` path if there is a clash. A rerun for the exact request/client reference already saved by the CLI can keep its delivered key file; it is never overwritten. Install it privately at the game's host, then set\n`credentialInstalled: true`. If writing fails after registration, the key is never printed as a fallback: ask an authorized operator to replace it through the existing rotation. The secret-free request/client reference is saved before key delivery, including before a possible key-write failure; state saving remains best effort. Never copy it into the job file or CLI state.\nA first registration always stops at this pause, even if installation was claimed\nin advance. A repeat never returns either key or native client secret again.\n\nThe final rerun supplies `checks` from the OpenAPI schema. Confirm every check with\n`confirmedChecks: true`: retained-data deletion, the viewer deletion route (email\nis the initial route), gate evidence, account sign-in data evidence, and the game-owned\nLIVE host-safety result. For account sign-in data, `gateVersion`, `code`, `migrations` and\n`removedWriters` evidence are separate required fields; the gate version alone\ncannot pass. Missing, stale or failing safety results refuse admission. \nSurface names are unique and nonempty; a passing result requires name filtering\nand viewer blocks on every inspected surface. The producer belongs to Reverie;\nthis command consumes its attested result and does not build a second checker.\n\nFor `gate.method: \"anonymous_https\"`, the CLI anonymously reads the derived host's\n`/healthz` with redirects disabled, keeps only its exact public `build`, and checks\nthe entry's redirect against the existing canonical issuer/client/callback rules.\nNo cookies, provider credentials, provider API reads or authentication addresses\nare recorded. Missing/unknown/`dev` builds, unreachable hosts, provider login pages,\narbitrary redirects and wrong builds fail. If the person must instead use existing\nprobe output, supply `method: \"attested_probe\"`, `attested: true`, `result: \"gated\"`\nand a short output reference bound to the same game, host and inspected build.\nConfirm these checks only after running the probe. Nothing treats failure as a pass.\n\nSuccessful submission returns **0**, with FunFab sign-in on for staff and the\n`not_submitted` game listed as experimental on Preview, so staff can find and\nlaunch it. Initial admission still requires hidden/staff first; only Preview\nsubmit lists it afterward in the same transaction. A completed rerun reports the\ncurrent state; it never switches sign-in back on or changes the listing. Opening an unsubmitted row is refused on every database writer, with one Preview\nexception: an UPDATE to experimental while access stays staff. Production, open\ninserts, featured listing and wider access retain their existing refusals.\nCodes **1**, **2**, and **3** retain failure, invalid input and confirmation meanings.\nChanges ask you in the terminal first. Add --yes to skip the question. Protected CLI state keeps\nonly the existing session and a secret-free request/client reference, never the\nsign-in key, evidence or a confirmation address in saved state. Activation addresses\nare intentionally returned in JSON or manual command output, as with P2; diagnostics\nand evidence never include them. Human address pauses print the validated address record.\n\nIf a response or a newly created native client is uncertain, stop for an authorized\nplatform operator to inspect that exact registration. Reruns stay fenced. A committed\nclient is retained after a lost commit response; a definitely rolled-back SQL attempt\nalone may have its new client cleaned up. No blind deletion or recreation occurs. After a definite SQL rollback and successful\ncleanup, only that exact request/attempt returns to the editable address stage; the\nperson explicitly reruns. Unknown cleanup stays fenced. The current inspected build\ncan change between pauses; gate and LIVE evidence must both match it. Registered\ngame/title/store details remain fixed. Submit alone allows 180 seconds for bounded\nauthentication, registration and outcome/cleanup calls; login and admit keep 10 seconds.\n\n## If the sign-in key is lost\n\nMike or an explicitly authorized platform operator uses\n`createCredentialAdmin` with `createPostgresCredentialStore`, a privileged direct\nPreview database connection and verified operator account ID, to rotate the exact\nstored `credential_id` in `funfab_game_submissions`. Install the replacement privately,\nthen resume the same request. Rotation replaces the hash and audits it atomically;\nthere is no new rotation API, command or hosted setting.\n\nHosted acceptance waits for the game-owned LIVE producer, Reverie's gated-stream\ntwo-deploy-and-rollback proof with rooms/links preserved (cardforge#2315 after #2327),\nthe enrollment freeze in that repository, and the separately approved #373/#368\nhosted window. No source merge or local proof claims those hosted checks passed.\n"
@@ -0,0 +1,34 @@
1
+ // Anonymous, redirect-only HTTPS probe. No provider credentials, cookies or auth
2
+ // URLs leave this process. Unobservable deployment identity is never a pass.
3
+ export async function probeSubmitGate({target,title,deployment,clientId,authorizationEndpoint,transport=fetch}) {
4
+ const stop=reason=>{throw Object.assign(Error('game_submit_checks_required'),{reason})}
5
+ const request=async url=>{try {return await transport(url,{redirect:'manual',credentials:'omit',headers:{Accept:'text/html'},signal:AbortSignal.timeout(10000)})} catch {stop('The game host could not be reached.')}}
6
+ const https=u=>u.protocol==='https:'&&!u.username&&!u.password&&!u.hash&&!u.port
7
+ let stable,auth
8
+ try {stable=new URL(target.origin)} catch {stop('The game host must be a Preview funfab.io address.')}
9
+ if(!https(stable)||!stable.hostname.endsWith('-preview.funfab.io'))stop('The game host must be a Preview funfab.io address.')
10
+ try {auth=new URL(authorizationEndpoint)} catch {stop('The sign-in service address is not the expected one.')}
11
+ // The existing platform /config response supplies this expected issuer.
12
+ if(!https(auth)||auth.pathname!=='/auth/v1/oauth/authorize'||auth.search)stop('The sign-in service address is not the expected one.')
13
+ if(!/^[a-f0-9]{40}$/.test(deployment?.build??''))stop('deployment.build must be a 40-character commit hash.')
14
+ const callback=target.callback
15
+ const health=await request(new URL('/healthz',stable))
16
+ let data;try {data=await health.json()} catch {stop('The host health response is not JSON.')}
17
+ if(health.status!==200||data?.build!==deployment.build)stop('The host is running the wrong build.')
18
+ let current=new URL(title.launchPath,stable)
19
+ for(let hop=0;hop<6;hop++) {
20
+ if(current.origin!==stable.origin||!https(current)) stop('The sign-in redirect is wrong. Check its client, callback and response type.')
21
+ const response=await request(current)
22
+ if(![301,302,303,307,308].includes(response.status)||!response.headers.get('location'))stop('The game entry did not redirect to sign-in.')
23
+ let next;try {next=new URL(response.headers.get('location'),current)} catch {stop('The sign-in redirect is wrong. Check its client, callback and response type.')}
24
+ if(!https(next)) stop('The sign-in redirect is wrong. Check its client, callback and response type.')
25
+ if(next.origin===auth.origin&&next.pathname===auth.pathname) {
26
+ const q=next.searchParams
27
+ if(q.getAll('client_id').length!==1||q.get('client_id')!==clientId||q.getAll('redirect_uri').length!==1||q.get('redirect_uri')!==callback||q.getAll('response_type').length!==1||q.get('response_type')!=='code') stop('The sign-in redirect is wrong. Check its client, callback and response type.')
28
+ return {gameId:target.game_id,host:target.launch_host,build:deployment.build,result:'gated',method:'anonymous_https',attested:true,evidence:'Anonymous HTTPS redirect and public build checked on this machine'}
29
+ }
30
+ if(next.origin!==stable.origin||next.search) stop('The sign-in redirect is wrong. Check its client, callback and response type.')
31
+ current=next
32
+ }
33
+ stop('The game entry redirected too many times.')
34
+ }
package/cli/tokens.mjs ADDED
@@ -0,0 +1,201 @@
1
+ import {constants} from 'node:fs'
2
+ import {randomUUID} from 'node:crypto'
3
+ import {alignedRows} from './approvals.mjs'
4
+ import {mkdir,lstat,open,realpath} from 'node:fs/promises'
5
+ import {homedir} from 'node:os'
6
+ import {join,resolve} from 'node:path'
7
+
8
+ export const tokenCommands=[
9
+ {command:'token create',arguments:'GAME|--staff --name NAME [--allow status,stop-start,access] [--expires TIME] [--print]',description:'Create a named token after a person approves it',example:'funfab token create emote-defense --name "Claude balancing" --allow stop-start,access',next:'Answer the question in your terminal.'},
10
+ {command:'token list',arguments:'[GAME|--staff]',description:'List tokens you can manage',example:'funfab token list emote-defense'},
11
+ {command:'token revoke',arguments:'GAME NAME [--reason TEXT] | --staff NAME | GAME --all --reason TEXT',description:'Revoke a named token, or every game token',example:'funfab token revoke emote-defense "Claude balancing"'},
12
+ {command:'token kill-switch',arguments:'on --reason TEXT',description:'Switch off every agent token in this environment',example:'funfab token kill-switch on --reason "Incident"'}
13
+ ]
14
+ const invalid=()=>{throw Error('usage')}
15
+ export function tokenIntent(args,{asJson=false,terminal=false}={}) {
16
+ const action=args[1], flags=new Map(), positional=[]
17
+ for(let i=2;i<args.length;i++) {
18
+ const arg=args[i]
19
+ if(!arg.startsWith('--')){positional.push(arg);continue}
20
+ if(!['--staff','--all','--print','--name','--allow','--expires','--reason'].includes(arg)||flags.has(arg))invalid()
21
+ const boolean=['--staff','--all','--print'].includes(arg)
22
+ if(!boolean&&(!args[i+1]||args[i+1].startsWith('--')))invalid()
23
+ flags.set(arg,boolean?true:args[++i])
24
+ }
25
+ const allowed={create:['--staff','--name','--allow','--expires','--print'],list:['--staff'],revoke:['--staff','--all','--reason'],'kill-switch':['--reason']}[action]
26
+ if(!allowed||[...flags.keys()].some(f=>!allowed.includes(f)))invalid()
27
+ const staff=flags.has('--staff'), name=action==='create'?flags.get('--name'):positional[staff?0:1]
28
+ const validText=(v,max)=>typeof v==='string'&&v===v.trim()&&v.length>0&&[...v].length<=max&&!/[\x00-\x1f\x7f-\x9f]/.test(v)
29
+ const reason=flags.get('--reason')
30
+ if(flags.has('--reason')&&!validText(reason,1000))invalid()
31
+ if(action==='kill-switch') {
32
+ if(positional.length!==1||positional[0]!=='on'||!reason)invalid()
33
+ return {action,reason}
34
+ }
35
+ if(positional.some(v=>!validText(v,200)))invalid()
36
+ if(action==='list') {
37
+ if(positional.length>(staff?0:1))invalid()
38
+ return {action,...(staff?{scope:{scope:'staff'}}:positional[0]?{scope:{scope:'game',game:positional[0]}}:{})}
39
+ }
40
+ if(action==='revoke'&&flags.has('--all')) {
41
+ if(staff||positional.length!==1||!reason)invalid()
42
+ return {action,game:positional[0],allForGame:true,reason}
43
+ }
44
+ if(positional.length!==(action==='create'?(staff?0:1):(staff?1:2))||!validText(name,100))invalid()
45
+ const scope=staff?{scope:'staff'}:{scope:'game',game:positional[0]}
46
+ if(action==='revoke')return {action,scope,name,...(reason?{reason}:{})}
47
+ const powers=flags.has('--allow')?flags.get('--allow').split(','):[]
48
+ if(new Set(powers).size!==powers.length||powers.some(p=>!['status','stop-start','access'].includes(p)))invalid()
49
+ const ticks={status:powers.includes('status'),switchOff:powers.includes('stop-start'),access:powers.includes('access')}
50
+ let expiresAt=null
51
+ if(flags.has('--expires')) {
52
+ const value=flags.get('--expires')
53
+ if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value)||!Number.isFinite(Date.parse(value))||Date.parse(value)<=Date.now())invalid()
54
+ expiresAt=new Date(value).toISOString()
55
+ }
56
+ if(flags.has('--print')&&(asJson||!terminal))invalid()
57
+ return {action,scope,name,ticks,expiresAt,print:flags.has('--print')}
58
+ }
59
+ const environmentLabel=e=>e==='preview'?'Preview':'Production'
60
+ const quote=v=>'"'+v.replaceAll('\\','\\\\').replaceAll('"','\\"').replaceAll('$','\\$').replaceAll('`','\\`')+'"'
61
+ const scopeArg=s=>s.scope==='staff'?'--staff':/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.game)?s.game:quote(s.game)
62
+ const revokeCommand=i=>`funfab token revoke ${scopeArg(i.scope)} ${quote(i.name)}`
63
+ const listCommand=i=>`funfab token list ${scopeArg(i.scope)}`
64
+ const date=(value,time=false)=>new Intl.DateTimeFormat('en-US',{timeZone:'UTC',month:'short',day:'numeric',year:'numeric',...(time?{hour:'numeric',minute:'2-digit',hour12:true}:{})}).format(new Date(value)).replace(/\u202f/g,' ').replace(/\b(AM|PM)\b/g,m=>m.toLowerCase())
65
+ const powerLabels=t=>[...(t.status?['move between Internal and Playtest']:[]),...(t.switchOff?['stop and start']:[]),...(t.access?['allow and block lists']:[])]
66
+ const madeButNotSaved=i=>`The token "${i.name}" was made, but it couldn't be saved here,\nand it can't be shown again. Revoke it, then make a new one:\n ${revokeCommand(i)}`
67
+ const uncertain=i=>`Couldn't tell whether the token "${i.name}" was made.\nCheck with: ${listCommand(i)}\nIf it's listed, revoke it and make a new one. Don't run create again first.`
68
+ const failure=(code,message,command)=>Object.assign(Error(code),{display:message,nextAction:{kind:'command',command}})
69
+ const slug=value=>value.normalize('NFKD').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,100)||'token'
70
+
71
+ // Adapt native exclusive creation, not the replaceable cli.json writer. Values never enter state.
72
+ export async function tokenDestination(environment,scope,name,mutationId) {
73
+ if(!['preview','production'].includes(environment)||typeof process.getuid!=='function'||!constants.O_NOFOLLOW)throw Error('private_file_unavailable')
74
+ const base=resolve(process.env.XDG_CONFIG_HOME||join(homedir(),'.config'))
75
+ // Refuse links in user-selected parents as well as in the token directories/file.
76
+ await mkdir(base,{recursive:true,mode:0o700})
77
+ if(await realpath(base)!==base)throw Object.assign(Error('private_file_unavailable'),{path:base})
78
+ const owner=process.getuid(), parents=[base,join(base,'funfab'),join(base,'funfab','tokens'),join(base,'funfab','tokens',environment)]
79
+ for(const [index,path] of parents.entries()) {
80
+ if(index)await mkdir(path,{mode:0o700}).catch(error=>{if(error.code!=='EEXIST')throw error})
81
+ const stat=await lstat(path)
82
+ if(!stat.isDirectory()||stat.isSymbolicLink()||stat.uid!==owner||(stat.mode&0o022))throw Object.assign(Error('private_file_unavailable'),{path})
83
+ if(index) {
84
+ const directory=await open(path,constants.O_RDONLY|constants.O_DIRECTORY|constants.O_NOFOLLOW)
85
+ try {await directory.chmod(0o700)} catch(error) {throw Object.assign(error,{path})} finally {await directory.close()}
86
+ }
87
+ }
88
+ if(mutationId!==undefined&&!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(mutationId))throw Error('private_file_unavailable')
89
+ const path=join(parents.at(-1),`${scope.scope==='staff'?'staff':slug(scope.game)}-${slug(name)}${mutationId?'-'+mutationId:''}`)
90
+ return path
91
+ }
92
+ export async function saveToken(value,environment,scope,name,mutationId) {
93
+ const path=await tokenDestination(environment,scope,name,mutationId)
94
+ const handle=await open(path,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600)
95
+ try {await handle.chmod(0o600);await handle.writeFile(value+'\n');await handle.sync()} finally {await handle.close()}
96
+ return path
97
+ }
98
+ const displayPath=path=>path.startsWith(homedir()+'/')?'~'+path.slice(homedir().length):path
99
+ const shellPath=path=>/^[a-zA-Z0-9_./~-]+$/.test(path)?path:quote(path)
100
+ async function preflight(environment,intent,mutationId) {
101
+ let path=join(resolve(process.env.XDG_CONFIG_HOME||join(homedir(),'.config')),'funfab','tokens',environment)
102
+ try {
103
+ path=await tokenDestination(environment,intent.scope,intent.name,mutationId)
104
+ if(!mutationId)return
105
+ try {await lstat(path)} catch(error) {if(error.code==='ENOENT')return;throw error}
106
+ throw Error('private_file_unavailable')
107
+ } catch(error) {
108
+ path=error.path??path
109
+ const message=`The token file can't be created here: ${path}. No token was made. Fix the folder or path, then run the same command again.`
110
+ throw Object.assign(Error('token_file_unavailable'),{display:message,nextAction:{kind:'person',instruction:message}})
111
+ }
112
+ }
113
+ const activeToken=t=>{
114
+ const unusedUntil=new Date(t.lastUsedAt??t.createdAt);unusedUntil.setUTCFullYear(unusedUntil.getUTCFullYear()+1)
115
+ return !t.revokedAt&&(!t.expiresAt||Date.parse(t.expiresAt)>Date.now())&&unusedUntil.getTime()>Date.now()
116
+ }
117
+
118
+ export async function runToken(intent,{call,load,output,approvals,asJson=false}) {
119
+ const saved=await load()
120
+ if(intent.action!=='list')approvals.requireTerminal()
121
+ const read=async(path,input)=>{
122
+ let value=await call(path,input,saved.ticket)
123
+ if(value.status==='activation_needed') {if(!await approvals.wait(saved.ticket,value,{activation:true}))return null;value=await call(path,input,saved.ticket)}
124
+ return value
125
+ }
126
+ let environment,scopeName,game
127
+ if(intent.action==='revoke'&&!intent.allForGame) {
128
+ let listed
129
+ try {listed=await read('token/list',{scope:intent.scope})}
130
+ catch(error) {if(error.message==='game_permission_denied')throw failure(error.message,`No token named "${intent.name}" that you can revoke.`,listCommand(intent));throw error}
131
+ if(!listed)return
132
+ const matches=listed.tokens.filter(t=>t.name===intent.name),current=matches.filter(t=>!t.revokedAt)
133
+ if(!current.length&&matches.some(t=>t.revokedAt)) {output({environment:listed.environment,revokedCount:0,message:"Revoked. The agent can't use it any more."});return}
134
+ if(current.length!==1)throw failure('game_permission_denied',`No token named "${intent.name}" that you can revoke.`,listCommand(intent))
135
+ environment=listed.environment;scopeName=intent.scope.scope==='staff'?'staff, every game you manage':intent.scope.game
136
+ } else if(intent.scope?.scope==='staff'||intent.action==='kill-switch'||intent.action==='list'&&!intent.scope) {
137
+ const result=await read('token/list',intent.scope?{scope:intent.scope}:{});if(!result)return
138
+ environment=result.environment;scopeName='staff, every game you manage'
139
+ if(intent.action==='list')return list(result)
140
+ } else {
141
+ game=await read('game/status',{game:intent.scope?.game??intent.game})
142
+ if(!game)return
143
+ environment=game.environment;scopeName=game.name
144
+ }
145
+ async function list(result) {
146
+ const own=await read('whoami',{});if(!own)return
147
+ const rows=result.tokens.filter(activeToken).map(t=>{
148
+ const powers=powerLabels(t.ticks).join(', ')
149
+ const age=t.lastUsedAt?Math.max(0,Math.floor((Date.now()-Date.parse(t.lastUsedAt))/60000)):null
150
+ return [t.name,t.authorizerAccountId===own.accountId?'you':'a staff member',`can ${powers||'see only'}`,t.expiresAt?`ends ${date(t.expiresAt)}`:'until revoked',age===null?'never used':`last used ${age} min ago`]
151
+ })
152
+ output({environment:result.environment,tokens:result.tokens,message:alignedRows(asJson?null:['Name','Created by','Permissions','Ends','Last used'],rows)||(!asJson?'No tokens.':'')})
153
+ }
154
+ if(intent.action==='list') {const result=await read('token/list',{scope:intent.scope});if(result)await list(result);return}
155
+ if(intent.action!=='create') {
156
+ const {action,...input}=intent
157
+ const prompt=action==='kill-switch'?`Switch off every agent token on ${environmentLabel(environment)}? All agents stop at once, until staff switch tokens back on. [y/N]`:intent.scope?.scope==='staff'?`Revoke staff token "${intent.name}"? Any agent using it stops working at once. [y/N]`:`Revoke "${intent.name}" for ${game?.name??scopeName}? Any agent using it stops working at once. [y/N]`
158
+ if(intent.allForGame) {
159
+ const listed=await read('token/list',{scope:{scope:'game',game:intent.game}});if(!listed)return
160
+ const tokens=listed.tokens.filter(activeToken)
161
+ if(!tokens.length){output({environment,revokedCount:0,message:'No tokens.'});return}
162
+ for(const token of tokens)if(!await approvals.question(`Revoke \"${token.name}\" for ${game.name}? Any agent using it stops working at once. [y/N]`))return
163
+ const result=await call('token/revoke',{...input,approvedIn:approvals.approvedIn},saved.ticket)
164
+ output({...result,message:`Revoked ${result.revokedCount} tokens for ${game.name}. Agents can't use them any more.`});return
165
+ }
166
+ let result
167
+ try {result=await approvals.write(`token/${action}`,action==='kill-switch'?{state:'on',reason:intent.reason}:input,saved,{prompt})}
168
+ catch(error) {
169
+ if(action==='revoke'&&!intent.allForGame&&error.message==='game_permission_denied')throw failure(error.message,`No token named "${intent.name}" that you can revoke.`,listCommand(intent))
170
+ throw error
171
+ }
172
+ if(result)output({...result,message:action==='kill-switch'?`All agent tokens on ${environmentLabel(result.environment)} are switched off. People can still list and revoke them.`:intent.allForGame?`Revoked ${result.revokedCount} tokens for ${game.name}. Agents can't use them any more.\nStaff tokens still work here. To stop those too: funfab token kill-switch on`:"Revoked. The agent can't use it any more."})
173
+ return
174
+ }
175
+ if(!asJson)output({message:`${environmentLabel(environment)} · ${scopeName}`})
176
+ const mutationId=randomUUID()
177
+ await preflight(environment,intent,mutationId)
178
+ const operation={action:'token-create',environment,scope:intent.scope.scope,name:intent.name,ticks:intent.ticks,expiresAt:intent.expiresAt,mutationId,...(game?{game:game.gameId,revision:game.revision,affectedTitles:game.titles}:{})}
179
+ const powers=powerLabels(intent.ticks)
180
+ const prompt=`Create "${intent.name}" for ${scopeName}? It can ${powers.length===1&&intent.ticks.switchOff?'stop and start the game':powers.length?powers.join(', '):'see only'}. [y/N]`
181
+ let response
182
+ try {response=await approvals.write('token/create',{operation},saved,{prompt,needs:"Creating an agent token needs you to confirm it's you."})}
183
+ catch(error) {
184
+ if(error.message==='delegate_tokens_disabled')throw Object.assign(error,{display:`Agent tokens are switched off on ${environmentLabel(environment)} right now. Ask staff.`,nextAction:{kind:'person',instruction:'Ask staff.'}})
185
+ if(error.message==='game_revision_conflict')throw Object.assign(error,{display:'This approval is no longer valid. No token was made. Run the same command again for a new approval.',nextAction:{kind:'command',command:listCommand(intent)}})
186
+ if(error.message==='game_request_conflict')throw failure(error.message,uncertain(intent),listCommand(intent))
187
+ if(error.message==='game_request_invalid'&&error.reason==='expiry_elapsed')throw Object.assign(error,{display:'The requested end date has passed. Choose a later --expires time and run the command again.',nextAction:{kind:'command',command:listCommand(intent)}})
188
+ if(['authorization_required','game_request_invalid','game_request_conflict','game_revision_conflict','delegate_tokens_disabled','game_permission_denied','game_action_unavailable','game_environment_mismatch'].includes(error.message))throw error
189
+ throw failure('token_delivery_unknown',uncertain(intent),listCommand(intent))
190
+ }
191
+ if(!response)return
192
+ if(!response.tokenValue&&response.token&&response.nextAction) {output({token:response.token,nextAction:response.nextAction,...(!asJson?{message:response.nextAction.instruction}:{})});return}
193
+ if(!response.token||typeof response.tokenValue!=='string'||!new RegExp(`^ffgt_${environment}_[A-Za-z0-9_-]{43}$`).test(response.tokenValue))throw failure('token_delivery_unknown',uncertain(intent),listCommand(intent))
194
+ let path
195
+ try {path=await saveToken(response.tokenValue,environment,intent.scope,intent.name,mutationId)}
196
+ catch {throw failure('token_delivery_lost',madeButNotSaved(intent),revokeCommand(intent))}
197
+ const shown=displayPath(path)
198
+ const message=`Token created: ${intent.name} (${scopeName}, ${environmentLabel(environment)})\nCan: ${powers.length?['see',...powers].join(', '):'see only'}\n${intent.expiresAt?`Ends: ${date(intent.expiresAt,true)} UTC`:'Lasts until revoked'}\nSaved to ${shown}\n (readable only by you; shown nowhere else)\n\nTo use it: export FUNFAB_TOKEN_FILE=${shellPath(path)}\nTo revoke: ${revokeCommand(intent)}`
199
+ output({environment,name:intent.name,path,message})
200
+ if(intent.print)process.stdout.write(response.tokenValue+'\n')
201
+ }
package/funfab ADDED
@@ -0,0 +1,16 @@
1
+ #!/bin/sh
2
+ if ! command -v node >/dev/null 2>&1; then
3
+ echo 'Node.js is missing. Install Node.js 22 or newer, then run funfab again.' >&2
4
+ exit 2
5
+ fi
6
+ if ! node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)' 2>/dev/null; then
7
+ echo 'FunFab needs Node.js 22 or newer. Upgrade Node.js, then run funfab again.' >&2
8
+ exit 2
9
+ fi
10
+ # npm link installs this wrapper as a symlink; resolve it before finding cli/.
11
+ script="$0"
12
+ while [ -L "$script" ]; do
13
+ target=$(readlink "$script")
14
+ case "$target" in /*) script="$target" ;; *) script="$(dirname "$script")/$target" ;; esac
15
+ done
16
+ exec node "$(dirname "$script")/cli/funfab.mjs" "$@"
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@funfab/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=22"
7
+ },
8
+ "bin": {
9
+ "funfab": "funfab"
10
+ },
11
+ "files": [
12
+ "funfab",
13
+ "cli/",
14
+ "validation/",
15
+ "skills/"
16
+ ],
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/Everyone-Loves-Beacon/funfab-website.git",
20
+ "directory": "packages/cli"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "provenance": false
25
+ }
26
+ }
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: funfab
3
+ description: Check and change FunFab games with the funfab
4
+ CLI (status, stop and start, allow and block lists, access
5
+ requests). Use when the user asks about a FunFab game.
6
+ ---
7
+
8
+ # Working with FunFab
9
+
10
+ ## Before anything
11
+ - Use the funfab CLI with --json. Don't call the API directly.
12
+ - FUNFAB_TOKEN_FILE must be set. If it isn't, stop and ask
13
+ the person to create a token. Show them the command:
14
+ funfab token create GAME --name "…" --allow TICK
15
+ - Never use the person's own sign-in. Never pass --yes for
16
+ them. Never print or copy the token file.
17
+
18
+ ## Doing the work
19
+ - Read first: funfab game status GAME --json
20
+ - Give every change a --reason in the person's own words.
21
+ - If a command is refused for a missing permission, tell
22
+ the person which one to add (status, stop-start or
23
+ access). Don't retry.
24
+ - Follow nextAction in the JSON when there is one.
25
+ - After a change, tell the person what changed and the
26
+ undo command.
27
+
28
+ ## Hand these back to the person
29
+ Creating or revoking tokens, the kill switch, turning
30
+ FunFab sign-in on or off, editors, holds and submitting a
31
+ game need a person. Say so, and show the command they'd run.
@@ -0,0 +1,61 @@
1
+ import {registrationTarget} from './target.mjs'
2
+ const object=x=>x&&typeof x==='object'&&!Array.isArray(x)
3
+ const exact=(x,keys)=>object(x)&&Object.keys(x).every(k=>keys.includes(k))
4
+ const text=x=>typeof x==='string'&&x.trim().length>0&&x.length<=1000&&!/(fgc_|fst_|Bearer |access_token|refresh_token|client_secret|authorization_id|[?&](code|ticket|token)=)/i.test(x)
5
+ export function submitInput(body) {
6
+ const check=(ok,field,expected)=>{if(!ok)throw Object.assign(Error('game_submit_input_invalid'),{field,expected})}
7
+ check(exact(body,['approvedIn','requestId','mode','game','title','deployment','addressReady','credentialInstalled','checks']),'submission','an object with only the documented fields')
8
+ check(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(body.requestId??''),'requestId','a UUID')
9
+ check(body.mode==='pass','mode','"pass"')
10
+ check(exact(body.game,['game_id','environment','hosting','name','per_play_cost','daily_room_quota','retains_account_data','store_ids','dnsTarget']),'game','an object with only the documented game fields')
11
+ check(text(body.game.name),'game.name','a nonempty name without secrets')
12
+ check(body.game.environment==='preview','game.environment','"preview"')
13
+ check(body.game.hosting==='stream','game.hosting','"stream"')
14
+ check(exact(body.title,['id','name','launchPath','contentDeclaration']),'title','an object with only the documented title fields')
15
+ for(const k of ['id','name','launchPath'])check(text(body.title[k]),'title.'+k,'nonempty text without secrets')
16
+ check(exact(body.deployment,['build']),'deployment','an object containing build')
17
+ check(/^[a-f0-9]{40}$/.test(body.deployment.build??''),'deployment.build','a 40-character lowercase commit hash')
18
+ for(const k of ['addressReady','credentialInstalled'])check(body[k]===undefined||typeof body[k]==='boolean',k,'true or false')
19
+ const d=body.title.contentDeclaration
20
+ const answers=['streamInput','sexualContent','strongViolence','drugs','gambling','strongLanguage','realMoney','childDirected']
21
+ check(exact(d,[...answers,'hostControls']),'title.contentDeclaration','an object with every content answer and hostControls')
22
+ for(const k of answers)check(typeof d[k]==='boolean','title.contentDeclaration.'+k,'true or false')
23
+ check(!d.childDirected,'title.contentDeclaration.childDirected','false; games aimed at children need a separate owner decision')
24
+ check(typeof d.hostControls==='string'&&d.hostControls.length<=1000&&(!(d.streamInput||d.hostControls.length>0)||text(d.hostControls)),'title.contentDeclaration.hostControls','text naming host controls when stream input is used')
25
+ let target
26
+ try {target=registrationTarget({...body.game,dnsTarget:body.game.dnsTarget??'pending.up.railway.app'})} catch(error) {
27
+ // registrationTarget owns these rules; keep its server error code unchanged.
28
+ throw Object.assign(error,{field:'game',expected:'a valid game; check game_id, store_ids and dnsTarget'})
29
+ }
30
+ const {dnsTarget,...game}=body.game,{dns,...bindingTarget}=target
31
+ return {target,input:{mode:'pass',game,title:body.title,deployment:body.deployment,target:bindingTarget}}
32
+ }
33
+ export function submitEvidence(checks) {
34
+ if(!exact(checks,['retention','viewerDeletion','accountsTokens','hostSafety','gate','confirmedChecks'])||checks.confirmedChecks!==true) throw Error('game_submit_checks_required')
35
+ for(const k of ['retention','viewerDeletion']) if(!exact(checks[k],['passed','evidence'])||checks[k].passed!==true||!text(checks[k].evidence)) throw Error('game_submit_checks_required')
36
+ const a=checks.accountsTokens,h=checks.hostSafety,g=checks.gate
37
+ if(!exact(a,['passed','gateVersion','code','migrations','removedWriters'])||a.passed!==true||!['gateVersion','code','migrations','removedWriters'].every(k=>text(a[k]))||
38
+ !exact(h,['schemaVersion','gameId','build','checkVersion','result','surfaces'])||h.schemaVersion!==1||h.result!=='pass'||
39
+ !['gameId','build','checkVersion'].every(k=>text(h[k]))||!Array.isArray(h.surfaces)||!h.surfaces.length||
40
+ !h.surfaces.every(s=>exact(s,['surface','nameFiltering','viewerBlocks'])&&text(s.surface)&&s.nameFiltering===true&&s.viewerBlocks===true)||
41
+ new Set(h.surfaces.map(s=>s.surface)).size!==h.surfaces.length||
42
+ !exact(g,['gameId','host','build','result','method','attested','evidence'])||g.result!=='gated'||!['anonymous_https','attested_probe'].includes(g.method)||g.attested!==true||
43
+ !['gameId','host','build','evidence'].every(k=>text(g[k]))) throw Error('game_submit_checks_required')
44
+ return checks
45
+ }
46
+ export const submitCopy=(name,environment='Preview')=>{
47
+ const prefix=`${name} — ${environment}: `
48
+ return {
49
+ address:prefix+"add the shown address record, set game.dnsTarget if needed and addressReady: true in the file, then run the same command.",
50
+ key:prefix+"install this game's sign-in key privately, set credentialInstalled: true in the file, then run the same command. If the key was lost, ask an authorized platform operator to replace it.",
51
+ complete:prefix+'FunFab sign-in is on for staff.',
52
+ listed:prefix+'FunFab sign-in is on for staff. The game is listed for staff on Preview.',
53
+ off:prefix+'FunFab sign-in is off.',
54
+ unknown:prefix+'registration needs an authorized platform operator to inspect it before you continue.',
55
+ checks:prefix+'confirm these checks for the inspected build: deletion, viewer deletion, access gate, host safety and account sign-in data.',
56
+ refused:prefix+'submission could not continue. Check your current sign-in, staff access, ownership and Preview settings.',
57
+ invalid:prefix+'check the submission file and all content answers. Games aimed at children need a separate decision.',
58
+ browserFailed:prefix+'the browser did not open automatically.',
59
+ activation:prefix+'confirm your command-line sign-in in your browser, then run the command again.',
60
+ }
61
+ }
@@ -0,0 +1,23 @@
1
+ // Fixed registration targets are declared by the caller; no provider metadata is read.
2
+ const paths={stream:'/auth/funfab/callback',vercel:'/auth/callback'}
3
+ const reserved=['www','api','accounts','account','auth','games','games-preview','preview','mail','support','admin','status','assets','crowdwork','snarktank','roast-rope','judges-chair','crowd-theory','read-the-room','mafia-live']
4
+ const cnamePatterns={stream:/^[a-z0-9-]+\.up\.railway\.app$/,vercel:/^(?:[a-z0-9-]+\.)?vercel-dns(?:-[0-9]+)?\.com$/}
5
+ export const invalid=()=>{throw Error('game_target_unverified')}
6
+ export function registrationTarget(input) {
7
+ const {game_id,environment,hosting,name,per_play_cost,daily_room_quota,retains_account_data,store_ids,dnsTarget,kind}=input??{}
8
+ if((kind!==undefined&&!['game','staff_tool'].includes(kind))||
9
+ !Object.hasOwn(paths,hosting)||!['preview','production'].includes(environment)||
10
+ !/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(game_id??'')||game_id.length>55||game_id.endsWith('-preview')||
11
+ reserved.includes(game_id)||typeof name!=='string'||!name.trim()||name.length>120||
12
+ typeof per_play_cost!=='boolean'||typeof retains_account_data!=='boolean'||
13
+ (per_play_cost&&(!Number.isInteger(daily_room_quota)||daily_room_quota<1))||
14
+ !Array.isArray(store_ids)||store_ids.some(id=>typeof id!=='string'||!id)||new Set(store_ids).size!==store_ids.length||
15
+ (retains_account_data&&!store_ids.length)) return invalid()
16
+ const dns=typeof dnsTarget==='string'&&hosting==='vercel'?dnsTarget.replace(/\.$/,''):dnsTarget
17
+ if(typeof dns!=='string'||!cnamePatterns[hosting].test(dns)) return invalid()
18
+ const pattern=environment==='preview'?'{game}-preview.funfab.io':'{game}.funfab.io'
19
+ const host=pattern.replace('{game}',game_id)
20
+ return {game_id,environment,hosting,...(kind===undefined?{}:{kind}),name:name.trim(),origin:`https://${host}`,callback:`https://${host}${paths[hosting]}`,
21
+ launch_host:host,stores:store_ids.map(id=>({id,shared:false})),retains_account_data,per_play_cost,daily_room_quota:per_play_cost?daily_room_quota:null,
22
+ dns:{host,record:`${host} CNAME ${dns}`}}
23
+ }