@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/README.md CHANGED
@@ -1,67 +1,94 @@
1
1
  # FunFab CLI
2
- Manage your FunFab games from a terminal, or let an agent
3
- do it for you with a token.
4
2
 
5
- ## Install
6
- Needs Node.js 22 or newer.
3
+ Let your agent run your FunFab games. You sign in and approve; it does the rest.
7
4
 
8
- ```sh
9
- npx @funfab/cli@0.1.0 --help
10
- npm install --global --save-exact @funfab/cli@0.1.0
11
- ```
5
+ For the FunFab team, on Preview, during this trial. You need a FunFab account with staff access.
12
6
 
13
- ## Sign in
14
- ```sh
15
- funfab login
16
- ```
17
- Your browser opens. Check that the code matches your
18
- terminal, then confirm.
7
+ ## Get started
19
8
 
20
- ## Check and change a game
21
- ```sh
22
- funfab game list
23
- funfab game status emote-defense
24
- funfab game stop emote-defense --reason "Balancing pass"
25
- ```
9
+ Use an agent that can run commands on your computer, such as Claude Code or Codex, and paste this in:
10
+
11
+ > Install the latest FunFab CLI (`npm install --global @funfab/cli@latest`). Install the skill that comes with it: copy the folder `$(npm root -g)/@funfab/cli/skills/funfab` into your skills folder (`~/.claude/skills/` for Claude Code, `~/.codex/skills/` for Codex) and read its `SKILL.md`. Then sign me in to FunFab and give me the link and code to confirm.
12
+
13
+ Your agent runs `funfab login` and gives you a link and a code. Open the link in your own browser, sign in, check the code matches and confirm.
14
+
15
+ **The `funfab` skill** is the only agent skill FunFab ships today. It comes with the CLI and teaches your agent the commands, when to ask you, and what only you can do. Reinstall it whenever you update the CLI, so they stay in step. The FunFab SDK, for building games, has no skill of its own.
16
+
17
+ ## How agent tokens work
18
+
19
+ - **What it is:** a token is a key your agent uses to change your games without asking you each time. It can always see a game's status, setup and requests, and it can only make the changes you approved when it was made: change the game's status, stop and start it, or manage its allow and block lists and requests. A token acts with your account's role and permissions, never more. It has only the powers you approved, and only while your account still has them: if your role or access to a game changes, the token changes with it.
20
+ - **How you get one:** your agent asks for it (`funfab token request`). You approve it in your own browser after checking the powers it asks for. Your agent collects it once, saves it to a private file on your computer, and points `FUNFAB_TOKEN_FILE` at that file. The token's value is never shown, and it can't be shown again.
21
+ - **What it covers:** a game token works on one game. It can have an end date or none, and it stops working if nobody uses it for a year. Staff can also get a token for every game they manage as staff, which lasts 90 days at most.
22
+ - **What still needs you:** signing in, approving a token, registering a new game, and anything about your own account or money. Lifting a hold needs approval from someone who can switch the game off.
23
+ - **See and stop your tokens:** `funfab token list emote-defense` shows a game's tokens. `funfab token revoke emote-defense "Balancing agent"` stops one at once. Staff can stop every agent token with `funfab token kill-switch on --reason "…"`.
24
+ - **If a token file is lost or leaked:** revoke it, then have your agent ask for a new one.
25
+
26
+ ## Ask your agent
27
+
28
+ Emote Defense is an example game. Use your own game's name; your agent finds its ID with `funfab game list`.
29
+
30
+ | You say | Your agent runs | You do |
31
+ | --- | --- | --- |
32
+ | "List my FunFab games." | `funfab game list` | nothing |
33
+ | "How is Emote Defense doing?" | `funfab game status emote-defense` | nothing |
34
+ | "Get a token for Emote Defense that can stop and start it." | `funfab token request emote-defense --name "…" --allow stop-start` | approve it in your browser |
35
+ | "Stop Emote Defense. Reason: balancing pass." | `funfab game stop emote-defense --reason "…"` | nothing |
36
+ | "Start Emote Defense again." | `funfab game start emote-defense --reason "…"` | nothing |
37
+ | "Show Emote Defense's access requests." | `funfab game requests emote-defense` | nothing |
38
+ | "Approve that request." | `funfab game requests emote-defense --answer ID --approve --reason "…"` | nothing |
39
+ | "Add this account to Emote Defense's allow list." | `funfab game allow emote-defense ACCOUNT --reason "…"` | nothing |
40
+ | "Block this account from Emote Defense." | `funfab game block emote-defense ACCOUNT --reason "…"` | nothing |
41
+ | "Put Emote Defense on hold." | `funfab game hold emote-defense --reason "…"` | nothing |
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
+ | "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 | answer submit's question in your terminal if your agent asks you to |
45
+
46
+ If a change needs a power your token doesn't have, your agent asks you for a new token with it.
47
+
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
+
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
+
60
+ ## Approving safely
61
+
62
+ - Approve only if you were expecting this request.
63
+ - Check this code matches the one the agent showed.
64
+ - If you didn't start it yourself, first check the exact action, game, reason and code with the token's maker, through a channel you already trust, not the message this link came in.
65
+ - Use your own browser profile, never one an agent controls.
66
+
67
+ ## Stop it at any time
26
68
 
