@funfab/cli 0.4.0 → 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/README.md CHANGED
@@ -41,12 +41,22 @@ Emote Defense is an example game. Use your own game's name; your agent finds its
41
41
  | "Put Emote Defense on hold." | `funfab game hold emote-defense --reason "…"` | nothing |
42
42
  | "Ask to lift the hold on Emote Defense. Reason: fixed the payout bug." | `funfab game unhold emote-defense --reason "…"` | you, or someone who can switch the game off, approve in the browser |
43
43
  | "Revoke the Balancing agent token." | `funfab token revoke emote-defense "Balancing agent"` | nothing (you can also run it yourself) |
44
- | "Register my new game." | `funfab game init game.json`, then helps you fill it in | run `funfab game submit game.json` in your terminal and answer its question |
44
+ | "Register my new game." | `funfab game init game.json`, then helps you fill it in | answer submit's question in your terminal if your agent asks you to |
45
45
 
46
46
  If a change needs a power your token doesn't have, your agent asks you for a new token with it.
47
47
 
48
48
  Changes need an agent token. When you run `funfab title show`, `funfab title hide`, `funfab game admit` or `funfab game submit` with your own sign-in, answer the question in your terminal. `--yes` skips that question where offered. High-stakes changes, like turning on FunFab sign-in for a game, also ask you to confirm it's you in your browser, once an hour.
49
49
 
50
+ ## Registering a new game
51
+
52
+ Ask your agent: "Register my new game on FunFab Preview." It prepares the file (`funfab game init`) and runs `funfab game submit`. Submit pauses twice. Your agent handles each step it can; if it can't, it tells you exactly what to do:
53
+
54
+ - **Exit 4, connect the address:** your agent sends the game's address records to a FunFab operator, who adds them. For a Vercel game, it first connects the address to the game's Preview branch using your Vercel access. Once the address works, it runs submit again.
55
+ - **Exit 5, install the sign-in key:** a FunFab operator installs the key privately in the game's Preview hosting settings. Your agent redeploys and runs submit again.
56
+ - **Exit 0:** the game is registered, and staff can play it on Preview.
57
+
58
+ A game with a live audience must pass its host-safety check first. Your agent fixes what the check lists, then submits again.
59
+
50
60
  ## Approving safely
51
61
 
52
62
  - Approve only if you were expecting this request.
@@ -77,8 +87,8 @@ Add --json to any command. Exit codes: 0 done, 1 failed,
77
87
  4 and 5 pauses during submit.
78
88
 
79
89
  ## Versions
80
- This is a trial (0.x). Pin an exact version. The previous
81
- version keeps working for 90 days after a new one.
90
+
91
+ This is a trial (0.x). Pin an exact version. The usual 90-day support window has one exception for this release. After the Preview switch, CLI 0.3.1 and 0.4.0 can still write starter files offline, but game submit in those versions will be refused. The older CLI may tell you to check sign-in, permissions or Preview settings. For a new submission, install 0.5.0 with `npm install --global @funfab/cli@0.5.0`, create a new file with `funfab game init`, and copy your answers into it.
82
92
 
83
93
  ## Help
