@funfab/cli 0.3.2 → 0.5.0

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/cli/funfab.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import {submitHelp} from './submit-help.mjs'
2
+ import {fieldGuide,submitHelp,submitSummary,submitInitMessage,vercelAddressMessage,vercelAddressSteps,railwayAddressMessage,railwayKeyMessage,vercelKeyMessage,submitRefusal,upgradeMessage} from './submit-help.mjs'
3
+ import {version,userAgent} from './version.mjs'
3
4
  import {createServer} from 'node:http'
4
5
  import {spawn} from 'node:child_process'
5
6
  import {createInterface} from 'node:readline/promises'
@@ -9,12 +10,15 @@ import {mkdir,readFile,open,rename,unlink,chmod,lstat} from 'node:fs/promises'
9
10
  import {randomBytes,randomUUID} from 'node:crypto'
10
11
  import {homedir} from 'node:os'
11
12
  import {join,dirname,resolve} from 'node:path'
12
- import {submitInput,submitCopy} from '../validation/submit.mjs'
13
+ import {submitInput,submitEvidence} from '../validation/capability-submit.mjs'
13
14
  import {probeSubmitGate} from './submit-probe.mjs'
15
+ import {vercelProbeRefusal} from './submit-probe-copy.mjs'
14
16
  import {CALLBACKS,createAttempt,authorizationURL} from './attempt.mjs'
15
17
  import {tokenCommands,tokenIntent,runToken} from './tokens.mjs'
16
- import {createApprovals,terminalMessage,alignedRows,malformedConfirmation,writePauseStatuses} from './approvals.mjs'
18
+ import {tokenRequestHelp,tokenRequestIntent,runTokenRequest,decodeApproval,approvalHelp,approvalIntent,runHoldApproval} from './request-approval.mjs'
19
+ import {createApprovals,terminalRequired,terminalMessage,alignedRows,malformedConfirmation} from './approvals.mjs'
17
20
  import {apiAddress,preview,validatedSignInConfig} from './origins.mjs'
21
+ import {readAgentToken,safeCredentialDiagnostic,tokenRefusal} from './credential.mjs'
18
22
  import {privateDirectories,privateFilesSupported} from './private-directory.mjs'
19
23
 