27
- Changes ask you in the terminal first. Add --yes to skip
28
- the question. High-stakes changes, like turning on FunFab
29
- sign-in for a game, also ask you to confirm it's you in your
30
- browser, once an hour.
31
-
32
- ## Lifting a hold or creating a token: confirm that one action
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.
38
-
39
- ## Let an agent work for you
40
- Coming soon.
41
- 1. Create a token that allows only what the agent needs:
42
- funfab token create emote-defense --name "Balancing agent" --allow stop-start
43
- 2. Give the agent the file the command printed:
44
- export FUNFAB_TOKEN_FILE=~/.config/funfab/tokens/preview/…
45
- 3. The agent runs funfab commands. It can do only what the
46
- token allows, and every change is logged and sent to
47
- the game's owner.
48
-
49
- Stop it at any time:
50
69
  ```sh
51
70
  funfab token revoke emote-defense "Balancing agent"
71
+ funfab token kill-switch on --reason "Incident"
52
72
  ```
53
73
 
54
- An agent can't use your own sign-in. Changes run without a
55
- terminal are refused, even with --yes.
74
+ `funfab logout` signs this computer out.
75
+
76
+ ## Install
77
+ Needs Node.js 22 or newer. Replace `VERSION` with the exact release you want to install.
78
+
79
+ ```sh
80
+ npx @funfab/cli@VERSION --help
81
+ npm install --global --save-exact @funfab/cli@VERSION
82
+ ```
56
83
 
57
84
  ## For scripts
58
85
  Add --json to any command. Exit codes: 0 done, 1 failed,
59
- 2 wrong command or setting, 3 needs a person,
86
+ 2 wrong command, setting or token file, 3 needs a person,
60
87
  4 and 5 pauses during submit.
61
88
 
62
89
  ## Versions
63
- This is a trial (0.x). Pin an exact version. The previous
64
- 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.
65
92
 
66
93
  ## Help
