@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/tokens.mjs CHANGED
@@ -1,31 +1,30 @@
1
1
  import {constants} from 'node:fs'
2
- import {randomUUID} from 'node:crypto'
3
- import {alignedRows} from './approvals.mjs'
4
- import {lstat,open} from 'node:fs/promises'
2
+ import {alignedRows, terminalMessage} from './approvals.mjs'
3
+ import {open} from 'node:fs/promises'
5
4
  import {privateDirectories,privateFilesSupported} from './private-directory.mjs'
5
+ import {environmentSettings} from './origins.mjs'
6
6
  import {homedir} from 'node:os'
7
7
  import {join,resolve} from 'node:path'
8
8
 
9
9
  export const tokenCommands=[
10
- {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.'},
11
10
  {command:'token list',arguments:'[GAME|--staff]',description:'List tokens you can manage',example:'funfab token list emote-defense'},
12
- {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"'},
11
+ {command:'token revoke',arguments:'GAME NAME|ID [--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"'},
13
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"'}
14
13
  ]
15
14
  const invalid=()=>{throw Error('usage')}
16
- export function tokenIntent(args,{asJson=false,terminal=false}={}) {
15
+ export function tokenIntent(args) {
17
16
  const action=args[1], flags=new Map(), positional=[]
18
17
  for(let i=2;i<args.length;i++) {
19
18
  const arg=args[i]
20
19
  if(!arg.startsWith('--')){positional.push(arg);continue}
21
- if(!['--staff','--all','--print','--name','--allow','--expires','--reason'].includes(arg)||flags.has(arg))invalid()
22
- const boolean=['--staff','--all','--print'].includes(arg)
20
+ if(!['--staff','--all','--reason'].includes(arg)||flags.has(arg))invalid()
21
+ const boolean=['--staff','--all'].includes(arg)
23
22
  if(!boolean&&(!args[i+1]||args[i+1].startsWith('--')))invalid()
24
23
  flags.set(arg,boolean?true:args[++i])
25
24
  }
26
- const allowed={create:['--staff','--name','--allow','--expires','--print'],list:['--staff'],revoke:['--staff','--all','--reason'],'kill-switch':['--reason']}[action]
25
+ const allowed={list:['--staff'],revoke:['--staff','--all','--reason'],'kill-switch':['--reason']}[action]
27
26
  if(!allowed||[...flags.keys()].some(f=>!allowed.includes(f)))invalid()
28
- const staff=flags.has('--staff'), name=action==='create'?flags.get('--name'):positional[staff?0:1]
27
+ const staff=flags.has('--staff'), name=positional[staff?0:1]
29
28
  const validText=(v,max)=>typeof v==='string'&&v===v.trim()&&v.length>0&&[...v].length<=max&&!/[\x00-\x1f\x7f-\x9f]/.test(v)
30
29
  const reason=flags.get('--reason')
31
30
  if(flags.has('--reason')&&!validText(reason,1000))invalid()
@@ -42,46 +41,35 @@ export function tokenIntent(args,{asJson=false,terminal=false}={}) {
42
41
  if(staff||positional.length!==1||!reason)invalid()
43
42
  return {action,game:positional[0],allForGame:true,reason}
44
43
  }
45
- if(positional.length!==(action==='create'?(staff?0:1):(staff?1:2))||!validText(name,100))invalid()
44
+ if(positional.length!==(staff?1:2)||!validText(name,100))invalid()
46
45
  const scope=staff?{scope:'staff'}:{scope:'game',game:positional[0]}
47
- if(action==='revoke')return {action,scope,name,...(reason?{reason}:{})}
48
- const powers=flags.has('--allow')?flags.get('--allow').split(','):[]
49
- if(new Set(powers).size!==powers.length||powers.some(p=>!['status','stop-start','access'].includes(p)))invalid()
50
- const ticks={status:powers.includes('status'),switchOff:powers.includes('stop-start'),access:powers.includes('access')}
51
- let expiresAt=null
52
- if(flags.has('--expires')) {
53
- const value=flags.get('--expires')
54
- 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()
55
- expiresAt=new Date(value).toISOString()
56
- }
57
- if(flags.has('--print')&&(asJson||!terminal))invalid()
58
- return {action,scope,name,ticks,expiresAt,print:flags.has('--print')}
46
+ return {action,scope,name,...(reason?{reason}:{})}
59
47
  }
60
- const environmentLabel=e=>e==='preview'?'Preview':'Production'
61
- const quote=v=>'"'+v.replaceAll('\\','\\\\').replaceAll('"','\\"').replaceAll('$','\\$').replaceAll('`','\\`')+'"'
62
- const scopeArg=s=>s.scope==='staff'?'--staff':/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.game)?s.game:quote(s.game)
63
- const revokeCommand=i=>`funfab token revoke ${scopeArg(i.scope)} ${quote(i.name)}`
64
- const listCommand=i=>`funfab token list ${scopeArg(i.scope)}`
65
- 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())
48
+ const environmentLabel=e=>environmentSettings(e)?.label??(e==='production'?'Production':undefined)
66
49
  const formatPowers=t=>[
67
50
  'Edit and unpublish store pages',
68
51
  ...(t.status?['Change the game’s status']:[]),
69
52
  ...(t.switchOff?['Stop and start the game']:[]),
70
53
  ...(t.access?['Requests, allow and block lists']:[])
71
54
  ].join(' · ')
72
- 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)}`
73
- 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.`
55
+ const quote=v=>'"'+v.replaceAll('\\','\\\\').replaceAll('"','\\"').replaceAll('$','\\$').replaceAll('`','\\`')+'"'
56
+ const scopeArg=s=>s.scope==='staff'?'--staff':/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.game)?s.game:quote(s.game)
57
+ const listCommand=i=>`funfab token list ${scopeArg(i.scope)}`
74
58
  const failure=(code,message,command)=>Object.assign(Error(code),{display:message,nextAction:{kind:'command',command}})