20
24
  if(Number(process.versions.node.split('.')[0])<22) {
@@ -31,62 +35,71 @@ const operator=instruction=>({kind:'operator',instruction})
31
35
  const operatorFailure=['The command could not be completed. Ask an authorized operator to inspect it before continuing.',operator('Inspect the failed command before continuing.')]
32
36
  const edit=(field,value,instruction)=>({kind:'edit_field',field,...(value===undefined?{}:{value}),instruction})
33
37
  const problem=(error,message,nextAction,exit=1)=>Object.assign(Error(error),{display:message,nextAction,exit})
34
- const fail=(error,message,nextAction,code=1,reason)=>{output({error,...(reason?{reason}:{}),...(asJson&&error==='terminal_required'?{}:{message}),nextAction});process.exitCode=code}
38
+ const fail=(error,message,nextAction,code=1,reason,interval)=>{output({error,...(reason?{reason}:{}),...(interval?{interval}:{}),...(asJson&&error==='terminal_required'?{}:{message}),nextAction});process.exitCode=code}
35
39
  const base=resolve(process.env.XDG_CONFIG_HOME||homedir()), root=join(base,'.funfab'), file=join(root,'cli.json')
36
40
  const address=apiAddress(process.env.FUNFAB_CLI_API_URL,process.env.FUNFAB_CLI_ALLOW_CUSTOM_API)
37
- if(address?.custom)console.error(`Using a custom API address: ${address.origin}`)
38
41
  const output=value=>{
39
42
  if(Object.hasOwn(value,'confirmationUrl'))return malformedConfirmation()
40
43
  print(value)
41
44
  }
45
+ const writePowers={'set-status':'status',stop:'stop-start',start:'stop-start',hold:'stop-start',unhold:'stop-start',allow:'access',block:'access'}
42
46
  const commands=[
47
+ ...tokenRequestHelp.map(c=>({...c,run:tokenRequest})),
48
+ ...approvalHelp.map(c=>({...c,run:approvalCommand})),
43
49
  ...tokenCommands.map(c=>({...c,run:tokenCommand})),
44
50
  {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},
45
51
  {command:'logout',arguments:'',description:'Sign out on this computer and end this CLI session',example:'funfab logout',run:logout,count:1},
46
52
  {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},
47
- ...['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})),
48
- ...['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})),
49
- ...['hold','unhold'].map(action=>({command:`game ${action}`,arguments:`GAME ${action==='hold'?'[--reason TEXT]':'--reason TEXT'}`,description:action==='hold'?'Place a hold; nobody can start the game until a person lifts it':'Lift the hold; the game stays stopped',example:`funfab game ${action} my-game --reason 'Reason'`,next:'Answer the question in your terminal.',run:gameWrite})),
53
+ ...['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'}`,...(read==='requests'?{next:'Needs an agent token.',nextFor:'--answer'}:{}),run:gameRead,count:read==='list'?2:3})),
54
+ ...['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:'Needs an agent token.',run:gameWrite})),
55
+ ...['hold','unhold'].map(action=>({command:`game ${action}`,arguments:`GAME ${action==='hold'?'[--reason TEXT]':'--reason TEXT'}`,description:action==='hold'?'Place a hold; nobody can start the game until a person lifts it':'Lift the hold; the game stays stopped',example:`funfab game ${action} my-game --reason 'Reason'`,next:'Needs an agent token.',run:gameWrite})),
50
56
  ...['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})),
51
57
  {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},
52
- {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},
58
+ {command:'game submit',arguments:'FILE',description:submitSummary,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},
53
59
  {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},
54
60
  {command:'help',arguments:'',description:'Show every command and option',example:'funfab --help'}
55
61
  ]
62
+ const retiredCreate=args[0]==='token'&&args[1]==='create'
56
63
  const command=commands.find(c=>args.slice(0,c.command.split(' ').length).join(' ')===c.command)
64
+ let holdIntent
65
+ if(command?.run===approvalCommand) {try {holdIntent=approvalIntent(args)} catch {}}
66
+ let requestIntent
67
+ if(command?.run===tokenRequest) {try {requestIntent=tokenRequestIntent(args.slice(2))} catch {}}
57
68
  let tokenUsage=false
58
- if(command?.run===tokenCommand) {try {tokenIntent(args,{asJson,terminal:Boolean(process.stdin.isTTY&&process.stdout.isTTY)});tokenUsage=true} catch {}}
69
+ if(command?.run===tokenCommand) {try {tokenIntent(args);tokenUsage=true} catch {}}
59
70
  let writeUsage=false
60
71
  if(command?.run===gameWrite||command?.command==='game requests'&&args.includes('--answer')) {
61
72
  try {writeIntent();writeUsage=true} catch {}
62
73
  }
63
74
  const isWrite=command?.run===gameWrite||command?.command==='game requests'&&args.includes('--answer')
64
- 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 ${preview.api}`},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'}}
65
- const fieldGuide={
66
- game:'Registration details: fill in the game ID, name, charging, data stores and host target before submitting.',
67
- title:'Catalog identity and launchPath: fill in before submitting.',
68
- contentDeclaration:'Inside title: answer every content question and name host controls before submitting.',
69
- deployment:'Set build to the inspected deployment commit before submitting; update it when the build changes.',
70
- addressReady:'Start false; set true after connecting the shown address record.',
71
- credentialInstalled:'Start false; set true after installing the delivered sign-in key privately.',
72
- checks:'Add the evidence and confirmedChecks at the final step.'
73
- }
74
- const informational=!argv.length||argv.includes('--help')||args[0]==='help'||argv.includes('--version')
75
+ const tokenPower=args[0]==='game'?(args[1]==='requests'&&isWrite?'access':Object.hasOwn(writePowers,args[1])?writePowers[args[1]]:undefined):undefined
76
+ const tokenRead=command?.run===gameRead&&!isWrite
77
+ const tokenUnsupported=['title show','title hide','game admit','game submit'].includes(command?.command)
78
+ const tokenPath=process.env.FUNFAB_TOKEN_FILE
79
+ const approvalOnly=command?.run===approvalCommand
80
+ const tokenMode=Boolean(tokenPath&&(tokenRead||tokenUnsupported||tokenPower||approvalOnly))
81
+ const tokenRequired=retiredCreate||Boolean((tokenPower||approvalOnly)&&!tokenPath)
82
+ const localTokenRefusal=tokenRequired||tokenMode&&tokenUnsupported
83
+ let agentToken
84
+ 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, where one is still asked','--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_TOKEN_FILE:'The file holding your agent token',FUNFAB_CLI_API_URL:`Accounts API HTTPS origin; default ${preview.api}`},exitCodes:{0:'Done',1:'Failed',2:'Check the command, settings or token file',3:'Needs a person: sign-in, an approval, or a token',4:'Connect the game address, then run the same command again',5:'Install the game sign-in key, then run the same command again'}}
85
+ const warnCustomAddress=()=>console.error(`Using a custom API address: ${safeCredentialDiagnostic(address.origin)}`)
86
+ if(address?.custom&&!tokenMode)warnCustomAddress()
87
+ const informational=!retiredCreate&&(!argv.length||argv.includes('--help')||args[0]==='help'||argv.includes('--version'))
75
88
  if(informational) {
76
- if(argv.includes('--version')) {const {version}=JSON.parse(await readFile(new URL('../package.json',import.meta.url),'utf8'));output({version,message:version})}
89
+ if(argv.includes('--version')) output({version,message:version})
77
90
  else {
78
91
  const entries=command&&command.command!=='help'?[help.commands.find(c=>c.command===command.command)]:help.commands
79
92
  const fields=command?.command==='game submit'?fieldGuide:undefined
80
- 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')})
93
+ 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.nextFor?` (${c.nextFor})`:''}: ${c.next}`]:[])]),...(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')})
81
94
  if(!argv.length)process.exitCode=2
82
95
  }
83
96
  }
84
97
  let usageOK=true
85
- 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)))) {
98
+ if(!informational&&!retiredCreate&&(!command?.run||(command.run===tokenCommand?!tokenUsage:command.run===tokenRequest?!requestIntent:approvalOnly?!holdIntent: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)))) {
86
99
  usageOK=false;fail('command_invalid','Check the command and its arguments. Run funfab --help for examples.',commandAction('funfab --help'),2)
87
100
  }
88
- const api=!informational&&usageOK&&command.command!=='game init'?address?.origin:undefined
89
- if(!api&&!informational&&usageOK&&!['game init','logout'].includes(command.command)) {
101
+ const api=!informational&&usageOK&&!localTokenRefusal&&command.command!=='game init'?address?.origin:undefined
102
+ if(!api&&!informational&&usageOK&&!localTokenRefusal&&!['game init','logout'].includes(command.command)) {
90
103
  const message="FUNFAB_CLI_API_URL isn't a FunFab API address. To use another address for testing, also set FUNFAB_CLI_ALLOW_CUSTOM_API=1."
91
104
  fail('configuration_invalid',message,person(message),2)
92
105
  }
@@ -139,24 +152,55 @@ const load=async()=>{
139
152
  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'))}
140
153
  }
141
154
  async function call(path,body,ticket,signal,origin=api) {
142
- const actionConfirmation=path==='token/create'||path==='game/action'&&body?.operation?.action==='unhold'
143
- const response=await fetch(`${origin}/api/cli/${path}`,{redirect:'error',method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json'}),...(actionConfirmation?{'FunFab-CLI-Action-Confirmation':'1'}:{}),...(ticket?{Authorization:`Bearer ${ticket}`}:{})},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:signal?AbortSignal.any([signal,AbortSignal.timeout(10000)]):AbortSignal.timeout(path==='submit'?180000:10000)})
155
+ const bearer=agentToken!==undefined&&ticket===agentToken
156
+ const payload=body===undefined?undefined:JSON.stringify(body)
157
+ if(bearer&&(origin.includes(ticket)||payload?.includes(ticket)))throw Error('account_unavailable')
158
+ const response=await fetch(`${origin}/api/cli/${path}`,{redirect:'error',method:body===undefined?'GET':'POST',headers:{'User-Agent':userAgent,...(body===undefined?{}:{'Content-Type':'application/json'}),...(ticket?{Authorization:`Bearer ${ticket}`}:{})},...(payload===undefined?{}:{body:payload}),signal:signal?AbortSignal.any([signal,AbortSignal.timeout(10000)]):AbortSignal.timeout(path==='submit'?180000:10000)})
144
159
  const rateLimited=response.status===429
145
- const data=await (rateLimited?response.json().catch(()=>null):response.json())
160
+ const data=await response.json().catch(error=>{
161
+ if(rateLimited)return null
162
+ if(path==='approval'&&error instanceof SyntaxError)throw Object.assign(Error('account_unavailable'),{unreadableApproval:true})
163
+ throw error
164
+ })
165
+ if(path==='approval'&&!(response.status===429&&!data)) {
166
+ if(bearer&&JSON.stringify(data)?.includes(ticket))throw Error('account_unavailable')
167
+ if(response.status===202&&data?.status==='activation_needed'&&!bearer)return data
168
+ if(response.ok) {
169
+ try {return decodeApproval(response.status,data,{...body,address,bearer})}
170
+ catch(error) {throw Object.assign(error,{unreadableApproval:true})}
171
+ }
172
+ if(!data||typeof data.error!=='string'||!/^[a-z_]+$/.test(data.error))throw Error('account_unavailable')
173
+ const reason=['input_invalid','expiry_elapsed','invalidated'].includes(data.reason)?data.reason:undefined
174
+ throw Object.assign(Error(data.error),{httpStatus:response.status,reason})
175
+ }
146
176
  if(rateLimited&&(typeof data?.error!=='string'||!data.error.trim())) {
147
177
  throw problem('rate_limited','Too many requests to FunFab right now. Wait a minute, then try again.',person('Wait a minute, then try again.'))
148
178
  }
149
- if(data?.status==='action_confirmation_needed'&&(!actionConfirmation||response.status!==202))return malformedConfirmation()
150
- if(actionConfirmation&&response.status===202&&!writePauseStatuses.includes(data?.status))return malformedConfirmation()
151
- 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
179
+ if(bearer&&(!data||typeof data!=='object'||Array.isArray(data)||JSON.stringify(data).includes(ticket)||
180
+ (response.ok&&(response.status!==200||Object.hasOwn(data,'status')||Object.hasOwn(data,'confirmationUrl')||Object.hasOwn(data,'error')))))throw Error('account_unavailable')
181
+ if(path==='submit'&&response.status===400&&data?.error==='cli_upgrade_required') {
182
+ const minimumVersion=data.minimumVersion
183
+ const semver=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
184
+ if(typeof minimumVersion==='string'&&semver.test(minimumVersion)&&!/\s/.test(minimumVersion)) {
185
+ throw problem('cli_upgrade_required',upgradeMessage(minimumVersion),commandAction(`npm install --global @funfab/cli@${minimumVersion}`))
186
+ }
187
+ }
188
+ if(!response.ok) throw Object.assign(Error(data.error??'account_unavailable'),{httpStatus:response.status},(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
152
189
  }
153
190
  const signInConfig = async () => validatedSignInConfig(
154
191
  await call('config'), address, () => call('config',undefined,undefined,undefined,preview.api))
192
+ async function callWithToken(path,body,power,game) {
193
+ try {return await call(path,body,agentToken)}
194
+ catch(error) {
195
+ const message=tokenRefusal(error,address.environment,power,game,args[1]==='start')
196
+ if(message)throw problem(error.message,message,person(message))
197
+ if(error.message==='authorization_required')throw Error('account_unavailable')
198
+ throw error
199
+ }
200
+ }
155
201
  const terminal=Boolean(process.stdin.isTTY&&process.stdout.isTTY&&!asJson)
156
- const personWrite=isWrite||['game submit','game admit','token create','token revoke','token kill-switch'].includes(command?.command)
157
- 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
158
- 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
159
- const approvals=createApprovals({call,output:print,tokenAdvice,allowLoopback:address?.loopback,openBrowser:async url=>!noBrowser&&await openBrowser(url),asJson,yes})
202
+ const personWrite=isWrite&&!tokenPower||['game submit','game admit'].includes(command?.command)
203
+ const approvals=createApprovals({call,output:print,allowLoopback:address?.loopback,openBrowser:async url=>!noBrowser&&await openBrowser(url),asJson,yes})
160
204
  const interactiveBrowser=terminal&&!noBrowser
161
205
  const browserCommand=process.platform==='darwin'?'open':process.platform==='win32'?null:'xdg-open'
162
206
  function openBrowser(url) {
@@ -258,7 +302,15 @@ async function logout() {
258
302
  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"})
259
303
  }
260
304
  function starter() {
261
- 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}
305
+ return {
306
+ requestId:randomUUID(),
307
+ game:{game_id:'',environment:'preview',name:'',per_play_cost:null,retains_account_data:null,store_ids:[]},
308
+ capabilities:{'sign-in':{v:[1]},'hosted-rooms':{v:[1],daily_room_quota:null},'live-audience':{v:[1]},'host-auth':{v:[1]}},
309
+ binding:{adapter:'funfab-web-host',gate:'stream'},
310
+ title:{id:'',name:'',transport:'funfab-web-host',action:'host',launchPath:'',
311
+ contentDeclaration:{publicInput:null,publicInputControls:'',sexualContent:null,strongViolence:null,drugs:null,gambling:null,strongLanguage:null,realMoney:null,childDirected:null}},
312
+ deployment:{build:''},addressReady:false,credentialInstalled:false
313
+ }
262
314
  }
263
315
  async function init() {
264
316
  let handle
@@ -269,22 +321,23 @@ async function init() {
269
321
  const exists=error.code==='EEXIST'
270
322
  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)
271
323
  } finally {if(handle)await handle.close()}
272
- 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.')})
324
+ output({file:args[2],message:submitInitMessage(args[2]),nextAction:edit('game.name',undefined,'Fill in the game name, then the remaining submission fields.')})
273
325
  }
274
326
  async function submit() {
275
- let copy=submitCopy('Your game'), body, keyPath, keyFolder
327
+ let game='Your game', body, keyPath, keyFolder
276
328
  try {
277
329
  let raw
278
330
  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)}
279
331
  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)}
280
- const {target}=submitInput(body), saved=await load()
281
- copy=submitCopy(target.name)
332
+ const {target,input}=submitInput(body), saved=await load()
333
+ game=target.name
334
+ const vercel=target.hosting==='vercel'
282
335
  const toFile=!process.stdout.isTTY||asJson||keyFile!==undefined
283
336
  const registered=saved.submission?.requestId===body.requestId&&typeof saved.submission.clientId==='string'&&saved.submission.clientId.length>0
284
337
  if(toFile) {
285
338
  keyPath=resolve(keyFile??join(root,'keys',`${target.game_id}-${body.requestId}.key`));keyFolder=dirname(keyPath)
286
339
  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)
287
- if(body.addressReady&&body.game.dnsTarget) {
340
+ if(body.addressReady&&target.dns) {
288
341
  try {
289
342
  // A saved registration can resume with its already delivered key file.
290
343
  // For a new registration, reject every existing entry, including links.
@@ -312,52 +365,100 @@ async function submit() {
312
365
  } else console.log(gameCredential)
313
366
  }
314
367
  let message=safe.message,nextAction
315
- 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}
316
- 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}`}
368
+ if(result.status==='address_needed') {
369
+ if(vercel) {
370
+ const {gate,host,recordType}=safe.address??{}
371
+ if(gate!=='vercel'||host!==target.launch_host||recordType!=='CNAME') throw Error('account_unavailable')
372
+ safe.address={gate,host,recordType}
373
+ }
374
+ message=vercel?vercelAddressMessage(target.launch_host):railwayAddressMessage
375
+ nextAction=edit('addressReady',true,vercel?vercelAddressSteps:message)
376
+ const details=vercel?vercelAddressSteps:safe.addressRecord
377
+ if(!asJson&&details)message+='\n'+details
378
+ }
379
+ if(result.status==='key_needed') {
380
+ message=vercel?vercelKeyMessage(game):railwayKeyMessage
381
+ nextAction=edit('credentialInstalled',true,message)
382
+ if(delivered)message+=` Key file: ${delivered}`
383
+ }
317
384
  if(result.status==='operator_needed')nextAction=operator('Inspect this registration before continuing.')
318
385
  output({...safe,...(delivered?{keyFile:delivered}:{}),message,...(nextAction?{nextAction}:{})})
319
386
  process.exitCode={complete:0,address_needed:4,key_needed:5,operator_needed:1}[result.status]??1
320
387
  }