84
94
  ```sh
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,8 +10,9 @@ 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
18
  import {tokenRequestHelp,tokenRequestIntent,runTokenRequest,decodeApproval,approvalHelp,approvalIntent,runHoldApproval} from './request-approval.mjs'
@@ -53,7 +55,7 @@ const commands=[
53
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})),
54
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})),
55
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},
56
- {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},
57
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},
58
60
  {command:'help',arguments:'',description:'Show every command and option',example:'funfab --help'}
59
61
  ]
@@ -80,24 +82,15 @@ const tokenRequired=retiredCreate||Boolean((tokenPower||approvalOnly)&&!tokenPat
80
82
  const localTokenRefusal=tokenRequired||tokenMode&&tokenUnsupported
81
83
  let agentToken
82
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'}}
83
- const fieldGuide={
84
- game:'Registration details: fill in the game ID, name, charging, data stores and host target before submitting.',
85
- title:'Catalog identity and launchPath: fill in before submitting.',
86
- contentDeclaration:'Inside title: answer every content question and name host controls before submitting.',
87
- deployment:'Set build to the inspected deployment commit before submitting; update it when the build changes.',
88
- addressReady:'Start false; set true after connecting the shown address record.',
89
- credentialInstalled:'Start false; set true after installing the delivered sign-in key privately.',
90
- checks:'Add the evidence and confirmedChecks at the final step.'
91
- }
92
85
  const warnCustomAddress=()=>console.error(`Using a custom API address: ${safeCredentialDiagnostic(address.origin)}`)
93
86
  if(address?.custom&&!tokenMode)warnCustomAddress()
94
87
  const informational=!retiredCreate&&(!argv.length||argv.includes('--help')||args[0]==='help'||argv.includes('--version'))
95
88
  if(informational) {
96
- 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})
97
90
  else {
98
91
  const entries=command&&command.command!=='help'?[help.commands.find(c=>c.command===command.command)]:help.commands
99
92
  const fields=command?.command==='game submit'?fieldGuide:undefined
100
- 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?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')})
101
94
  if(!argv.length)process.exitCode=2
102
95
  }
103
96
  }
@@ -162,7 +155,7 @@ async function call(path,body,ticket,signal,origin=api) {
162
155
  const bearer=agentToken!==undefined&&ticket===agentToken
163
156
  const payload=body===undefined?undefined:JSON.stringify(body)
164
157
  if(bearer&&(origin.includes(ticket)||payload?.includes(ticket)))throw Error('account_unavailable')
165
- const response=await fetch(`${origin}/api/cli/${path}`,{redirect:'error',method:body===undefined?'GET':'POST',headers:{...(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)})
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)})
166
159
  const rateLimited=response.status===429
167
160
  const data=await response.json().catch(error=>{
168
161
  if(rateLimited)return null
@@ -185,6 +178,13 @@ async function call(path,body,ticket,signal,origin=api) {
185
178
  }
186
179
  if(bearer&&(!data||typeof data!=='object'||Array.isArray(data)||JSON.stringify(data).includes(ticket)||
187
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
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
189
189
  }
190
190
  const signInConfig = async () => validatedSignInConfig(
@@ -302,7 +302,15 @@ async function logout() {
302
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"})
303
303
  }
304
304
  function starter() {
305
- 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
+ }
306
314
  }
307
315
  async function init() {
308
316
  let handle
@@ -313,22 +321,23 @@ async function init() {
313
321
  const exists=error.code==='EEXIST'
314
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)
315
323
  } finally {if(handle)await handle.close()}
316
- 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.')})
317
325
  }
318
326
  async function submit() {
319
- let copy=submitCopy('Your game'), body, keyPath, keyFolder
327
+ let game='Your game', body, keyPath, keyFolder
320
328
  try {
321
329
  let raw
322
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)}
323
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)}
324
- const {target}=submitInput(body), saved=await load()
325
- copy=submitCopy(target.name)
332
+ const {target,input}=submitInput(body), saved=await load()
333
+ game=target.name
334
+ const vercel=target.hosting==='vercel'
326
335
  const toFile=!process.stdout.isTTY||asJson||keyFile!==undefined
327
336
  const registered=saved.submission?.requestId===body.requestId&&typeof saved.submission.clientId==='string'&&saved.submission.clientId.length>0
328
337
  if(toFile) {
329
338
  keyPath=resolve(keyFile??join(root,'keys',`${target.game_id}-${body.requestId}.key`));keyFolder=dirname(keyPath)
330
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)
331
- if(body.addressReady&&body.game.dnsTarget) {
340
+ if(body.addressReady&&target.dns) {
332
341
  try {
333
342
  // A saved registration can resume with its already delivered key file.
334
343
  // For a new registration, reject every existing entry, including links.
@@ -356,29 +365,64 @@ async function submit() {
356
365
  } else console.log(gameCredential)
357
366
  }
358
367
  let message=safe.message,nextAction
359
- 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}
360
- 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
+ }
361
384
  if(result.status==='operator_needed')nextAction=operator('Inspect this registration before continuing.')
362
385
  output({...safe,...(delivered?{keyFile:delivered}:{}),message,...(nextAction?{nextAction}:{})})
363
386
  process.exitCode={complete:0,address_needed:4,key_needed:5,operator_needed:1}[result.status]??1
364
387
  }
365
388
  if(!await approvals.question(`Turn on FunFab sign-in for ${target.name}? [y/N]`))return
366
- 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)
367
393
  if(reference.status!=='key_needed'||reference.gameCredential||!body.credentialInstalled) {await emit(reference);return}
368
- if(reference.clientId) {saved.submission={requestId:body.requestId,clientId:reference.clientId};await save(saved).catch(()=>{})}
369
- 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
+ }
370
405
  const config=await signInConfig()
371
- 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})
372
407
  }
373
- 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))
374
410
  } catch(error) {
375
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
+ }
376
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}
377
- 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}
378
- const checks=error.message==='game_submit_checks_required'
379
- 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)
380
- 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
381
- 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.'))
382
426
  }
383
427
  }
384
428
  async function gameRead() {
@@ -1 +1,41 @@
1
- export const submitHelp = "## Start a submission\n\nRun `funfab game init my-game.json`. This works offline without signing in and creates a new file with a fresh `requestId`; existing files and links are refused. Keep that request ID for every rerun of this submission. Fill in the placeholders, then run `funfab game submit my-game.json`. The first unfilled field is reported with a correction step. Run `funfab game submit --help` for the field guide.\n\n- `game`: set `game_id`, `name`, `per_play_cost` (whether each play costs money), `retains_account_data` (whether the game keeps account-linked data), and `store_ids` (the game's stores, or an empty array if none). Set `daily_room_quota` when charging per play; otherwise leave it null. Keep `environment: \"preview\"` and `hosting: \"stream\"`. Fill `dnsTarget` with the host target when connecting the address.\n- `title`: set `id`, the displayed `name`, and `launchPath`, the path people use to launch the game.\n- `title.contentDeclaration`: replace each null with an honest content answer; `streamInput` means viewer input can appear on stream. `hostControls` names how the host hides inputs and blocks viewers. The other questions cover sexual content, strong violence, drugs, gambling, strong language, real money and whether the game is aimed at children. Child-directed games need a separate owner decision.\n- `deployment.build`: the commit of the deployment you inspected. Update it if the inspected build changes.\n- `addressReady` and `credentialInstalled`: start false. Submit tells you when to connect the address and install the sign-in key; set each true only after doing that step.\n- `mode`: keep `\"pass\"`. Add `checks` only at the final step, using the checklist below. Never put a sign-in key or ticket in this file.\n\n## Evidence checklist\n\nCollect evidence for the inspected build, then add `checks` to the same file. Use @funfab/sdk/schemas/host-safety for the host-safety result format. Examples below are fictional notes, not evidence to copy as a passing result. Replace `<inspected commit>` with the actual build and confirm only what you tested.\n\n| `checks` part | What it proves | Who produces it | How to get it | Example value |\n| --- | --- | --- | --- | --- |\n| `retention` | Account-linked data can be deleted, or none is kept. | Developer | Review stored data and exercise deletion; record the result or explain why no account data is retained. | `{\"passed\":true,\"evidence\":\"Deletion rehearsal removed the fixture account data\"}` |\n| `viewerDeletion` | A viewer has a working way to request deletion. | Developer | Exercise the viewer deletion route (initially support email) and record the result. | `{\"passed\":true,\"evidence\":\"Support email deletion rehearsal completed\"}` |\n| `accountsTokens` | The game uses the shared sign-in gate and has removed old account/token storage and writers. | Developer using the game's code and migration history | Inspect the gate version, code, migrations and removed writers; record each separately. | `{\"passed\":true,\"gateVersion\":\"ticket-v1\",\"code\":\"Gate integration inspected at build\",\"migrations\":\"Legacy token tables removed\",\"removedWriters\":\"Old token writers removed\"}` |\n| `gate` | The inspected game sends unsigned visitors through the expected sign-in gate. | CLI's anonymous HTTPS gate probe, or developer using existing probe output | For `anonymous_https`, supply the game, host and build binding; the final rerun replaces the gate entry with its probe result. For `attested_probe`, run the existing probe first and reference its output. | `{\"gameId\":\"example-game\",\"host\":\"example-game-preview.funfab.io\",\"build\":\"<inspected commit>\",\"result\":\"gated\",\"method\":\"attested_probe\",\"attested\":true,\"evidence\":\"Probe output: unsigned entry gated at inspected build\"}` |\n| `hostSafety` | Every inspected stream surface filters names and supports viewer blocks. | Game-owned LIVE safety producer (Reverie's tools) | Run the producer for this deployment and copy its attested result, including all inspected surfaces. | `{\"schemaVersion\":1,\"gameId\":\"example-game\",\"build\":\"<inspected commit>\",\"checkVersion\":\"live-v1\",\"result\":\"pass\",\"surfaces\":[{\"surface\":\"host\",\"nameFiltering\":true,\"viewerBlocks\":true}]}` |\n| `confirmedChecks` | You have reviewed the collected evidence for this build. | Developer | Review all five results above, then explicitly confirm at the final step. | `true` |\n\n`funfab game submit submission.json [--json]` is the caller-owned stream prototype\nsubmission on Preview. It works from this repository without CardForge. Sign in and\nactivate the CLI first. A staff member or super-admin owns every game they submit;\nthere is no alternate-owner option. Production refuses the call even if the file\nclaims Preview. \n\nKeep one structured file (correctable before registration) and its UUID `requestId` for every explicit rerun. Supply\n`mode: \"pass\"` (the temporary ticket-mode wire value), `game`, `title` with every\ncontent answer and a non-null validated `launchPath`, and `deployment: {\"build\":\n\"<inspected 40-character commit>\"}`. `game` uses the existing registration fields:\n`game_id`, `environment: \"preview\"`, `hosting: \"stream\"`, `name`, `per_play_cost`,\n`daily_room_quota` when needed, `retains_account_data`, `store_ids`, and `dnsTarget`\nwhen the person has attached the host and received its target. A non-shared store\nmay hold non-account data. Shared/reserved stores, reused stores and retired IDs\nremain refused. The title's `contentDeclaration` answers `streamInput`,\n`hostControls`, `sexualContent`, `strongViolence`, `drugs`, `gambling`,\n`strongLanguage`, `realMoney`, and `childDirected`. All answers are required;\nstream-visible inputs require named host controls. Child-directed games wait for\na separate owner decision; this command has no exception switch.\n\nFirst run with `addressReady: false`. Exit **4** asks the person to connect the\naddress record. Add its declared `dnsTarget`, set `addressReady: true`, then rerun.\nRegistration commits the game, title, encrypted native secret, sign-in-key hash,\naudit and progress together. Exit **5** delivers the sign-in key once. It appears on screen only when stdout is a terminal and `--json` is absent. Otherwise it is written to `<state folder>/keys/<game_id>-<requestId>.key`; JSON and redirected output return only the path. `--key-file PATH` always selects file delivery. The default keys folder is owner-only (0700), the file is owner-only (0600), and existing files are never overwritten. Its folder must be writable and its path must not already exist (including links) before a new registration call. Choose another `--key-file` path if there is a clash. A rerun for the exact request/client reference already saved by the CLI can keep its delivered key file; it is never overwritten. Install it privately at the game's host, then set\n`credentialInstalled: true`. If writing fails after registration, the key is never printed as a fallback: ask an authorized operator to replace it through the existing rotation. The secret-free request/client reference is saved before key delivery, including before a possible key-write failure; state saving remains best effort. Never copy it into the job file or CLI state.\nA first registration always stops at this pause, even if installation was claimed\nin advance. A repeat never returns either key or native client secret again.\n\nThe final rerun supplies `checks` from the OpenAPI schema. Confirm every check with\n`confirmedChecks: true`: retained-data deletion, the viewer deletion route (email\nis the initial route), gate evidence, account sign-in data evidence, and the game-owned\nLIVE host-safety result. For account sign-in data, `gateVersion`, `code`, `migrations` and\n`removedWriters` evidence are separate required fields; the gate version alone\ncannot pass. Missing, stale or failing safety results refuse admission. \nSurface names are unique and nonempty; a passing result requires name filtering\nand viewer blocks on every inspected surface. The producer belongs to Reverie;\nthis command consumes its attested result and does not build a second checker.\n\nFor `gate.method: \"anonymous_https\"`, the CLI anonymously reads the derived host's\n`/healthz` with redirects disabled, keeps only its exact public `build`, and checks\nthe entry's redirect against the existing canonical issuer/client/callback rules.\nNo cookies, provider credentials, provider API reads or authentication addresses\nare recorded. Missing/unknown/`dev` builds, unreachable hosts, provider login pages,\narbitrary redirects and wrong builds fail. If the person must instead use existing\nprobe output, supply `method: \"attested_probe\"`, `attested: true`, `result: \"gated\"`\nand a short output reference bound to the same game, host and inspected build.\nConfirm these checks only after running the probe. Nothing treats failure as a pass.\n\nSuccessful submission returns **0**, with FunFab sign-in on for staff and the\n`not_submitted` game listed as experimental on Preview, so staff can find and\nlaunch it. Initial admission still requires hidden/staff first; only Preview\nsubmit lists it afterward in the same transaction. A completed rerun reports the\ncurrent state; it never switches sign-in back on or changes the listing. Opening an unsubmitted row is refused on every database writer, with one Preview\nexception: an UPDATE to experimental while access stays staff. Production, open\ninserts, featured listing and wider access retain their existing refusals.\nCodes **1**, **2**, and **3** retain failure, invalid input and confirmation meanings.\nChanges ask you in the terminal first. Add --yes to skip the question. Protected CLI state keeps\nonly the existing session and a secret-free request/client reference, never the\nsign-in key, evidence or a confirmation address in saved state. Activation addresses\nare intentionally returned in JSON or manual command output, as with P2; diagnostics\nand evidence never include them. Human address pauses print the validated address record.\n\nIf a response or a newly created native client is uncertain, stop for an authorized\nplatform operator to inspect that exact registration. Reruns stay fenced. A committed\nclient is retained after a lost commit response; a definitely rolled-back SQL attempt\nalone may have its new client cleaned up. No blind deletion or recreation occurs. After a definite SQL rollback and successful\ncleanup, only that exact request/attempt returns to the editable address stage; the\nperson explicitly reruns. Unknown cleanup stays fenced. The current inspected build\ncan change between pauses; gate and LIVE evidence must both match it. Registered\ngame/title/store details remain fixed. Submit alone allows 180 seconds for bounded\nauthentication, registration and outcome/cleanup calls; login and admit keep 10 seconds.\n\n## If the sign-in key is lost\n\nMike or an explicitly authorized platform operator uses\n`createCredentialAdmin` with `createPostgresCredentialStore`, a privileged direct\nPreview database connection and verified operator account ID, to rotate the exact\nstored `credential_id` in `funfab_game_submissions`. Install the replacement privately,\nthen resume the same request. Rotation replaces the hash and audits it atomically;\nthere is no new rotation API, command or hosted setting.\n\nHosted acceptance waits for the game-owned LIVE producer, Reverie's gated-stream\ntwo-deploy-and-rollback proof with rooms/links preserved (cardforge#2315 after #2327),\nthe enrollment freeze in that repository, and the separately approved #373/#368\nhosted window. No source merge or local proof claims those hosted checks passed.\n"
1
+ export const submitSummary = "Register a game you own on FunFab Preview."
2
+ export const submitInitMessage = file => `Created ${file}. This file starts with the stream profile. Fill in the fields, then run funfab game submit ${file}. Run funfab game submit --help for the field guide.`
3
+ export const vercelAddressMessage = host => `Connect ${host} to the game’s Vercel Preview branch. Follow the address steps in funfab game submit --help. After verifying the address, set binding.vercelCname to the assigned target and addressReady to true, then run the same submit command.`
4
+ export const railwayAddressMessage = "Find the CNAME Railway assigns for the shown Preview address. Give the address and target to an authorized FunFab operator through the existing DNS process. Once the address works over HTTPS, set binding.railwayCname to the Railway target and addressReady to true. Run the same submit command."
5
+ export const railwayKeyMessage = "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."
6
+ export const vercelKeyMessage = game => `${game} is registered. Ask an authorized FunFab operator to install the sign-in key privately for the same Vercel Preview branch. Redeploy that branch, set credentialInstalled to true, and run the same submit command.`
7
+ export const upgradeMessage = minimumVersion => `Game submit needs FunFab CLI ${minimumVersion} or later. Run npm install --global @funfab/cli@${minimumVersion}. If this is a new submission with an older starter file, use funfab game init to create a new file and copy your answers before submitting.`
8
+ export const submitRefusal = {
9
+ game_submit_capability_unsupported: "Check the capabilities and their versions against `funfab game submit --help`. Correct the declaration, then run the same submit command.",
10
+ game_submit_capability_required: "Preview web hosting requires sign-in. Paid play also requires hosted rooms. Check that your game declares the capabilities it uses, then run the same submit command.",
11
+ }
12
+ export const fieldGuide = {
13
+ "game": "Set the game slug, name, whether each play costs money, whether the game retains account-linked data, and the stores it uses. Account-linked data requires a non-shared game store. Use an empty store list if the game uses no stores. Keep `environment` set to `preview`.",
14
+ "capabilities": "The stream starter includes all four capabilities with `\"v\": [1]`. For Vercel, keep `sign-in` for FunFab sign-in and remove any of the other entries the game doesn’t use. `hosted-rooms` is for games that create or count rooms. `live-audience` is for games played with a live audience. `host-auth` is for hosts signing in on funfab.io. With paid play, declare `hosted-rooms` and set a positive `capabilities.hosted-rooms.daily_room_quota`.",
15
+ "binding": "Keep `adapter` set to `funfab-web-host`. Set `gate` to `stream` for Railway or `vercel` for Vercel. Add `railwayCname` or `vercelCname` at the address pause for that gate. FunFab supplies the Preview address and sign-in callback.",
16
+ "title": "Set the title slug, display name, and launch path on the game’s Preview address. Keep `transport` set to `funfab-web-host`. Set `action` to `host` for “Host a game” or `play` for “Play”.",
17
+ "title.contentDeclaration": "Answer every question. Set `publicInput` if players’ or viewers’ input can reach others, for example in chat, on stream, or on a leaderboard. If it can, describe how you manage it in `publicInputControls`. Otherwise, use an empty string. The other answers cover sexual content, strong violence, drugs, gambling, strong language, and real money. This command can’t submit a child-directed game. Ask the platform operator if your game is aimed at children.",
18
+ "deployment.build": "Enter the full 40-character commit of the deployment you inspected. Update it and the evidence if the inspected deployment changes.",
19
+ "addressReady and credentialInstalled": "Start with both set to `false`. Set each to `true` only after completing its pause. Keep keys and tickets out of this file.",
20
+ "checks.core": "Record how you tested deletion of retained account-linked data, or why none is kept, in `retention`. Record how you tested the viewer deletion request route in `viewerDeletion`.",
21
+ "checks.capabilities[\"sign-in\"]": "Record the gate version and code you inspected. Show that the game uses the sign-in ticket exchange and that FunFab account tokens never reach it.",
22
+ "checks.capabilities[\"live-audience\"]": "For a live-audience game, include the game’s passing LIVE host-safety result for the inspected commit. It must cover name filtering and viewer blocks on every applicable surface. Use the format in `@funfab/sdk/schemas/host-safety`.",
23
+ "checks.adapter": "Bind the gate check to the exact game, Preview address, and inspected commit. On Railway, serve the build at `/healthz` and the callback at `/auth/funfab/callback`. On Vercel, use `/auth/callback` and put the full build commit in `X-FunFab-Build` on the FunFab authorization redirect. For Vercel, `GET /auth/access-state` must allow `https://preview.funfab.io` in CORS and deny unrelated origins. Choose `anonymous_https` for the CLI probe. If Vercel protection blocks it, ask an authorized operator to run the approved probe and reference its output using `attested_probe`.",
24
+ "checks.confirmedChecks": "Set this to `true` after reviewing every check that applies. Run the same submit command to finish.",
25
+ }
26
+ export const vercelAddressSteps = [
27
+ "Using the developer’s Vercel access, attach this exact address to the game’s Vercel team, project, and Preview Git branch. Check that the branch differs from the Production branch, uses the standard Preview environment, and has no domain redirect.",
28
+ "Find the single rank-1 CNAME assigned by Vercel. Give it and any required verification TXT record to an authorized FunFab operator through the existing DNS process. Wait for the operator to record the change and confirm it is in place.",
29
+ "Verify the branch binding, DNS, and HTTPS for the exact Preview address. Set `binding.vercelCname` to Vercel’s assigned target and `addressReady` to `true`, then run the same submit command with the same file.",
30
+ ].map((step, index) => `${index + 1}. ${step}`).join('\n')
31
+ const fieldLines = checks => Object.entries(fieldGuide)
32
+ .filter(([field]) => field.startsWith('checks.') === checks)
33
+ .map(([field, description]) => `- \`${field}\`: ${description}`)
34
+ export const submitHelp = [
35
+ '## Start a submission', '', "Run `funfab game init submission.json` to create a file offline. Keep its `requestId` and use the same file at each pause. Fill in the details, then run `funfab game submit submission.json` from an active staff CLI session at a terminal.", '',
36
+ ...fieldLines(false), '', '## Confirm the evidence', '', ...fieldLines(true), '',
37
+ '## Vercel address steps', '', vercelAddressSteps, '',
38
+ 'Changes ask you in the terminal first. Add --yes to skip the question.', '',
39
+ 'Exit 5 delivers the sign-in key once. It appears on screen only when stdout is a terminal and --json is absent. Otherwise it is written to <state folder>/keys/<game_id>-<requestId>.key. JSON and redirected output return only the path. --key-file PATH always selects file delivery. Existing files are never overwritten.', '',
40
+ "## If the sign-in key is lost\n\nMike or an explicitly authorized platform operator uses\n`createCredentialAdmin` with `createPostgresCredentialStore`, a privileged direct\nPreview database connection and verified operator account ID, to rotate the exact\nstored `credential_id` in `funfab_game_submissions`. Install the replacement privately,\nthen resume the same request. Rotation replaces the hash and audits it atomically;\nthere is no new rotation API, command or hosted setting."
41
+ ].join('\n')
@@ -0,0 +1,6 @@
1
+ export const vercelProbeRefusal = {
2
+ build: "Check that the Preview address serves your inspected commit and that its FunFab authorization redirect carries the full commit in `X-FunFab-Build`. Run the same submit command after fixing the check.",
3
+ redirect: "Check the Preview address and the game’s FunFab sign-in settings, including the callback. Run the same submit command after fixing the check.",
4
+ protection: "Vercel protection stopped the gate check. Ask an authorized FunFab operator to run the approved probe for this Preview address and inspected commit. Record its output reference in `checks.adapter` with `method` set to `attested_probe`, then run the same submit command.",
5
+ cors: "Set the game’s access-state endpoint to allow `https://preview.funfab.io` and deny unrelated origins. Test both before running the same submit command.",
6
+ }
@@ -1,34 +1,66 @@
1
- // Anonymous, redirect-only HTTPS probe. No provider credentials, cookies or auth
1
+ import {preview} from './origins.mjs'
2
+ import {vercelProbeRefusal} from './submit-probe-copy.mjs'
3
+ import {userAgent} from './version.mjs'
4
+
5
+ async function isJson(response) {
6
+ if(!/^application\/json(?:;|$)/i.test(response.headers.get('content-type')??''))return false
7
+ try {await response.json();return true} catch {return false}
8
+ }
9
+
10
+ // Anonymous HTTPS gate probe. No provider credentials, cookies or auth
2
11
  // URLs leave this process. Unobservable deployment identity is never a pass.