75
59
  const slug=value=>value.normalize('NFKD').toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,100)||'token'
76
60
 
77
61
  // Adapt native exclusive creation, not the replaceable cli.json writer. Values never enter state.
78
- export async function tokenDestination(environment,scope,name,mutationId) {
79
- if(!['preview','production'].includes(environment)||!privateFilesSupported)throw Error('private_file_unavailable')
62
+ export async function prepareTokenDirectory(environment) {
63
+ if(!environmentSettings(environment)||!privateFilesSupported)throw Error('private_file_unavailable')
80
64
  const base=resolve(process.env.XDG_CONFIG_HOME||join(homedir(),'.config'))
81
65
  const parents=[join(base,'funfab'),join(base,'funfab','tokens'),join(base,'funfab','tokens',environment)]
82
66
  await privateDirectories(base,parents,{create:true})
67
+ return parents.at(-1)
68
+ }
69
+ export async function tokenDestination(environment,scope,name,mutationId) {
70
+ const directory=await prepareTokenDirectory(environment)
83
71
  if(mutationId!==undefined&&!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(mutationId))throw Error('private_file_unavailable')
84
- const path=join(parents.at(-1),`${scope.scope==='staff'?'staff':slug(scope.game)}-${slug(name)}${mutationId?'-'+mutationId:''}`)
72
+ const path=join(directory,`${scope.scope==='staff'?'staff':slug(scope.game)}-${slug(name)}${mutationId?'-'+mutationId:''}`)
85
73
  return path
86
74
  }
87
75
  export async function saveToken(value,environment,scope,name,mutationId) {
@@ -90,53 +78,61 @@ export async function saveToken(value,environment,scope,name,mutationId) {
90
78
  try {await handle.chmod(0o600);await handle.writeFile(value+'\n');await handle.sync()} finally {await handle.close()}
91
79
  return path
92
80
  }
93
- const displayPath=path=>path.startsWith(homedir()+'/')?'~'+path.slice(homedir().length):path
94
- const shellPath=path=>/^[a-zA-Z0-9_./~-]+$/.test(path)?path:quote(path)
95
- async function preflight(environment,intent,mutationId) {
96
- let path=join(resolve(process.env.XDG_CONFIG_HOME||join(homedir(),'.config')),'funfab','tokens',environment)
97
- try {
98
- path=await tokenDestination(environment,intent.scope,intent.name,mutationId)
99
- if(!mutationId)return
100
- try {await lstat(path)} catch(error) {if(error.code==='ENOENT')return;throw error}
101
- throw Error('private_file_unavailable')
102
- } catch(error) {
103
- path=error.path??path
104
- 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.`
105
- throw Object.assign(Error('token_file_unavailable'),{display:message,nextAction:{kind:'person',instruction:message}})
106
- }
107
- }
81
+ const date=value=>new Intl.DateTimeFormat('en-US',{timeZone:'UTC',dateStyle:'medium'}).format(new Date(value))
108
82
  const activeToken=t=>{
109
83
  const unusedUntil=new Date(t.lastUsedAt??t.createdAt);unusedUntil.setUTCFullYear(unusedUntil.getUTCFullYear()+1)
110
84
  return !t.revokedAt&&(!t.expiresAt||Date.parse(t.expiresAt)>Date.now())&&unusedUntil.getTime()>Date.now()
111
85
  }
112
86
 
113
- export async function runToken(intent,{call,load,output,approvals,asJson=false}) {
114
- const saved=await load()
115
- if(intent.action!=='list')approvals.requireTerminal()
87
+ export async function runToken(intent,{call,load,output,approvals,asJson=false,environment}) {
88
+ const {ticket}=await load()
116
89
  const read=async(path,input)=>{
117
- let value=await call(path,input,saved.ticket)
118
- if(value.status==='activation_needed') {if(!await approvals.wait(saved.ticket,value,{activation:true}))return null;value=await call(path,input,saved.ticket)}
90
+ let value=await call(path,input,ticket)
91
+ if(value.status==='activation_needed') {if(!await approvals.wait(ticket,value,{activation:true}))return null;value=await call(path,input,ticket)}
119
92
  return value
120
93
  }
121
- let environment,scopeName,game,tokenToRevoke
122
- if(intent.action==='revoke'&&!intent.allForGame) {
123
- let listed
124
- try {listed=await read('token/list',{scope:intent.scope})}
125
- 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}
126
- if(!listed)return
127
- const matches=listed.tokens.filter(t=>t.name===intent.name),current=matches.filter(t=>!t.revokedAt)
128
- 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}
129
- if(current.length!==1||!current[0].id)throw failure('game_permission_denied',`No token named "${intent.name}" that you can revoke.`,listCommand(intent))
130
- tokenToRevoke=current[0];scopeName=tokenToRevoke.gameId??intent.scope.game
131
- } else if(intent.scope?.scope==='staff'||intent.action==='kill-switch'||intent.action==='list') {
132
- const result=await read('token/list',intent.scope?{scope:intent.scope}:{});if(!result)return
133
- environment=result.environment;scopeName='staff, every game you manage'
134
- if(intent.action==='list')return list(result)
135
- } else {
136
- game=await read('game/status',{game:intent.scope?.game??intent.game})
137
- if(!game)return
138
- environment=game.environment;scopeName=game.name
94
+ if(intent.action==='list') {
95
+ const result=await read('token/list',intent.scope?{scope:intent.scope}:{})
96
+ if(result)await list(result)
97
+ return
98
+ }
99
+ const {action,reason,scope,name,allForGame}=intent
100
+ const exactId=scope?.scope==='game'&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(name)
101
+ const path=`token/${action}`
102
+ const input=action==='kill-switch'?{state:'on',reason}:allForGame?{game:intent.game,allForGame:true,reason}:
103
+ {...(exactId?{tokenId:name}:{scope,name}),...(reason?{reason}:{})}
104
+ const prompt=(game,tokenName)=>action==='kill-switch'?
105
+ `Switch off every agent token on ${environmentLabel(environment)}? All agents stop at once, until staff switch tokens back on. [y/N]`:
106
+ allForGame?`Revoke every game token for ${game?.name??intent.game} (${game?.gameId??intent.game})? Any agent using one stops working at once. [y/N]`:
107
+ scope.scope==='staff'?`Revoke staff token "${tokenName}"? Any agent using it stops working at once. [y/N]`:
108
+ `Revoke "${tokenName}" for ${scope.game}? Any agent using it stops working at once. [y/N]`
109
+ const gameDisplay=async()=>{
110
+ const game=await call('game/status',{game:intent.game},ticket).catch(()=>null)
111
+ return game?.name&&game.gameId?game:null
112
+ }
113
+ let result, game
114
+ try {
115
+ try {result=await read(path,input);if(!result)return}
116
+ catch(error) {
117
+ if(error.httpStatus!==403||error.message!=='terminal_required')throw error
118
+ try {approvals.requireTerminal({allowJson:true})}
119
+ catch {throw Object.assign(Error('terminal_required'),{display:terminalMessage,exit:3,nextAction:{kind:'person',instruction:terminalMessage}})}
120
+ if(allForGame)game=await gameDisplay()
121
+ if(!await approvals.question(prompt(game,name),undefined,{allowJson:true}))return
122
+ result=await call(path,{...input,approvedIn:approvals.approvedIn},ticket)
123
+ }
124
+ } catch(error) {
125
+ if(action==='revoke'&&!allForGame&&!exactId&&error.message==='game_permission_denied')
126
+ throw failure(error.message,`No token named "${name}" that you can revoke.`,listCommand(intent))
127
+ throw error
139
128
  }
129
+ if(result.status==='activation_needed') {await approvals.wait(ticket,result,{activation:true,pendingOnly:true});return}
130
+ if(action==='revoke'&&(!Number.isSafeInteger(result.revokedCount)||result.revokedCount<0))throw Error('account_unavailable')
131
+ if(allForGame&&!game)game=await gameDisplay()
132
+ const message=allForGame?`Revoked ${result.revokedCount} tokens for ${game?.name??intent.game}. Agents can't use them any more.`:
133
+ action==='kill-switch'?`All agent tokens on ${environmentLabel(result.environment)} are switched off. People can still list and revoke them.`:
134
+ "Revoked. The agent can't use it any more."
135
+ output({...result,message})
140
136
  async function list(result) {
141
137
  const own=await read('whoami',{});if(!own)return
142
138
  const active=result.tokens.filter(activeToken)
@@ -153,51 +149,4 @@ export async function runToken(intent,{call,load,output,approvals,asJson=false})
153
149
  ])]
154
150
  output({environment:result.environment,tokens:result.tokens,message:lines.join('\n')||(!asJson?'No tokens.':'')})
155
151
  }
156
- if(intent.allForGame) {
157
- if(!game.gameId||!game.name)throw Error('account_unavailable')
158
- const prompt=`Revoke every game token for ${game.name} (${game.gameId})? Any agent using one stops working at once. [y/N]`
159
- const result=await approvals.write('token/revoke',{game:game.gameId,allForGame:true,reason:intent.reason},saved,{prompt})
160
- if(result)output({...result,message:`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`})
161
- return
162
- }
163
- if(intent.action!=='create') {
164
- const {action,reason}=intent
165
- const input=action==='kill-switch'?{state:'on',reason}:{tokenId:tokenToRevoke.id,...(reason?{reason}:{})}
166
- 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 "${tokenToRevoke.name}"? Any agent using it stops working at once. [y/N]`:`Revoke "${tokenToRevoke.name}" for ${scopeName}? Any agent using it stops working at once. [y/N]`
167
- let result
168
- try {result=await approvals.write(`token/${action}`,input,saved,{prompt})}
169
- catch(error) {
170
- if(action==='revoke'&&error.message==='game_permission_denied')throw failure(error.message,`No token named "${intent.name}" that you can revoke.`,listCommand(intent))
171
- throw error
172
- }
173
- 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.`:"Revoked. The agent can't use it any more."})
174
- return
175
- }
176
- if(!asJson)output({message:`${environmentLabel(environment)} · ${scopeName}`})
177
- const mutationId=randomUUID()
178
- await preflight(environment,intent,mutationId)
179
- 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}:{})}
180
- const powers=formatPowers(intent.ticks)
181
- const prompt=`Create "${intent.name}" for ${scopeName}? It can ${powers}. [y/N]`
182
- let response
183
- try {response=await approvals.write('token/create',{operation},saved,{prompt,needs:"Creating an agent token needs you to confirm it's you.",needsAction:'Creating an agent token needs your confirmation in the browser.'})}
184
- catch(error) {
185
- 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.'}})
186
- 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)}})
187
- if(error.message==='game_request_conflict')throw failure(error.message,uncertain(intent),listCommand(intent))
188
- 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)}})
189
- if(error.malformedConfirmation||['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
190
- throw failure('token_delivery_unknown',uncertain(intent),listCommand(intent))
191
- }
192
- if(!response)return
193
- if(!response.tokenValue&&response.token&&response.nextAction) {output({token:response.token,nextAction:response.nextAction,...(!asJson?{message:response.nextAction.instruction}:{})});return}
194
- 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))
195
- let path
196
- try {path=await saveToken(response.tokenValue,environment,intent.scope,intent.name,mutationId)}
197
- catch {throw failure('token_delivery_lost',madeButNotSaved(intent),revokeCommand(intent))}
198
- const shown=displayPath(path)
199
- const paidLine=response.paidGameName?`\n${response.paidGameName} costs money each time it's played. Starting it and letting players in will spend money.`:''
200
- const message=`Token created: ${intent.name} (${scopeName}, ${environmentLabel(environment)})\nSaved to ${shown}\n (readable only by you; shown nowhere else)\nCan: ${powers}${paidLine}\n${intent.expiresAt?`Ends: ${date(intent.expiresAt,true)} UTC`:'Lasts until revoked'}\n\nTo use it: export FUNFAB_TOKEN_FILE=${shellPath(path)}\nTo revoke: ${revokeCommand(intent)}`
201
- output({environment,name:intent.name,path,message})
202
- if(intent.print)process.stdout.write(response.tokenValue+'\n')
203
152
  }