321
388
  if(!await approvals.question(`Turn on FunFab sign-in for ${target.name}? [y/N]`))return
322
- const reference=await call('submit',{...body,credentialInstalled:false,approvedIn:approvals.approvedIn},saved.ticket)
389
+ const {checks,...request}=body
390
+ request.binding=input.binding
391
+ request.approvedIn=approvals.approvedIn
392
+ const reference=await call('submit',{...request,credentialInstalled:false},saved.ticket)
323
393
  if(reference.status!=='key_needed'||reference.gameCredential||!body.credentialInstalled) {await emit(reference);return}
324
- if(reference.clientId) {saved.submission={requestId:body.requestId,clientId:reference.clientId};await save(saved).catch(()=>{})}
325
- if(body.credentialInstalled&&body.checks?.gate?.method==='anonymous_https') {
394
+ const {clientId}=reference
395
+ if(typeof clientId!=='string'||!clientId.trim()) {
396
+ await emit({status:'operator_needed',message:`${game} — Preview: registration needs an authorized platform operator to inspect it before you continue.`});return
397
+ }
398
+ saved.submission={requestId:body.requestId,clientId}
399
+ await save(saved).catch(()=>{})
400
+ const adapter=checks?.adapter
401
+ if(adapter?.method==='anonymous_https') {
402
+ if(adapter.gameId!==target.game_id||adapter.host!==target.launch_host||adapter.build!==input.deployment.build) {
403
+ throw Object.assign(Error('game_submit_checks_required'),{field:'checks.adapter',expected:'passing evidence for this deployment'})
404
+ }
326
405
  const config=await signInConfig()
327
- 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})
406
+ checks.adapter=await probeSubmitGate({target,title:body.title,deployment:body.deployment,clientId,authorizationEndpoint:new URL('/auth/v1/oauth/authorize',config.authOrigin).href})
328
407
  }