67
94
  ```sh
package/cli/approvals.mjs CHANGED
@@ -2,23 +2,23 @@ import {createInterface} from 'node:readline/promises'
2
2
  import {setTimeout as delay} from 'node:timers/promises'
3
3
  import {isConfirmationAddress} from './origins.mjs'
4
4
 
5
- export const terminalRequired=Object.freeze({error:'terminal_required',nextAction:{kind:'command',command:'funfab token create'}})
6
5
  export const terminalMessage='This change needs a person at a terminal. Run the command yourself in a terminal.'
6
+ export const terminalRequired=Object.freeze({error:'terminal_required',nextAction:{kind:'person',instruction:terminalMessage}})
7
7
  export const malformedConfirmation=()=>{throw Object.assign(Error('account_unavailable'),{malformedConfirmation:true})}
8
- export const writePauseStatuses=['activation_needed','sudo_needed','action_confirmation_needed']
8
+ const writePauseStatuses=['activation_needed','sudo_needed']
9
9
 
10
- export function createApprovals({call,output,openBrowser,allowLoopback=false,asJson=false,yes=false,tokenAdvice,input=process.stdin,out=process.stdout,now=Date.now,sleep=delay}) {
10
+ export function createApprovals({call,output,openBrowser,allowLoopback=false,asJson=false,yes=false,input=process.stdin,out=process.stdout,now=Date.now,sleep=delay}) {
11
11
  const terminal=Boolean(input.isTTY&&out.isTTY)
12
12
  const emit=(value,message)=>output({...value,...(!asJson?{message}:{})})
13
13
  const next=url=>({kind:'open_url',url})
14
- function requireTerminal() {
15
- if(!terminal||(asJson&&!yes))throw Object.assign(Error('terminal_required'),{...terminalRequired,display:asJson?undefined:terminalMessage+(tokenAdvice?'\n'+tokenAdvice:''),exit:3})
14
+ function requireTerminal({allowJson=false}={}) {
15
+ if(!terminal||(asJson&&!yes&&!allowJson))throw Object.assign(Error('terminal_required'),{...terminalRequired,display:asJson?undefined:terminalMessage,exit:3})
16
16
  }
17
- async function question(prompt,gameId) {
18
- requireTerminal()
17
+ async function question(prompt,gameId,{allowJson=false}={}) {
18
+ requireTerminal({allowJson})
19
19
  if(asJson&&gameId)throw Object.assign(Error('terminal_required'),{...terminalRequired,exit:3})
20
20
  if(yes&&!gameId)return true
21
- const rl=createInterface({input,output:out,crlfDelay:Infinity})
21
+ const rl=createInterface({input,output:asJson&&allowJson?process.stderr:out,crlfDelay:Infinity})
22
22
  try {
23
23
  if(!yes&&(await rl.question(prompt+' '))!=='y') {emit({status:'cancelled'},'Nothing changed.');return false}
24
24
  if(gameId&&(await rl.question(`Type ${gameId} to confirm: `))!==gameId) {emit({status:'cancelled'},`That didn't match ${gameId}. Nothing changed.`);return false}
@@ -26,19 +26,17 @@ export function createApprovals({call,output,openBrowser,allowLoopback=false,asJ
26
26
  } catch(error) {if(error.name!=='AbortError')throw error;emit({status:'cancelled'},'Nothing changed.');return false}
27
27
  finally {rl.close()}
28
28
  }