@@ -0,0 +1,4 @@
1
+ import {readFileSync} from 'node:fs'
2
+
3
+ export const {version} = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))
4
+ export const userAgent = `funfab-cli/${version}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@funfab/cli",
3
- "version": "0.3.2",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -1,37 +1,81 @@
1
1
  ---
2
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.
3
+ description: Run FunFab games for a person with the funfab CLI
4
+ (status, stop and start, allow and block lists, access
5
+ requests, holds). Use when the user asks about a FunFab game.
6
6
  ---
7
7
 
8
8
  # Working with FunFab
9
9
 
10
+ You do the work. The person signs in, and approves the few
11
+ steps that need them.
12
+
10
13
  ## Before anything
11
14
  - 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.
15
+ - Changes need an agent token. If FUNFAB_TOKEN_FILE isn't set,
16
+ get one (below). Never print or copy a token file.
17
+
18
+ ## Register a game on Preview
19
+
20
+ Use CLI 0.5.0 after the Preview switch is announced. Prepare the file offline with `funfab game init`. For Vercel, set the gate and declare the capabilities with the developer. Use the developer’s activated staff CLI session at a terminal for submit. For this command, leave `FUNFAB_TOKEN_FILE` unset.
21
+
22
+ - **Exit 4 on Vercel.** Check the exact team, project, and non-Production Preview branch with the developer’s Vercel access. The binding must have no redirect or custom environment and must have exactly one rank-1 assigned CNAME. Give that target and any verification TXT record to the authorized operator through the existing DNS process. Once you verify the binding, DNS, and HTTPS, record `binding.vercelCname` and set `addressReady` to `true`.
23
+ - **Exit 4 on Railway.** Find the CNAME Railway assigns for the shown Preview address. Give it to the authorized operator through the existing DNS process. After verifying HTTPS on the address, record `binding.railwayCname` and set `addressReady` to `true`.
24
+ - **Exit 5.** Use the existing private process to give the authorized operator the file containing the sign-in key. Keep the key out of chat, the submission file, and logs. Have the operator install it on the exact Preview branch for Vercel, or in the game’s Preview hosting settings for Railway. Set `credentialInstalled` to `true` once it is installed and deployed.
25
+ - **Finish.** Use the same file and request ID for each rerun. Confirm evidence for the inspected commit. If registration is uncertain or the key was lost, stop and ask an authorized operator to inspect or rotate it.
26
+
27
+ ## Getting a token (once per game)
28
+ 1. If the person isn't signed in: run funfab login --json and
29
+ give them the link.
30
+ 2. Ask for only the powers you need:
31
+ funfab token request GAME --name "…" --allow stop-start
32
+ 3. The reply has nextAction.kind "open_url". Give the person
33
+ that link and the code. Never open the link yourself.
34
+ 4. When they say they approved, run the resume command.
35
+ 5. Set FUNFAB_TOKEN_FILE to the file it names.
17
36
 
18
37
  ## Doing the work
19
38
  - Read first: funfab game status GAME --json
20
39
  - 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.
32
-
33
- funfab game unhold and funfab token create
34
-
35
- These two commands need a person at a terminal and a
36
- browser every time. An agent should ask the person to
37
- run the command themselves. No token can do either.
40
+ - After a change, tell the person what changed.
41
+ - If a command is refused, tell the person why. Don't retry, and
42
+ don't try another way in.
43
+
44
+ ## Following nextAction
45
+ - "open_url": a person must open this link. Pass it on with the
46
+ code. Don't open it.
47
+ - "command": run that command when the step before it is done.
48
+ - "person": tell the person what it says.
49
+
50
+ ## When a step needs a person
51
+ Exit code 3 means a person has to do something.
52
+ - Say what the request will do, and who can approve it. Lifting
53
+ a hold needs someone who can switch the game off.
54
+ - If the approver isn't the token's maker, give them the
55
+ exact action, game, reason and code, so they can check them
56
+ with the token's maker before approving.
57
+ - The request ends at expiresAt. The approval and your resume
58
+ command both have to happen before then.
59
+ - To check on it, use the status command, no more often than
60
+ interval seconds.
61
+ - If it ran out of time, ask again.
62
+
63
+ ## Tell the person
64
+ - Approve only a request you were expecting.
65
+ - Check the code on the page matches the one I gave you.
66
+ - If you didn't start the request yourself, first check the
67
+ exact action, game, reason and code with the token's
68
+ maker, through a channel you already trust, not the message
69
+ the link came in.
70
+ - Use your own browser profile, never one an agent controls.
71
+
72
+ ## Only a person can
73
+ Sign in. Approve. Change who the editors or staff are. Anything
74
+ about their own account or money.
75
+ To stop an agent at once, a person runs:
76
+ funfab token revoke GAME "NAME"
77
+ funfab token kill-switch on --reason "…"
78
+
79
+ ## Exit codes
80
+ 0 done · 1 failed · 2 wrong command, setting or token file ·
81
+ 3 needs a person · 4 and 5 pauses during submit
@@ -0,0 +1,120 @@
1
+ import {registrationTarget} from './target.mjs'
2
+
3
+ const adapter = 'funfab-web-host'
4
+ const capabilityNames = ['sign-in', 'hosted-rooms', 'live-audience', 'host-auth']
5
+ const cnameFields = {stream: 'railwayCname', vercel: 'vercelCname'}
6
+ const pendingTargets = {stream: 'pending.up.railway.app', vercel: 'vercel-dns.com'}
7
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value)
8
+ const exact = (value, keys) => object(value) && Object.keys(value).every(key => keys.includes(key))
9
+ const text = (value, max = 1000) => typeof value === 'string' && value.trim().length > 0 &&
10
+ value.length <= max && !/(fgc_|fst_|ffgt_|Bearer |access_token|refresh_token|client_secret|authorization_id|[?&](code|ticket|token)=)/i.test(value)
11
+ const buildHash = /^[a-f0-9]{40}$/
12
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
13
+ const answers = ['publicInput', 'sexualContent', 'strongViolence', 'drugs', 'gambling', 'strongLanguage', 'realMoney', 'childDirected']
14
+
15
+ function check(ok, field, expected, code = 'game_submit_input_invalid') {
16
+ if (!ok) throw Object.assign(Error(code), {field, expected})
17
+ }
18
+
19
+ function capabilityProfile(capabilities, paid) {
20
+ check(object(capabilities), 'capabilities', 'an object keyed by capability name')
21
+ for (const [name, value] of Object.entries(capabilities)) {
22
+ const v = value?.v
23
+ check(capabilityNames.includes(name) && Array.isArray(v) && v.length === 1 && v[0] === 1,
24
+ 'capabilities', 'supported capabilities with version [1]', 'game_submit_capability_unsupported')
25
+ check(exact(value, name === 'hosted-rooms' ? ['v', 'daily_room_quota'] : ['v']),
26
+ `capabilities.${name}`, 'an object with only the documented capability fields')
27
+ }
28
+ check(Object.hasOwn(capabilities, 'sign-in') && (!paid || Object.hasOwn(capabilities, 'hosted-rooms')),
29
+ 'capabilities', 'sign-in and, for paid play, hosted-rooms', 'game_submit_capability_required')
30
+ const quota = capabilities['hosted-rooms']?.daily_room_quota
31
+ check((!paid && quota == null) || (Number.isInteger(quota) && quota > 0),
32
+ 'capabilities.hosted-rooms.daily_room_quota', 'a positive integer for paid play')
33
+ return quota
34
+ }
35
+
36
+ // Offline declaration validation also accepts files without terminal approval.
37
+ // The CLI supplies approvedIn from its terminal approval. Accounts API createCliAPI
38
+ // checks it before calling submit in server/accounts-api/cli-runtime.mjs.
39
+ export function submitInput(body) {
40
+ check(exact(body, ['approvedIn', 'requestId', 'game', 'capabilities', 'binding', 'title', 'deployment', 'addressReady', 'credentialInstalled', 'checks']),
41
+ 'submission', 'an object with only the documented fields')
42
+ const {game, capabilities, binding, title, deployment} = body
43
+ check(typeof body.requestId === 'string' && uuid.test(body.requestId), 'requestId', 'a UUID')
44
+ check(exact(game, ['game_id', 'environment', 'name', 'per_play_cost', 'retains_account_data', 'store_ids']),
45
+ 'game', 'an object with only the documented game fields')
46
+ check(typeof game.game_id === 'string', 'game', 'a valid game; check game_id and store_ids')
47
+ check(text(game.name, 120), 'game.name', 'a nonempty name without secrets')
48
+ check(game.environment === 'preview', 'game.environment', '"preview"')
49
+ check(typeof game.per_play_cost === 'boolean', 'game.per_play_cost', 'true or false')
50
+ check(typeof game.retains_account_data === 'boolean', 'game.retains_account_data', 'true or false')
51
+ check(Array.isArray(game.store_ids) && game.store_ids.every(id => text(id)), 'game.store_ids', 'a list of store IDs')
52
+ const quota = capabilityProfile(capabilities, game.per_play_cost)
53
+ check(exact(title, ['id', 'name', 'launchPath', 'contentDeclaration', 'transport', 'action']),
54
+ 'title', 'an object with only the documented title fields')
55
+ check(text(title.id) && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(title.id), 'title.id', 'a title slug')
56
+ check(text(title.name, 120), 'title.name', 'a nonempty name without secrets')
57
+ const path = title.launchPath
58
+ check(text(path, 256) && /^\/(?!\/)/.test(path) && !/[#\\\x00-\x1f\x7f-\x9f]|%(?:2f|5c|[01][\da-f]|7f)/i.test(path)
59
+ && !/(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i.test(path.split('?')[0]), 'title.launchPath', 'a path on the game’s Preview address')
60
+ check(title.transport === adapter, 'title.transport', '"funfab-web-host"')
61
+ check(['host', 'play'].includes(title.action), 'title.action', '"host" or "play"')
62
+ const d = title.contentDeclaration
63
+ check(exact(d, [...answers, 'publicInputControls']), 'title.contentDeclaration', 'an object with all content answers')
64
+ for (const key of answers) check(typeof d[key] === 'boolean', `title.contentDeclaration.${key}`, 'true or false')
65
+ check(!d.childDirected, 'title.contentDeclaration.childDirected', 'false; games aimed at children need a separate owner decision')
66
+ check((!d.publicInput && d.publicInputControls === '') || text(d.publicInputControls),
67
+ 'title.contentDeclaration.publicInputControls', 'text naming how you manage public input when it is used')
68
+ check(exact(deployment, ['build']) && typeof deployment.build === 'string' && buildHash.test(deployment.build),
69
+ 'deployment.build', 'a 40-character lowercase commit hash')
70
+ for (const key of ['addressReady', 'credentialInstalled']) check(body[key] === undefined || typeof body[key] === 'boolean', key, 'true or false')
71
+ const gate = binding?.gate
72
+ check((gate === 'stream' || gate === 'vercel') && exact(binding, ['adapter', 'gate', cnameFields[gate]]) && binding.adapter === adapter,
73
+ 'binding', 'a funfab-web-host binding for stream or Vercel')
74
+ const cname = binding[cnameFields[gate]]
75
+ check(cname === undefined || typeof cname === 'string', `binding.${cnameFields[gate]}`, 'the assigned CNAME target')
76
+ check(!body.addressReady || gate === 'stream' || cname !== undefined, 'binding.vercelCname', 'the assigned Vercel CNAME target')
77
+ let registration
78
+ try {
79
+ // Reuse registration's domain, callback and CNAME rules before the provider assigns a target.
80
+ registration = registrationTarget({...game, hosting: gate, daily_room_quota: quota, dnsTarget: cname ?? pendingTargets[gate]})
81
+ } catch (error) {
82
+ throw Object.assign(error, {field:'game', expected:'a valid game; check game_id, store_ids and the assigned CNAME'})
83
+ }
84
+ const {dns, ...target} = registration
85
+ const normalized = cname === undefined ? binding : {...binding, [cnameFields[gate]]: cname.replace(/\.$/, '')}
86
+ return {
87
+ target: {...target, ...(cname === undefined ? {} : {dns})},
88
+ input: {game, capabilities, binding:normalized, title, deployment, target}
89
+ }
90
+ }
91
+
92
+ export function submitEvidence(checks, {capabilities, target, deployment}) {
93
+ const valid = (ok, field) => check(ok, `checks.${field}`, 'passing evidence for this deployment', 'game_submit_checks_required')
94
+ const matches = value => value.gameId === target.game_id && value.build === deployment.build
95
+ valid(exact(checks, ['confirmedChecks', 'core', 'capabilities', 'adapter']) && checks.confirmedChecks === true, 'confirmedChecks')
96
+ valid(exact(checks.core, ['retention', 'viewerDeletion']), 'core')
97
+ for (const key of ['retention', 'viewerDeletion']) {
98
+ const note = checks.core[key]
99
+ valid(exact(note, ['passed', 'evidence']) && note.passed === true && text(note.evidence), `core.${key}`)
100
+ }
101
+ const live = Object.hasOwn(capabilities, 'live-audience')
102
+ valid(exact(checks.capabilities, live ? ['sign-in', 'live-audience'] : ['sign-in']), 'capabilities')
103
+ const signIn = checks.capabilities['sign-in']
104
+ valid(exact(signIn, ['passed', 'gateVersion', 'code']) && signIn.passed === true &&
105
+ text(signIn.gateVersion) && text(signIn.code),
106
+ 'capabilities.sign-in')
107
+ if (live) {
108
+ const h = checks.capabilities['live-audience']
109
+ valid(exact(h, ['schemaVersion', 'gameId', 'build', 'checkVersion', 'result', 'surfaces']) &&
110
+ h.schemaVersion === 1 && h.result === 'pass' && matches(h) && text(h.checkVersion, 100) &&
111
+ Array.isArray(h.surfaces) && h.surfaces.length > 0 && h.surfaces.every(s =>
112
+ exact(s, ['surface', 'nameFiltering', 'viewerBlocks']) && text(s.surface, 100) && s.nameFiltering === true && s.viewerBlocks === true) &&
113
+ new Set(h.surfaces.map(s => s.surface)).size === h.surfaces.length, 'capabilities.live-audience')
114
+ }
115
+ const g = checks.adapter
116
+ valid(exact(g, ['gameId', 'host', 'build', 'result', 'method', 'attested', 'evidence']) &&
117
+ matches(g) && g.host === target.launch_host && g.result === 'gated' && g.attested === true &&
118
+ ['anonymous_https', 'attested_probe'].includes(g.method) && text(g.evidence), 'adapter')
119
+ return checks
120
+ }