329
- await emit(await call('submit',{...body,approvedIn:approvals.approvedIn},saved.ticket))
408
+ submitEvidence(checks,{capabilities:input.capabilities,target,deployment:input.deployment})
409
+ await emit(await call('submit',{...request,checks},saved.ticket))
330
410
  } catch(error) {
331
411
  if(error.display||error.malformedConfirmation||['authorization_required','invalid_configuration',...Object.keys(refusals)].includes(error.message))throw error
412
+ if(Object.hasOwn(submitRefusal,error.message)) {
413
+ const instruction=submitRefusal[error.message]
414
+ fail(error.message,instruction,edit('capabilities',undefined,instruction),error.httpStatus?1:2);return
415
+ }
416
+ if(error.message==='game_submit_checks_required') {
417
+ const legacyReason=error.reason&&!Object.values(vercelProbeRefusal).includes(error.reason)
418
+ const message=(legacyReason?`${error.reason} Correct the gate check, then run the same command.`:error.reason)??(error.field?`Check ${error.field}: expected ${error.expected}. Correct this field, then run the same command.`:`${game} — Preview: confirm every applicable check for the inspected build.`)
419
+ fail(error.message,message,edit(error.field??'checks',undefined,error.reason??message));return
420
+ }
332
421
  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}
333
- 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}
334
- const checks=error.message==='game_submit_checks_required'
335
- 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)
336
- 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
337
- 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.'))
422
+ if(['game_submit_input_invalid','game_target_unverified'].includes(error.message)) {
423
+ fail('game_submit_input_invalid',`${game} — Preview: check the submission file and all content answers. Games aimed at children need a separate decision.`,person('Check the submission fields and all content answers.'),2);return
424
+ }
425
+ fail('game_submit_refused',`${game} — Preview: submission could not continue. Check your current sign-in, staff access, ownership and Preview settings.`,person('Check your sign-in, staff access, ownership and Preview settings.'))
338
426
  }