29
- async function wait(ticket,pause,{activation=false,opened=false,signIn=false,signal,needsAction,pendingOnly=false,beforeWait}={}) {
29
+ async function wait(ticket,pause,{activation=false,opened=false,signIn=false,signal,pendingOnly=false,beforeWait}={}) {
30
30
  const {confirmationUrl:url,requestId,code,interval=5,expiresAt}=pause
31
31
  if (!isConfirmationAddress(url,requestId,allowLoopback)) return malformedConfirmation()
32
32
  if(!/^[A-Za-z0-9_-]{43}$/.test(requestId??'')||!/^[A-Z0-9]{4}$/.test(code??'')||!Number.isInteger(interval)||interval<5||!Number.isFinite(Date.parse(expiresAt)))return malformedConfirmation()
33
33
  await beforeWait?.(url)
34
- const action=pause.status==='action_confirmation_needed'
35
- const safe={status:action?pause.status:activation?'activation_needed':'sudo_needed',confirmationUrl:url,requestId,code,interval,expiresAt,nextAction:next(url)}
34
+ const safe={status:activation?'activation_needed':'sudo_needed',confirmationUrl:url,requestId,code,interval,expiresAt,nextAction:next(url)}
35
+ const matchCode=`Check the code matches: ${code}`
36
36
  if(asJson||!terminal||pendingOnly) {
37
- output(pendingOnly&&!asJson&&terminal?{...safe,message:url}:safe)
37
+ output(pendingOnly&&!asJson&&terminal?{...safe,message:`Open this address in your browser. ${matchCode}\n${url}`}:safe)
38
38
  process.exitCode=3;return false
39
39
  }
40
- if(action&&needsAction)emit({status:safe.status},needsAction)
41
- const matchCode=`Check the code matches: ${code}`
42
40
  const browserOpened=opened||await openBrowser(url)
43
41
  emit(safe,browserOpened?`Opening your browser${signIn?' to sign in':''}. ${matchCode}`:`Open this address in your browser. ${matchCode}`)
44
42
  if(!browserOpened)emit(safe,url)
@@ -61,8 +59,8 @@ export function createApprovals({call,output,openBrowser,allowLoopback=false,asJ
61
59
  }
62
60
  if(combined.aborted||now()>=deadline)break
63
61
  if(!state||!['pending','confirmed','cancelled','expired'].includes(state.status)||state.code!==code||!Number.isInteger(state.interval??5)||(state.interval??5)<5||!Number.isFinite(Date.parse(state.expiresAt)))return malformedConfirmation()
64
- if(state.status==='confirmed') {if(!action)emit({status:'confirmed'},activation?'Confirmed.':"Confirmed. High-stakes commands won't ask again for an hour.");return true}
65
- if(state.status==='cancelled') {emit({status:'cancelled'},action?'Cancelled. Nothing changed.':'You chose "No, this isn\'t me" in your browser. Nothing changed.');process.exitCode=1;return false}
62
+ if(state.status==='confirmed') {emit({status:'confirmed'},activation?'Confirmed.':"Confirmed. High-stakes commands won't ask again for an hour.");return true}
63
+ if(state.status==='cancelled') {emit({status:'cancelled'},'You chose "No, this isn\'t me" in your browser. Nothing changed.');process.exitCode=1;return false}
66
64
  if(state.status==='expired'){expired=true;break}
67
65
  seconds=Math.max(seconds,state.interval??5)
68
66
  }
@@ -73,7 +71,7 @@ export function createApprovals({call,output,openBrowser,allowLoopback=false,asJ
73
71
  emit({error:'confirmation_expired',nextAction:{kind:'command',command:'funfab '+process.argv.slice(2).map(arg=>"'"+arg.replaceAll("'", "'\\''")+"'").join(' ')}},"You didn't confirm in your browser in time. Nothing changed. Run the command again to try again.")
74
72
  process.exitCode=1;return false
75
73
  }
76
- async function write(path,body,saved,{prompt,destructive,needs,needsAction}={}) {
74
+ async function write(path,body,saved,{prompt,destructive,needs}={}) {
77
75
  requireTerminal()
78
76
  if(!await question(prompt,destructive))return null
79
77
  const approvedIn=yes?'yes':'terminal',input={...body,approvedIn}
@@ -82,9 +80,9 @@ export function createApprovals({call,output,openBrowser,allowLoopback=false,asJ
82
80
  if(!await wait(saved.ticket,result,{activation:true}))return null
83
81
  result=await call(path,input,saved.ticket)
84
82
  }
85
- if(result.status==='sudo_needed'||result.status==='action_confirmation_needed') {
86
- if(result.status==='sudo_needed'&&needs&&!asJson)emit({status:'sudo_needed'},needs)
87
- if(!await wait(saved.ticket,result,{needsAction}))return null
83
+ if(result.status==='sudo_needed') {
84
+ if(needs&&!asJson)emit({status:'sudo_needed'},needs)
85
+ if(!await wait(saved.ticket,result))return null
88
86
  // The pause proves that no write ran. This is the one first execution, not a
89
87
  // transport retry. A thrown/uncertain sent write is never retried here.
90
88
  result=await call(path,input,saved.ticket)
@@ -0,0 +1,63 @@
1
+ import {constants} from 'node:fs'
2
+ import {open} from 'node:fs/promises'
3
+ import {privateFilesSupported} from './private-directory.mjs'
4
+
5
+ export const safeCredentialDiagnostic = value => value.replace(/ffgt_[a-z]+_[A-Za-z0-9_-]{43}/gi, '[redacted]').replace(/[\x00-\x1f\x7f-\x9f]/g, char => JSON.stringify(char).slice(1,-1))
6
+
7
+ export async function readAgentToken(path, environment) {
8
+ try {
9
+ if (!privateFilesSupported || !constants.O_NONBLOCK) throw Error()
10
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
11
+ try {
12
+ const stat = await handle.stat()
13
+ const prefix = `ffgt_${environment.id}_`
14
+ const length = prefix.length + 43
15
+ if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o7177) || !(stat.mode & 0o400)) throw Error()
16
+ // Keep one extra byte beyond the maximum valid length to detect trailing data.
17
+ const buffer = Buffer.alloc(length + 2)
18
+ let size = 0
19
+ while (size < buffer.length) {
20
+ const {bytesRead} = await handle.read(buffer, size, buffer.length - size, null)
21
+ if (!bytesRead) break
22
+ size += bytesRead
23
+ }
24
+ const value = buffer.subarray(0, size).toString('utf8')
25
+ const token = value.endsWith('\n') ? value.slice(0, -1) : value
26
+ if (token.length !== length || !token.startsWith(prefix) || /[^A-Za-z0-9_-]/.test(token)) throw Error()
27
+ return token
28
+ } finally {
29
+ await handle.close()
30
+ }
31
+ } catch {
32
+ const shown = safeCredentialDiagnostic(path)
33
+ const display = `The token file can't be used: ${shown}. It has to be a file only you can read, holding one FunFab token for ${environment.label}. Ask the token's maker to check it, or to revoke that token and make a new one.`
34
+ throw Object.assign(Error('token_file_invalid'), {display, nextAction:{kind:'person',instruction:display}, exit:2})
35
+ }
36
+ }
37
+
38
+ export function tokenRefusal(error, environment, power, game, starting) {
39
+ const {message: code, httpStatus} = error
40
+ const askMaker = "Ask the token's maker for a new one."
41
+ if (httpStatus === 401) return {
42
+ __proto__: null,
43
+ authorization_required: `FunFab doesn't recognise this token on ${environment.label}. ${askMaker}`,
44
+ delegate_token_expired: `This token has ended. ${askMaker}`,
45
+ delegate_token_revoked: `This token was revoked. ${askMaker}`,
46
+ delegate_token_inactive: `This token stopped working because nobody used it for a year. ${askMaker}`
47
+ }[code]
48
+ if (httpStatus !== 403) return
49
+ const name = game?.name ?? 'that game'
50
+ const capability = {
51
+ status: `change ${name}'s status`,
52
+ 'stop-start': `stop or start ${name}`,
53
+ access: `change ${name}'s allow and block lists or answer its requests`
54
+ }[power]
55
+ return {
56
+ __proto__: null,
57
+ delegate_tokens_disabled: `Agent tokens are switched off on ${environment.label} right now. Ask staff.`,
58
+ delegate_token_scope_denied: "This token can't be used on that game. Ask the token's maker for a token for it.",
59
+ delegate_token_permission_denied: capability && `This token can't ${capability}. Ask the person who made it for a token that can.`,
60
+ game_permission_denied: "The person who made this token can't make this change any more. Ask them or staff.",
61
+ game_switch_off_held: game && starting && `${name} is on hold. Lifting it needs approval from someone who can switch the game off. To ask: funfab game unhold ${game.gameId} --reason "…"`
62
+ }[code]
63
+ }