3
12
  export async function probeSubmitGate({target,title,deployment,clientId,authorizationEndpoint,transport=fetch}) {
4
13
  const stop=reason=>{throw Object.assign(Error('game_submit_checks_required'),{reason})}
5
- const request=async url=>{try {return await transport(url,{redirect:'manual',credentials:'omit',headers:{Accept:'text/html'},signal:AbortSignal.timeout(10000)})} catch {stop('The game host could not be reached.')}}
6
- const https=u=>u.protocol==='https:'&&!u.username&&!u.password&&!u.hash&&!u.port
14
+ const vercel=target.hosting==='vercel'
15
+ const redirectWrong=vercel?vercelProbeRefusal.redirect:'The sign-in redirect is wrong. Check its client, callback and response type.'
16
+ const unrelatedOrigin='https://unrelated.example'
17
+ const redirects=[301,302,303,307,308]
18
+ const request=async (url,origin)=>{
19
+ let response
20
+ try {response=await transport(url,{redirect:'manual',credentials:'omit',headers:{Accept:origin?'application/json':'text/html','User-Agent':userAgent,...(origin?{Origin:origin}:{})},signal:AbortSignal.timeout(10000)})}
21
+ catch {stop('The game host could not be reached.')}
22
+ if(vercel&&(response.headers.has('x-vercel-mitigated')||(!origin&&response.status===401)))stop(vercelProbeRefusal.protection)
23
+ return response
24
+ }
25
+ const https=u=>u.protocol==='https:'&&!u.username&&!u.password&&!u.href.includes('#')&&!u.port
7
26
  let stable,auth
8
- try {stable=new URL(target.origin)} catch {stop('The game host must be a Preview funfab.io address.')}
9
- if(!https(stable)||!stable.hostname.endsWith('-preview.funfab.io'))stop('The game host must be a Preview funfab.io address.')
27
+ try {stable=new URL(target.origin)} catch {stop(vercel?redirectWrong:'The game host must be a Preview funfab.io address.')}
28
+ if(!https(stable)||stable.hostname!==`${target.game_id}-preview.funfab.io`||stable.origin!==target.origin||stable.hostname!==target.launch_host)stop(vercel?redirectWrong:'The game host must be a Preview funfab.io address.')
10
29
  try {auth=new URL(authorizationEndpoint)} catch {stop('The sign-in service address is not the expected one.')}
11
30
  // The existing platform /config response supplies this expected issuer.
12
31
  if(!https(auth)||auth.pathname!=='/auth/v1/oauth/authorize'||auth.search)stop('The sign-in service address is not the expected one.')
13
32
  if(!/^[a-f0-9]{40}$/.test(deployment?.build??''))stop('deployment.build must be a 40-character commit hash.')
14
33
  const callback=target.callback
15
- const health=await request(new URL('/healthz',stable))
16
- let data;try {data=await health.json()} catch {stop('The host health response is not JSON.')}
17
- if(health.status!==200||data?.build!==deployment.build)stop('The host is running the wrong build.')
34
+ if(!vercel) {
35
+ const health=await request(new URL('/healthz',stable))
36
+ let data;try {data=await health.json()} catch {stop('The host health response is not JSON.')}
37
+ if(health.status!==200||data?.build!==deployment.build)stop('The host is running the wrong build.')
38
+ }
18
39
  let current=new URL(title.launchPath,stable)
19
40
  for(let hop=0;hop<6;hop++) {
20
- if(current.origin!==stable.origin||!https(current)) stop('The sign-in redirect is wrong. Check its client, callback and response type.')
41
+ if(current.origin!==stable.origin||!https(current)) stop(redirectWrong)
21
42
  const response=await request(current)
22
- if(![301,302,303,307,308].includes(response.status)||!response.headers.get('location'))stop('The game entry did not redirect to sign-in.')
23
- let next;try {next=new URL(response.headers.get('location'),current)} catch {stop('The sign-in redirect is wrong. Check its client, callback and response type.')}
24
- if(!https(next)) stop('The sign-in redirect is wrong. Check its client, callback and response type.')
43
+ if(!redirects.includes(response.status)||!response.headers.get('location'))stop(vercel?redirectWrong:'The game entry did not redirect to sign-in.')
44
+ let next;try {next=new URL(response.headers.get('location'),current)} catch {stop(redirectWrong)}
45
+ if(vercel&&next.hostname==='vercel.com'&&/^\/(?:sso-api|login|oauth)(?:\/|$)/.test(next.pathname))stop(vercelProbeRefusal.protection)
46
+ if(!https(next)) stop(redirectWrong)
25
47
  if(next.origin===auth.origin&&next.pathname===auth.pathname) {
26
48
  const q=next.searchParams
27
- if(q.getAll('client_id').length!==1||q.get('client_id')!==clientId||q.getAll('redirect_uri').length!==1||q.get('redirect_uri')!==callback||q.getAll('response_type').length!==1||q.get('response_type')!=='code') stop('The sign-in redirect is wrong. Check its client, callback and response type.')
28
- return {gameId:target.game_id,host:target.launch_host,build:deployment.build,result:'gated',method:'anonymous_https',attested:true,evidence:'Anonymous HTTPS redirect and public build checked on this machine'}
49
+ if(!clientId||q.getAll('client_id').length!==1||q.get('client_id')!==clientId||q.getAll('redirect_uri').length!==1||q.get('redirect_uri')!==callback||q.getAll('response_type').length!==1||q.get('response_type')!=='code') stop(redirectWrong)
50
+ if(vercel) {
51
+ if(response.headers.get('x-funfab-build')!==deployment.build)stop(vercelProbeRefusal.build)
52
+ const endpoint=new URL('/auth/access-state',stable)
53
+ const allowed=await request(endpoint,preview.website)
54
+ if(allowed.status!==200||allowed.headers.get('access-control-allow-origin')!==preview.website
55
+ ||allowed.headers.get('access-control-allow-credentials')!=='true'
56
+ ||!await isJson(allowed))stop(vercelProbeRefusal.cors)
57
+ const denied=await request(endpoint,unrelatedOrigin)
58
+ if(![200,403].includes(denied.status)||denied.headers.has('access-control-allow-origin')||!await isJson(denied))stop(vercelProbeRefusal.cors)
59
+ }
60
+ return {gameId:target.game_id,host:target.launch_host,build:deployment.build,result:'gated',method:'anonymous_https',attested:true,evidence:vercel?'Anonymous HTTPS redirect, build marker and access-state CORS checked on this machine':'Anonymous HTTPS redirect and public build checked on this machine'}
29
61
  }
30
- if(next.origin!==stable.origin||next.search) stop('The sign-in redirect is wrong. Check its client, callback and response type.')
62
+ if(next.origin!==stable.origin||next.search) stop(redirectWrong)
31
63
  current=next
32
64
  }
33
- stop('The game entry redirected too many times.')
65
+ stop(vercel?redirectWrong:'The game entry redirected too many times.')
34
66
  }
@@ -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.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -15,6 +15,15 @@ steps that need them.
15
15
  - Changes need an agent token. If FUNFAB_TOKEN_FILE isn't set,
16
16
  get one (below). Never print or copy a token file.
17
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
+
18
27
  ## Getting a token (once per game)
19
28
  1. If the person isn't signed in: run funfab login --json and
20
29
  give them the link.
@@ -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
+ }