339
427
  }
340
428
  async function gameRead() {
341
429
  if(args[1]==='requests'&&args.includes('--answer'))return gameWrite()
342
- const read=args[1], saved=await load()
430
+ const read=args[1], saved=tokenMode?null:await load()
343
431
  let result
344
- try {result=await call(`game/${read}`,read==='list'?{}:{game:args[2],...(args[3]?{before:args[4]}:{})},saved.ticket)}
432
+ const body=read==='list'?{}:{game:args[2],...(args[3]?{before:args[4]}:{})}
433
+ try {result=tokenMode?await callWithToken(`game/${read}`,body):await call(`game/${read}`,body,saved.ticket)}
345
434
  catch(error) {
435
+ if(error.display&&tokenMode)throw error
346
436
  const retry=`funfab game requests '${String(args[2]??'').replaceAll("'", "'\\''")}'`
347
437
  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})
348
438
  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.'))
349
439
  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'))
350
440
  throw error
351
441
  }
352
- if(result.status==='activation_needed'){if(await confirmation(result))return gameRead();return}
442
+ if(tokenMode) {
443
+ const isSummary=game=>game?.environment===address.environment.id&&
444
+ ['gameId','name','displayStatus','accessText','listing'].every(key=>typeof game[key]==='string')
445
+ if(read==='list'?result.environment!==address.environment.id||!Array.isArray(result.games)||!result.games.every(isSummary):
446
+ !isSummary(read==='status'?result:result.game))throw Error('account_unavailable')
447
+ if(read==='check'&&!Array.isArray(result.steps)||read==='requests'&&
448
+ (!Array.isArray(result.requests)||result.requests.some(row=>typeof row?.accountId!=='string'||typeof row.createdAt!=='string')))throw Error('account_unavailable')
449
+ } else if(result.status==='activation_needed'){if(await confirmation(result))return gameRead();return}
353
450
  const steps=read==='check'?result.steps.map(s=>({...s,nextAction:s.nextAction?(['cleanup','signups','admission'].includes(s.step)?operator:person)(s.nextAction):null})):undefined
354
451
  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
355
452
  const label=game=>`${game.name} — ${game.environment==='preview'?'Preview':'Production'}\n${game.displayStatus} · ${{hidden:'hidden',experimental:'listed',featured:'featured'}[game.listing]}\n${game.accessText}`
356
453
  let message=read==='list'?`${result.environment==='preview'?'Preview':'Production'}\n${result.games.map(label).join('\n\n')||'No games.'}`:label(result.game??result)
357
454
  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.'
358
455
  if(read==='check')message+='\n'+result.steps.map(s=>`${s.message}${s.nextAction?' '+s.nextAction:''}`).join('\n')
359
- 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}`:'')
360
- 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.'
456
+ if(read==='requests') {
457
+ const headers=tokenMode?['Account','Requested']:['Account','Account created','Requested']
458
+ const rows=result.requests.map(r=>tokenMode?[r.accountId,r.createdAt.slice(0,10)]:[r.account.displayName??'FunFab account',r.account.createdAt.slice(0,10),r.createdAt.slice(0,10)])
459
+ if(!asJson)message=rows.length?label(result.game)+'\n'+alignedRows(headers,rows)+(result.next?`\nMore requests: ${nextAction.command}`:''):'No pending access requests.'
460
+ else if(!tokenMode)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}`:'')
461
+ }
361
462
  output({...result,...(steps?{steps}:{}),message,...(nextAction?{nextAction}:{})})
362
463
  }
363
464
  function writeIntent() {
@@ -373,7 +474,7 @@ function writeIntent() {
373
474
  if(!boolean&&(!args[i+1]||args[i+1].startsWith('--')))throw Error('usage')
374
475
  flags.set(flag,boolean?true:args[++i])
375
476
  }
376
- intent.reason=flags.get('--reason')??(intent.action==='hold'?'Person placed a switch-off hold':undefined)
477
+ intent.reason=flags.get('--reason')??(intent.action==='hold'?'An agent token placed a switch-off hold.':undefined)
377
478
  if(!intent.reason?.trim()||intent.reason.trim().length>1000)throw Error('usage')
378
479
  if(flags.has('--remove')&&!['allow','block'].includes(args[1])||['--answer','--approve','--decline'].some(f=>flags.has(f))&&!answer)throw Error('usage')
379
480
  if(intent.accountId&&!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(intent.accountId))throw Error('usage')
@@ -390,47 +491,76 @@ function writeIntent() {
390
491
  }
391
492
  return intent
392
493
  }
494
+ const missingApprovalToken=()=>problem('token_required',"This command needs an agent token. Set FUNFAB_TOKEN_FILE to the token's file. To get a token: funfab token request",commandAction('funfab token request'),3)
495
+ async function approvalCommand() {
496
+ await runHoldApproval(holdIntent,{call,ticket:agentToken,print,address,asJson})
497
+ }
498
+ async function tokenRequest() {
499
+ try {await runTokenRequest(requestIntent,{load,call,approvals,print,address,asJson})}
500
+ catch(error) {error.noSignIn=true;throw error}
501
+ }
393
502
  async function tokenCommand() {
394
- await runToken(tokenIntent(args,{asJson,terminal}),{api,call,load,save,output,approvals,asJson})
503
+ await runToken(tokenIntent(args),{call,load,output,approvals,asJson,environment:address.environment.id})
504
+ }
505
+
506
+ const elapsedExpiryMessage='That end date has passed. Run the same command again with --expires TIME or --expires never.'
507
+
508
+ function changeResult(result, gameId, message, expiryElapsed=false) {
509
+ const nextAction=commandAction(`funfab game status ${gameId}`)
510
+ const guidance=expiryElapsed?{reason:'expiry_elapsed',message:elapsedExpiryMessage}:{}
511
+ output({...result,...guidance,...(!asJson?{message:`${guidance.message??message}\nNext: ${nextAction.command}`}:{}),nextAction})
512
+ if(expiryElapsed)process.exitCode=1
395
513
  }
396
514
 
397
515
  async function gameWrite() {
398
- const intent=writeIntent(),saved=await load()
516
+ const {selector,...fields}=writeIntent(), saved=tokenMode?null:await load()
399
517
  let game,selected
400
518
  const read=async(path,body)=>{
519
+ if(tokenMode)return callWithToken(path,body,tokenPower)
401
520
  const value=await call(path,body,saved.ticket)
402
521
  if(value.status==='activation_needed') {if(await confirmation(value))return call(path,body,saved.ticket);return null}
403
522
  return value
404
523
  }
405
- if(intent.action.startsWith('title-')) {
524
+ if(fields.action.startsWith('title-')) {
406
525
  const list=await read('game/list',{});if(!list)return
407
526
  const titles=list.games.flatMap(g=>g.titles.filter(t=>t.retiredAt===null).map(t=>({game:g,title:t})))
408
- let matches=titles.filter(t=>t.title.titleId===intent.selector)
409
- if(!matches.length)matches=titles.filter(t=>t.title.name===intent.selector)
527
+ let matches=titles.filter(t=>t.title.titleId===selector)
528
+ if(!matches.length)matches=titles.filter(t=>t.title.name===selector)
410
529
  if(matches.length!==1)throw problem('game_request_invalid','Choose one current title by its exact name or ID.',commandAction('funfab game list'),2)
411
530
  game=matches[0].game;selected=matches[0].title
412
- } else {game=await read('game/status',{game:intent.selector});if(!game)return}
413
- const {selector,...fields}=intent
531
+ } else {game=await read('game/status',{game:selector});if(!game)return}
532
+ if(tokenMode&&(!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(game.gameId??'')||typeof game.name!=='string'||!game.name||
533
+ game.environment!==address.environment.id||!Number.isSafeInteger(game.revision)||game.revision<0||!Array.isArray(game.titles)))throw Error('account_unavailable')
414
534
  const operation={...fields,game:game.gameId,environment:game.environment,revision:game.revision,affectedTitles:selected?[selected]:game.titles,mutationId:randomUUID()}
535
+ if(fields.action==='unhold')return runHoldApproval({action:'request',operation,game},{call,ticket:agentToken,print,address,asJson})
415
536
  if(selected)Object.assign(operation,{title:selected.titleId,expectedShown:selected.shown,expectedRetiredAt:null})
416
- let account
417
- 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}
418
- if(intent.accountId) {
419
- const lookup=await read('game/lookup',{game:game.gameId,accountId:intent.accountId});if(!lookup)return
420
- operation.accessRevision=lookup[intent.action].revision;account=lookup.targetAccount??lookup.account
421
- }
422
- const name=account?.displayName??'this FunFab account',g=game.name
423
- 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
424
- const questions={hold:`Place a hold on ${g}? While it's held, nobody can start it until a person lifts the hold.`,unhold:`Lift the hold on ${g}? It stays stopped until someone starts it.`,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}.`}
425
- if(!asJson)output({message:`${game.environment==='preview'?'Preview':'Production'} · ${g}`})
537
+ const g=game.name
538
+ const variant=fields.action==='grant'?(fields.active?'grant':'revoke'):fields.action==='block'?(fields.active?'block':'lift'):fields.action==='request-decide'?'request-'+fields.decision:fields.action
539
+ const canExpire=['grant','block','request-grant'].includes(variant)
540
+ const messages={hold:'Hold placed.',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.'}
426
541
  let response
427
- try {response=await approvals.write('game/action',{operation},saved,{prompt:questions[variant]+' [y/N]',needsAction:variant==='unhold'?'Lifting a hold needs your confirmation in the browser.':undefined,needs:variant==='unhold'?`Lifting the hold on ${g} needs you to confirm it's you.`:undefined,destructive:game.environment==='production'&&['off','block','revoke','title-hide','request-decline'].includes(variant)?game.gameId:undefined})}
428
- catch(error) {if(error.message==='game_switch_off_held')throw problem(error.message,`${g} is on hold. A person has to lift the hold first: funfab game unhold ${game.gameId} --reason "…"`,commandAction(`funfab game unhold ${game.gameId} --reason "…"`));throw error}
542
+ if(tokenMode) {
543
+ try {response=await callWithToken('game/action',{operation},tokenPower,game)}
544
+ catch(error) {
545
+ if(canExpire&&error.message==='game_request_invalid'&&error.reason==='expiry_elapsed') {
546
+ fail(error.message,elapsedExpiryMessage,commandAction(`funfab game status ${game.gameId}`),1,error.reason)
547
+ return
548
+ }
549
+ throw error
550
+ }
551
+ if(response.result?.mutationId!==operation.mutationId||response.result?.game?.gameId!==game.gameId||
552
+ !['applied','not_active'].includes(response.result.outcome))throw Error('account_unavailable')
553
+ } else {
554
+ const questions={'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}.`}
555
+ if(!asJson)output({message:`${game.environment==='preview'?'Preview':'Production'} · ${g}`})
556
+ response=await approvals.write('game/action',{operation},saved,{prompt:questions[variant]+' [y/N]',destructive:game.environment==='production'&&variant==='title-hide'?game.gameId:undefined})
557
+ }
429
558
  if(!response)return
430
559
  const result=response.result
431
- 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]
432
- const messages={hold:'Hold placed.',unhold:`Hold lifted. ${g} is still stopped.\nTo start it: funfab game start ${game.gameId} --reason "…"`,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.'}
433
- output({...result,...(!asJson?{message:messages[variant]+(undo?'\nTo undo: '+undo:'')}:{}),nextAction:commandAction(`funfab game status ${game.gameId}`)})
560
+ if(!result)throw Error('account_unavailable')
561
+ const expiryElapsed=tokenMode&&canExpire&&!Object.hasOwn(operation,'expiresAt')&&result.outcome==='applied'&&
562
+ typeof result.expiresAt==='string'&&Date.parse(result.expiresAt)<=Date.now()
563
+ changeResult(result,game.gameId,messages[variant],expiryElapsed)
434
564
  }
435
565
 
436
566
  async function admit() {
@@ -438,7 +568,7 @@ async function admit() {
438
568
  if(game.status==='activation_needed'){if(await confirmation(game))return admit();return}
439
569
  const operation={action:'admit',game:game.gameId,enabled:args[3]==='on',gateEvidence:args[4],cleanupEvidence:args[5]}
440
570
  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})
441
- 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'})
571
+ if(result)changeResult({...result,status:'updated'},game.gameId,`FunFab sign-in turned ${operation.enabled?'on':'off'}.`)
442
572
  }
443
573
  const refusals={
444
574
  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.')],
@@ -453,7 +583,7 @@ const refusals={
453
583
  }
454
584
  async function report(error,offer=true) {
455
585
  const known={
456
- terminal_required:[terminalMessage,commandAction('funfab token create')],
586
+ terminal_required:[terminalMessage,terminalRequired.nextAction],
457
587
  authorization_required:['Your sign-in has expired. To sign in again, run funfab login.',commandAction('funfab login')],
458
588
  loopback_unavailable:['The local sign-in ports are busy. Close another sign-in attempt, then run funfab login.',commandAction('funfab login')],
459
589
  attempt_expired:['Sign-in took too long. Run funfab login to start again.',commandAction('funfab login')],
@@ -464,15 +594,36 @@ async function report(error,offer=true) {
464
594
  game_not_found:['The game was not found. Check its name in the game list.',commandAction('funfab game list')],
465
595
  ...(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]}`)]}:{}),
466
596
  ...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.')]])),
467
- 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.')]
597
+ 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.')]
468
598
  }
469
- const entry=known[error.message]??operatorFailure
470
- 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)
471
- if(offer&&terminal&&!error.noSignIn&&error.message==='authorization_required') {
599
+ const recognized=Object.hasOwn(known,error.message)
600
+ const entry=recognized?known[error.message]:operatorFailure
601
+ fail(error.display||recognized?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,error.interval)
602
+ if(offer&&!tokenMode&&terminal&&!error.noSignIn&&error.message==='authorization_required') {
472
603
  const rl=createInterface({input:process.stdin,output:process.stdout})
473
604
  let answer
474
605
  try {answer=await rl.question('Press Enter to sign in now, or anything else to stop. ')} finally {rl.close()}
475
606
  if(answer==='') {process.exitCode=0;try {if(await login()){await command.run()}} catch(next) {await report(next,false)}}
476
607
  }
477
608
  }
478
- if(api||(!informational&&usageOK&&['logout','game init'].includes(command.command)))try {if(personWrite)approvals.requireTerminal();await command.run()} catch(error) {await report(error)}
609
+ if(api||(!informational&&usageOK&&(localTokenRefusal||['logout','game init'].includes(command.command))))try {
610
+ if(tokenRequired) {
611
+ if(approvalOnly)throw missingApprovalToken()
612
+ const selector=args[2]??''
613
+ const game=/^[a-z0-9]+(-[a-z0-9]+)*$/.test(selector)?selector:"'"+selector.replaceAll("'","'\\''")+"'"
614
+ const message=retiredCreate?'funfab token create has been replaced. To get a token: funfab token request':
615
+ `This change needs an agent token. To get one: funfab token request ${game} --name "…" --allow ${tokenPower}`
616
+ throw problem('token_required',message,commandAction('funfab token request'),3)
617
+ }
618
+ if(tokenMode) {
619
+ if(tokenUnsupported) {
620
+ const message="An agent token can't do this yet. Ask the game's owner or a staff member to run this command."
621
+ throw problem('game_action_unavailable',message,person(`Ask the game's owner or a staff member to run funfab ${command.command}.`))
622
+ }
623
+ try {agentToken=await readAgentToken(tokenPath,address.environment)}
624
+ catch(error) {throw approvalOnly?missingApprovalToken():error}
625
+ if(address.custom){await signInConfig();warnCustomAddress()}
626
+ }
627
+ if(personWrite)approvals.requireTerminal()
628
+ await command.run()
629
+ } catch(error) {await report(error)}
package/cli/origins.mjs CHANGED
@@ -1,4 +1,6 @@
1
- export const preview = Object.freeze({api:'https://api-preview.funfab.io',website:'https://preview.funfab.io'})
1
+ export const preview = Object.freeze({api:'https://api-preview.funfab.io',website:'https://preview.funfab.io',id:'preview',label:'Preview'})
2
+ const environments = new Map([[preview.api,preview]])
3
+ export const environmentSettings = id => [...environments.values()].find(environment => environment.id === id)
2
4
  const loopbackHosts = ['localhost', '127.0.0.1', '[::1]']
3
5
  const loopback = url => ['http:', 'https:'].includes(url.protocol) && loopbackHosts.includes(url.hostname)
4
6
 
@@ -10,9 +12,9 @@ function parseURL(value, originOnly = false) {
10
12
  }
11
13
  export function apiAddress(value = preview.api, allowCustom) {
12
14
  const url = parseURL(value,true)
13
- if (value === preview.api) return {origin: value}
14
- if (url && loopback(url)) return {origin: value, loopback: true}
15
- if (url?.protocol === 'https:' && allowCustom === '1') return {origin: value, custom: true}
15
+ if (environments.has(value)) return {origin: value, environment: environments.get(value)}
16
+ if (url && loopback(url)) return {origin: value, loopback: true, environment: preview}
17
+ if (url?.protocol === 'https:' && allowCustom === '1') return {origin: value, custom: true, environment: preview}
16
18
  }
17
19
 
18
20
  export async function validatedSignInConfig(config, address, getPreviewConfig) {