@funfab/cli 0.2.0 → 0.3.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/approvals.mjs +5 -6
- package/cli/attempt.mjs +0 -2
- package/cli/funfab.mjs +74 -28
- package/cli/origins.mjs +34 -0
- package/cli/private-directory.mjs +18 -0
- package/cli/tokens.mjs +16 -21
- package/package.json +1 -1
package/cli/approvals.mjs
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import {createInterface} from 'node:readline/promises'
|
|
2
2
|
import {setTimeout as delay} from 'node:timers/promises'
|
|
3
|
+
import {isConfirmationAddress} from './origins.mjs'
|
|
3
4
|
|
|
4
5
|
export const terminalRequired=Object.freeze({error:'terminal_required',nextAction:{kind:'command',command:'funfab token create'}})
|
|
5
6
|
export const terminalMessage='This change needs a person at a terminal. Run the command yourself in a terminal.'
|
|
6
7
|
export const malformedConfirmation=()=>{throw Object.assign(Error('account_unavailable'),{malformedConfirmation:true})}
|
|
7
8
|
export const writePauseStatuses=['activation_needed','sudo_needed','action_confirmation_needed']
|
|
8
9
|
|
|
9
|
-
export function createApprovals({call,output,openBrowser,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,tokenAdvice,input=process.stdin,out=process.stdout,now=Date.now,sleep=delay}) {
|
|
10
11
|
const terminal=Boolean(input.isTTY&&out.isTTY)
|
|
11
12
|
const emit=(value,message)=>output({...value,...(!asJson?{message}:{})})
|
|
12
13
|
const next=url=>({kind:'open_url',url})
|
|
@@ -25,13 +26,11 @@ export function createApprovals({call,output,openBrowser,asJson=false,yes=false,
|
|
|
25
26
|
} catch(error) {if(error.name!=='AbortError')throw error;emit({status:'cancelled'},'Nothing changed.');return false}
|
|
26
27
|
finally {rl.close()}
|
|
27
28
|
}
|
|
28
|
-
async function wait(ticket,pause,{activation=false,opened=false,signIn=false,signal,needsAction,pendingOnly=false}={}) {
|
|
29
|
+
async function wait(ticket,pause,{activation=false,opened=false,signIn=false,signal,needsAction,pendingOnly=false,beforeWait}={}) {
|
|
29
30
|
const {confirmationUrl:url,requestId,code,interval=5,expiresAt}=pause
|
|
30
|
-
if
|
|
31
|
-
let target
|
|
32
|
-
try {target=new URL(url)} catch {return malformedConfirmation()}
|
|
33
|
-
if(!(target.protocol==='https:'||(target.protocol==='http:'&&['127.0.0.1','localhost','[::1]'].includes(target.hostname))))return malformedConfirmation()
|
|
31
|
+
if (!isConfirmationAddress(url,requestId,allowLoopback)) return malformedConfirmation()
|
|
34
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
|
+
await beforeWait?.(url)
|
|
35
34
|
const action=pause.status==='action_confirmation_needed'
|
|
36
35
|
const safe={status:action?pause.status:activation?'activation_needed':'sudo_needed',confirmationUrl:url,requestId,code,interval,expiresAt,nextAction:next(url)}
|
|
37
36
|
if(asJson||!terminal||pendingOnly) {
|
package/cli/attempt.mjs
CHANGED
|
@@ -35,8 +35,6 @@ export function createAttempt({redirectUri, now=Date.now} = {}) {
|
|
|
35
35
|
|
|
36
36
|
export function authorizationURL({authOrigin,clientId,attempt}) {
|
|
37
37
|
const origin=new URL(authOrigin)
|
|
38
|
-
if (origin.origin!==authOrigin || !['https:','http:'].includes(origin.protocol) ||
|
|
39
|
-
(origin.protocol==='http:' && !['localhost','127.0.0.1','[::1]'].includes(origin.hostname))) throw new Error('invalid_configuration')
|
|
40
38
|
const url=new URL('/auth/v1/oauth/authorize',origin)
|
|
41
39
|
url.search=new URLSearchParams({client_id:clientId,redirect_uri:attempt.redirectUri,response_type:'code',scope:'email offline_access',state:attempt.state,code_challenge_method:'S256',code_challenge:attempt.challenge}).toString()
|
|
42
40
|
return url.href
|
package/cli/funfab.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import {createServer} from 'node:http'
|
|
|
4
4
|
import {spawn} from 'node:child_process'
|
|
5
5
|
import {createInterface} from 'node:readline/promises'
|
|
6
6
|
import {Writable} from 'node:stream'
|
|
7
|
+
import {constants} from 'node:fs'
|
|
7
8
|
import {mkdir,readFile,open,rename,unlink,chmod,lstat} from 'node:fs/promises'
|
|
8
9
|
import {randomBytes,randomUUID} from 'node:crypto'
|
|
9
10
|
import {homedir} from 'node:os'
|
|
@@ -13,6 +14,8 @@ import {probeSubmitGate} from './submit-probe.mjs'
|
|
|
13
14
|
import {CALLBACKS,createAttempt,authorizationURL} from './attempt.mjs'
|
|
14
15
|
import {tokenCommands,tokenIntent,runToken} from './tokens.mjs'
|
|
15
16
|
import {createApprovals,terminalMessage,alignedRows,malformedConfirmation,writePauseStatuses} from './approvals.mjs'
|
|
17
|
+
import {apiAddress,preview,validatedSignInConfig} from './origins.mjs'
|
|
18
|
+
import {privateDirectories,privateFilesSupported} from './private-directory.mjs'
|
|
16
19
|
|
|
17
20
|
if(Number(process.versions.node.split('.')[0])<22) {
|
|
18
21
|
console.error('FunFab needs Node.js 22 or newer. Upgrade Node.js, then run funfab again.')
|
|
@@ -21,15 +24,21 @@ if(Number(process.versions.node.split('.')[0])<22) {
|
|
|
21
24
|
const argv=process.argv.slice(2), asJson=argv.includes('--json'), noBrowser=argv.includes('--no-browser'), yes=argv.includes('--yes')
|
|
22
25
|
const keyIndex=argv.indexOf('--key-file'), keyFile=keyIndex<0?undefined:argv[keyIndex+1]
|
|
23
26
|
const args=argv.filter((x,i)=>!['--json','--no-browser','--help','--version','--yes'].includes(x)&&(keyIndex<0||(i!==keyIndex&&i!==keyIndex+1)))
|
|
24
|
-
const
|
|
27
|
+
const print=value=>console.log(asJson?JSON.stringify(value):value.message??JSON.stringify(value))
|
|
25
28
|
const commandAction=command=>({kind:'command',command})
|
|
26
29
|
const person=instruction=>({kind:'person',instruction})
|
|
27
30
|
const operator=instruction=>({kind:'operator',instruction})
|
|
31
|
+
const operatorFailure=['The command could not be completed. Ask an authorized operator to inspect it before continuing.',operator('Inspect the failed command before continuing.')]
|
|
28
32
|
const edit=(field,value,instruction)=>({kind:'edit_field',field,...(value===undefined?{}:{value}),instruction})
|
|
29
33
|
const problem=(error,message,nextAction,exit=1)=>Object.assign(Error(error),{display:message,nextAction,exit})
|
|
30
34
|
const fail=(error,message,nextAction,code=1,reason)=>{output({error,...(reason?{reason}:{}),...(asJson&&error==='terminal_required'?{}:{message}),nextAction});process.exitCode=code}
|
|
31
|
-
const
|
|
32
|
-
const
|
|
35
|
+
const base=resolve(process.env.XDG_CONFIG_HOME||homedir()), root=join(base,'.funfab'), file=join(root,'cli.json')
|
|
36
|
+
const address=apiAddress(process.env.FUNFAB_CLI_API_URL,process.env.FUNFAB_CLI_ALLOW_CUSTOM_API)
|
|
37
|
+
if(address?.custom)console.error(`Using a custom API address: ${address.origin}`)
|
|
38
|
+
const output=value=>{
|
|
39
|
+
if(Object.hasOwn(value,'confirmationUrl'))return malformedConfirmation()
|
|
40
|
+
print(value)
|
|
41
|
+
}
|
|
33
42
|
const commands=[
|
|
34
43
|
...tokenCommands.map(c=>({...c,run:tokenCommand})),
|
|
35
44
|
{command:'whoami',arguments:'',description:'Show your account, confirmation and session limits',example:'funfab whoami',next:'Run funfab login to start a new confirmation if still waiting.',run:whoami,count:1},
|
|
@@ -52,7 +61,7 @@ if(command?.run===gameWrite||command?.command==='game requests'&&args.includes('
|
|
|
52
61
|
try {writeIntent();writeUsage=true} catch {}
|
|
53
62
|
}
|
|
54
63
|
const isWrite=command?.run===gameWrite||command?.command==='game requests'&&args.includes('--answer')
|
|
55
|
-
const help={commands:commands.map(({run,count,...entry})=>entry),flags:{'--help':'Show help for this command','--version':'Show the version','--json':'Print JSON','--yes':'Skip the question from a terminal','--no-browser':'Print the link instead of opening a browser','--key-file PATH':'Write the sign-in key to a new private file'},settings:{FUNFAB_CLI_API_URL
|
|
64
|
+
const help={commands:commands.map(({run,count,...entry})=>entry),flags:{'--help':'Show help for this command','--version':'Show the version','--json':'Print JSON','--yes':'Skip the question from a terminal','--no-browser':'Print the link instead of opening a browser','--key-file PATH':'Write the sign-in key to a new private file'},settings:{FUNFAB_CLI_API_URL:`Accounts API HTTPS origin; default ${preview.api}`},exitCodes:{0:'Done',1:'Failed',2:'Check the command or settings',3:'Needs a person or browser confirmation',4:'Connect the game address, then run the same command again',5:'Install the game sign-in key, then run the same command again'}}
|
|
56
65
|
const fieldGuide={
|
|
57
66
|
game:'Registration details: fill in the game ID, name, charging, data stores and host target before submitting.',
|
|
58
67
|
title:'Catalog identity and launchPath: fill in before submitting.',
|
|
@@ -76,41 +85,74 @@ let usageOK=true
|
|
|
76
85
|
if(!informational&&(!command?.run||(command.run===tokenCommand?!tokenUsage:isWrite?!writeUsage:!(args.length===command.count||(command.command==='game requests'&&args.length===5&&args[3]==='--before'))||(command.command==='game admit'&&!['on','off'].includes(args[3]))||args.some((x,i)=>x.startsWith('--')&&!(command.command==='game requests'&&i===3&&x==='--before')))||(keyIndex>=0&&(!keyFile||keyFile.startsWith('--')||command.command!=='game submit'||argv.lastIndexOf('--key-file')!==keyIndex)))) {
|
|
77
86
|
usageOK=false;fail('command_invalid','Check the command and its arguments. Run funfab --help for examples.',commandAction('funfab --help'),2)
|
|
78
87
|
}
|
|
79
|
-
|
|
80
|
-
if(!informational&&usageOK
|
|
88
|
+
const api=!informational&&usageOK&&command.command!=='game init'?address?.origin:undefined
|
|
89
|
+
if(!api&&!informational&&usageOK&&!['game init','logout'].includes(command.command)) {
|
|
90
|
+
const message="FUNFAB_CLI_API_URL isn't a FunFab API address. To use another address for testing, also set FUNFAB_CLI_ALLOW_CUSTOM_API=1."
|
|
91
|
+
fail('configuration_invalid',message,person(message),2)
|
|
92
|
+
}
|
|
93
|
+
const privateStateError=()=>problem('cli_state_not_private',"Your saved sign-in isn't private. Run funfab logout, then funfab login.",commandAction('funfab logout'))
|
|
94
|
+
async function checkStateDirectory(create=false) {
|
|
95
|
+
// Windows keeps the previous state handling until the CLI supports Windows permissions.
|
|
96
|
+
if(!privateFilesSupported)return create?mkdir(root,{recursive:true,mode:0o700}):undefined
|
|
97
|
+
try {await privateDirectories(base,[root],{create})} catch(error) {
|
|
98
|
+
if(error.code==='ENOENT')throw error
|
|
99
|
+
if(error.path===base)throw Object.assign(problem('cli_state_not_private',...operatorFailure),{unsafeStateDirectory:true})
|
|
100
|
+
const path=process.env.XDG_CONFIG_HOME?root:'~/.funfab'
|
|
101
|
+
const message=`Your FunFab settings folder isn't private: ${path}. Remove it, then run funfab login.`
|
|
102
|
+
throw Object.assign(problem('cli_state_not_private',message,person(message)),{unsafeStateDirectory:true})
|
|
103
|
+
}
|
|
104
|
+
}
|
|
81
105
|
const save=async value=>{
|
|
82
106
|
try {
|
|
83
|
-
await
|
|
107
|
+
await checkStateDirectory(true)
|
|
84
108
|
const temp=join(root,`.cli-${randomBytes(16).toString('hex')}`)
|
|
85
109
|
let handle
|
|
86
110
|
try {
|
|
87
111
|
handle=await open(temp,'wx',0o600)
|
|
112
|
+
if(privateFilesSupported)await handle.chmod(0o600)
|
|
88
113
|
await handle.writeFile(JSON.stringify(value)); await handle.close(); handle=null
|
|
89
114
|
await rename(temp,file)
|
|
90
115
|
} finally {if(handle) await handle.close(); await unlink(temp).catch(()=>{})}
|
|
91
|
-
} catch {throw problem('cli_state_unwritable','The saved sign-in could not be written. Make the CLI state folder writable, then run funfab login.',person('Make the CLI state folder writable, then run funfab login.'))}
|
|
116
|
+
} catch(error) {if(error.display)throw error;throw problem('cli_state_unwritable','The saved sign-in could not be written. Make the CLI state folder writable, then run funfab login.',person('Make the CLI state folder writable, then run funfab login.'))}
|
|
92
117
|
}
|
|
93
118
|
const load=async()=>{
|
|
94
119
|
let raw
|
|
95
|
-
try {
|
|
120
|
+
try {
|
|
121
|
+
await checkStateDirectory()
|
|
122
|
+
const flags=privateFilesSupported?constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK:'r'
|
|
123
|
+
const handle=await open(file,flags).catch(error=>{
|
|
124
|
+
if(privateFilesSupported&&['ELOOP','EMLINK','EACCES','EPERM','ENXIO'].includes(error.code))throw privateStateError()
|
|
125
|
+
throw error
|
|
126
|
+
})
|
|
127
|
+
try {
|
|
128
|
+
if(privateFilesSupported) {
|
|
129
|
+
const stat=await handle.stat()
|
|
130
|
+
if(!stat.isFile()||stat.uid!==process.getuid()||(stat.mode&0o077))throw privateStateError()
|
|
131
|
+
}
|
|
132
|
+
raw=await handle.readFile('utf8')
|
|
133
|
+
} finally {await handle.close()}
|
|
134
|
+
} catch(error) {
|
|
135
|
+
if(error.display)throw error
|
|
96
136
|
if(error.code==='ENOENT')throw problem('authorization_required',"You're not signed in. Run funfab login.",commandAction('funfab login'))
|
|
97
137
|
throw problem('cli_state_unreadable','The saved sign-in cannot be read. Check the CLI state file permissions, then run funfab login.',person('Check the CLI state file permissions, then run funfab login.'))
|
|
98
138
|
}
|
|
99
139
|
try {const saved=JSON.parse(raw);if(!saved||typeof saved.ticket!=='string'||!saved.ticket)throw Error();return saved} catch {throw problem('cli_state_corrupt','The saved sign-in is damaged. Run funfab login to replace it.',commandAction('funfab login'))}
|
|
100
140
|
}
|
|
101
|
-
async function call(path,body,ticket,signal) {
|
|
141
|
+
async function call(path,body,ticket,signal,origin=api) {
|
|
102
142
|
const actionConfirmation=path==='token/create'||path==='game/action'&&body?.operation?.action==='unhold'
|
|
103
|
-
const response=await fetch(`${
|
|
143
|
+
const response=await fetch(`${origin}/api/cli/${path}`,{redirect:'error',method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{'Content-Type':'application/json'}),...(actionConfirmation?{'FunFab-CLI-Action-Confirmation':'1'}:{}),...(ticket?{Authorization:`Bearer ${ticket}`}:{})},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:signal?AbortSignal.any([signal,AbortSignal.timeout(10000)]):AbortSignal.timeout(path==='submit'?180000:10000)})
|
|
104
144
|
const data=await response.json()
|
|
105
145
|
if(data?.status==='action_confirmation_needed'&&(!actionConfirmation||response.status!==202))return malformedConfirmation()
|
|
106
146
|
if(actionConfirmation&&response.status===202&&!writePauseStatuses.includes(data?.status))return malformedConfirmation()
|
|
107
147
|
if(!response.ok) throw Object.assign(Error(data.error??'account_unavailable'),(path.startsWith('game/')||path.startsWith('token/')||path==='confirm-request')&&['game_request_invalid','game_request_conflict'].includes(data.error)&&['input_invalid','cursor_invalid','expiry_elapsed','consumed','answered','invalidated'].includes(data.reason)?{reason:data.reason}:{});return data
|
|
108
148
|
}
|
|
149
|
+
const signInConfig = async () => validatedSignInConfig(
|
|
150
|
+
await call('config'), address, () => call('config',undefined,undefined,undefined,preview.api))
|
|
109
151
|
const terminal=Boolean(process.stdin.isTTY&&process.stdout.isTTY&&!asJson)
|
|
110
152
|
const personWrite=isWrite||['game submit','game admit','token create','token revoke','token kill-switch'].includes(command?.command)
|
|
111
153
|
const tokenTick=args[0]==='game'?({'set-status':'status',stop:'stop-start',start:'stop-start',allow:'access',block:'access',requests:args.includes('--answer')?'access':null}[args[1]]):null
|
|
112
154
|
const tokenAdvice=tokenTick&&/^[a-z0-9]+(-[a-z0-9]+)*$/.test(args[2]??'')?`To let an agent or script do it, create a token: funfab token create ${args[2]} --name \"…\" --allow ${tokenTick}`:undefined
|
|
113
|
-
const approvals=createApprovals({call,output,tokenAdvice,openBrowser:async url=>!noBrowser&&await openBrowser(url),asJson,yes})
|
|
155
|
+
const approvals=createApprovals({call,output:print,tokenAdvice,allowLoopback:address?.loopback,openBrowser:async url=>!noBrowser&&await openBrowser(url),asJson,yes})
|
|
114
156
|
const interactiveBrowser=terminal&&!noBrowser
|
|
115
157
|
const browserCommand=process.platform==='darwin'?'open':process.platform==='win32'?null:'xdg-open'
|
|
116
158
|
function openBrowser(url) {
|
|
@@ -151,11 +193,12 @@ async function listen() {
|
|
|
151
193
|
}
|
|
152
194
|
async function login() {
|
|
153
195
|
let previous
|
|
154
|
-
try {previous=await load()} catch {}
|
|
196
|
+
try {previous=await load()} catch(error) {if(error.message==='cli_state_not_private')throw error}
|
|
197
|
+
const config=await signInConfig()
|
|
155
198
|
const {server,redirectUri}=await listen(), attempt=createAttempt({redirectUri})
|
|
156
199
|
let callbackResponse, readline, pasteCallback
|
|
157
200
|
try {
|
|
158
|
-
const
|
|
201
|
+
const url=authorizationURL({authOrigin:config.authOrigin,clientId:config.clientId,attempt})
|
|
159
202
|
const pending=new Promise((resolve,reject)=>{
|
|
160
203
|
const timer=setTimeout(()=>{readline?.close();reject(Error('attempt_expired'))},600000)
|
|
161
204
|
server.on('request',(req,res)=>{
|
|
@@ -180,14 +223,16 @@ async function login() {
|
|
|
180
223
|
const code=await pending
|
|
181
224
|
const exchange=await call('exchange',{code,verifier:attempt.verifier,redirectUri})
|
|
182
225
|
const confirmation=await call('activation',{},exchange.ticket)
|
|
183
|
-
await
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
226
|
+
const confirmed=await approvals.wait(exchange.ticket,confirmation,{
|
|
227
|
+
activation:true,opened:interactiveBrowser&&Boolean(callbackResponse),signIn:true,
|
|
228
|
+
async beforeWait(url) {
|
|
229
|
+
await save({ticket:exchange.ticket})
|
|
230
|
+
// A valid replacement is saved before retiring an existing session.
|
|
231
|
+
if(previous)try {const ended=await call('logout',{},previous.ticket);if(ended.ended!==true)throw Error('account_unavailable')}catch(error){if(error.message!=='authorization_required')throw error}
|
|
232
|
+
if(callbackResponse){callbackResponse.writeHead(303,{Location:url,'Cache-Control':'no-store','Referrer-Policy':'no-referrer'});callbackResponse.end()}
|
|
233
|
+
await opening
|
|
234
|
+
}
|
|
235
|
+
})
|
|
191
236
|
if(confirmed){
|
|
192
237
|
const own=await call('whoami',{},exchange.ticket);output({status:'signed_in',...(!asJson?{message:`Signed in as ${own.displayName??own.email??'FunFab account'}.${command.command==='login'?'':' Continuing…'}`}:{})})}
|
|
193
238
|
return confirmed
|
|
@@ -202,9 +247,9 @@ async function whoami() {
|
|
|
202
247
|
}
|
|
203
248
|
async function logout() {
|
|
204
249
|
let saved,malformed,exists=true,ended=false
|
|
205
|
-
try {saved=await load()} catch(error) {if(error.message==='authorization_required')exists=false}
|
|
206
|
-
if(saved)try {ended=(await call('logout',{},saved.ticket)).ended===true} catch(error) {if(error.malformedConfirmation)malformed=error}
|
|
207
|
-
try {await unlink(file)} catch(error) {if(error.code!=='ENOENT')throw problem('cli_state_unwritable','The saved sign-in could not be removed. Make the CLI state folder writable, then run funfab logout.',person('Make the CLI state folder writable, then run funfab logout.'))}
|
|
250
|
+
try {saved=await load()} catch(error) {if(error.unsafeStateDirectory)throw error;if(error.message==='authorization_required')exists=false}
|
|
251
|
+
if(saved&&api)try {ended=(await call('logout',{},saved.ticket)).ended===true} catch(error) {if(error.malformedConfirmation)malformed=error}
|
|
252
|
+
try {await checkStateDirectory();await unlink(file)} catch(error) {if(error.display)throw error;if(error.code!=='ENOENT')throw problem('cli_state_unwritable','The saved sign-in could not be removed. Make the CLI state folder writable, then run funfab logout.',person('Make the CLI state folder writable, then run funfab logout.'))}
|
|
208
253
|
if(malformed)throw malformed
|
|
209
254
|
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"})
|
|
210
255
|
}
|
|
@@ -252,6 +297,7 @@ async function submit() {
|
|
|
252
297
|
}
|
|
253
298
|
const emit=async result=>{
|
|
254
299
|
if(result.status==='activation_needed') {if(await confirmation(result))await submit();return}
|
|
300
|
+
if(result.status==='sudo_needed')return approvals.wait(saved.ticket,result,{pendingOnly:true})
|
|
255
301
|
if(result.clientId) {saved.submission={requestId:body.requestId,clientId:result.clientId};await save(saved).catch(()=>{})}
|
|
256
302
|
const {gameCredential,...safe}=result
|
|
257
303
|
let delivered
|
|
@@ -273,12 +319,12 @@ async function submit() {
|
|
|
273
319
|
if(reference.status!=='key_needed'||reference.gameCredential||!body.credentialInstalled) {await emit(reference);return}
|
|
274
320
|
if(reference.clientId) {saved.submission={requestId:body.requestId,clientId:reference.clientId};await save(saved).catch(()=>{})}
|
|
275
321
|
if(body.credentialInstalled&&body.checks?.gate?.method==='anonymous_https') {
|
|
276
|
-
const config=await
|
|
322
|
+
const config=await signInConfig()
|
|
277
323
|
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})
|
|
278
324
|
}
|
|
279
325
|
await emit(await call('submit',{...body,approvedIn:approvals.approvedIn},saved.ticket))
|
|
280
326
|
} catch(error) {
|
|
281
|
-
if(error.display||['authorization_required',...Object.keys(refusals)].includes(error.message))throw error
|
|
327
|
+
if(error.display||error.malformedConfirmation||['authorization_required','invalid_configuration',...Object.keys(refusals)].includes(error.message))throw error
|
|
282
328
|
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}
|
|
283
329
|
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}
|
|
284
330
|
const checks=error.message==='game_submit_checks_required'
|
|
@@ -416,7 +462,7 @@ async function report(error,offer=true) {
|
|
|
416
462
|
...Object.fromEntries(['game_signups_closed','game_submission_required','game_switch_off_held','game_live_production_only','game_title_declaration_required','game_staff_cannot_be_blocked','game_account_not_found'].map(code=>[code,[{game_signups_closed:'Game sign-ups are closed.',game_submission_required:'This game needs approval before it can be opened.',game_switch_off_held:'A hold prevents starting this game.',game_live_production_only:'Moving a game to Playtest is available only on Production.',game_title_declaration_required:'This title needs a valid content declaration.',game_staff_cannot_be_blocked:'Staff accounts cannot be blocked.',game_account_not_found:'The target account is unavailable.'}[code],(code==='game_signups_closed'?operator:person)('Ask the authorized owner or operator to resolve this before creating another confirmation.')]])),
|
|
417
463
|
game_permission_denied:command.command==='game submit'?refusals.game_permission_denied:['You cannot change this game. Ask its owner or a staff member for help.',person('Ask the game owner or a staff member for help.')]
|
|
418
464
|
}
|
|
419
|
-
const entry=known[error.message]??
|
|
465
|
+
const entry=known[error.message]??operatorFailure
|
|
420
466
|
fail(error.display?error.message:known[error.message]?error.message:'command_failed',error.display??entry[0],error.nextAction??entry[1],error.exit??(isWrite&&['accounts_request_invalid','game_request_invalid'].includes(error.message)?2:1),error.reason)
|
|
421
467
|
if(offer&&terminal&&!error.noSignIn&&error.message==='authorization_required') {
|
|
422
468
|
const rl=createInterface({input:process.stdin,output:process.stdout})
|
package/cli/origins.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export const preview = Object.freeze({api:'https://api-preview.funfab.io',website:'https://preview.funfab.io'})
|
|
2
|
+
const loopbackHosts = ['localhost', '127.0.0.1', '[::1]']
|
|
3
|
+
const loopback = url => ['http:', 'https:'].includes(url.protocol) && loopbackHosts.includes(url.hostname)
|
|
4
|
+
|
|
5
|
+
function parseURL(value, originOnly = false) {
|
|
6
|
+
try {
|
|
7
|
+
const url = new URL(value)
|
|
8
|
+
return !originOnly || url.origin === value ? url : null
|
|
9
|
+
} catch {return null}
|
|
10
|
+
}
|
|
11
|
+
export function apiAddress(value = preview.api, allowCustom) {
|
|
12
|
+
const url = parseURL(value,true)
|
|
13
|
+
if (value === preview.api) return {origin: value}
|
|
14
|
+
if (url && loopback(url)) return {origin: value, loopback: true}
|
|
15
|
+
if (url?.protocol === 'https:' && allowCustom === '1') return {origin: value, custom: true}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function validatedSignInConfig(config, address, getPreviewConfig) {
|
|
19
|
+
const auth = parseURL(config?.authOrigin,true)
|
|
20
|
+
if (!auth || (auth.protocol !== 'https:' && !(address.loopback && loopback(auth)))
|
|
21
|
+
|| typeof config.clientId !== 'string' || !config.clientId) throw Error('invalid_configuration')
|
|
22
|
+
if (address.custom) {
|
|
23
|
+
const expected = await getPreviewConfig()
|
|
24
|
+
if (config.authOrigin !== expected?.authOrigin || config.clientId !== expected?.clientId) throw Error('invalid_configuration')
|
|
25
|
+
}
|
|
26
|
+
return config
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function isConfirmationAddress(value, requestId, allowLoopback) {
|
|
30
|
+
const url = typeof value === 'string' && !/[\u0000-\u0020\u007f]/u.test(value) && parseURL(value)
|
|
31
|
+
return Boolean(url && (url.origin === preview.website || (allowLoopback && loopback(url)))
|
|
32
|
+
&& !url.username && !url.password && !value.includes('#') && url.pathname === '/account/cli-confirmation'
|
|
33
|
+
&& url.searchParams.size === 1 && url.searchParams.get('request') === requestId)
|
|
34
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import {constants} from 'node:fs'
|
|
2
|
+
import {mkdir, open, realpath} from 'node:fs/promises'
|
|
3
|
+
export const privateFilesSupported = typeof process.getuid === 'function' && Boolean(constants.O_NOFOLLOW)
|
|
4
|
+
|
|
5
|
+
export async function privateDirectories(base, owned, {create = false} = {}) {
|
|
6
|
+
for (const path of [base, ...owned]) {
|
|
7
|
+
try {
|
|
8
|
+
if (create) await mkdir(path, {recursive: true, mode: 0o700})
|
|
9
|
+
if (path === base && await realpath(base) !== base) throw Error('private_file_unavailable')
|
|
10
|
+
const directory = await open(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
|
|
11
|
+
try {
|
|
12
|
+
const stat = await directory.stat()
|
|
13
|
+
if (!stat.isDirectory() || stat.uid !== process.getuid() || (stat.mode & 0o022)) throw Error('private_file_unavailable')
|
|
14
|
+
if (path !== base && (stat.mode & 0o7777) !== 0o700) await directory.chmod(0o700)
|
|
15
|
+
} finally {await directory.close()}
|
|
16
|
+
} catch (error) {throw Object.assign(error, {path})}
|
|
17
|
+
}
|
|
18
|
+
}
|
package/cli/tokens.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {constants} from 'node:fs'
|
|
2
2
|
import {randomUUID} from 'node:crypto'
|
|
3
3
|
import {alignedRows} from './approvals.mjs'
|
|
4
|
-
import {
|
|
4
|
+
import {lstat,open} from 'node:fs/promises'
|
|
5
|
+
import {privateDirectories,privateFilesSupported} from './private-directory.mjs'
|
|
5
6
|
import {homedir} from 'node:os'
|
|
6
7
|
import {join,resolve} from 'node:path'
|
|
7
8
|
|
|
@@ -62,7 +63,12 @@ const scopeArg=s=>s.scope==='staff'?'--staff':/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.
|
|
|
62
63
|
const revokeCommand=i=>`funfab token revoke ${scopeArg(i.scope)} ${quote(i.name)}`
|
|
63
64
|
const listCommand=i=>`funfab token list ${scopeArg(i.scope)}`
|
|
64
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())
|
|
65
|
-
const
|
|
66
|
+
const formatPowers=t=>[
|
|
67
|
+
'Edit and unpublish store pages',
|
|
68
|
+
...(t.status?['Change the game’s status']:[]),
|
|
69
|
+
...(t.switchOff?['Stop and start the game']:[]),
|
|
70
|
+
...(t.access?['Requests, allow and block lists']:[])
|
|
71
|
+
].join(' · ')
|
|
66
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)}`
|
|
67
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.`
|
|
68
74
|
const failure=(code,message,command)=>Object.assign(Error(code),{display:message,nextAction:{kind:'command',command}})
|
|
@@ -70,21 +76,10 @@ const slug=value=>value.normalize('NFKD').toLowerCase().replace(/[^a-z0-9]+/g,'-
|
|
|
70
76
|
|
|
71
77
|
// Adapt native exclusive creation, not the replaceable cli.json writer. Values never enter state.
|
|
72
78
|
export async function tokenDestination(environment,scope,name,mutationId) {
|
|
73
|
-
if(!['preview','production'].includes(environment)
|
|
79
|
+
if(!['preview','production'].includes(environment)||!privateFilesSupported)throw Error('private_file_unavailable')
|
|
74
80
|
const base=resolve(process.env.XDG_CONFIG_HOME||join(homedir(),'.config'))
|
|
75
|
-
|
|
76
|
-
await
|
|
77
|
-
if(await realpath(base)!==base)throw Object.assign(Error('private_file_unavailable'),{path:base})
|
|
78
|
-
const owner=process.getuid(), parents=[base,join(base,'funfab'),join(base,'funfab','tokens'),join(base,'funfab','tokens',environment)]
|
|
79
|
-
for(const [index,path] of parents.entries()) {
|
|
80
|
-
if(index)await mkdir(path,{mode:0o700}).catch(error=>{if(error.code!=='EEXIST')throw error})
|
|
81
|
-
const stat=await lstat(path)
|
|
82
|
-
if(!stat.isDirectory()||stat.isSymbolicLink()||stat.uid!==owner||(stat.mode&0o022))throw Object.assign(Error('private_file_unavailable'),{path})
|
|
83
|
-
if(index) {
|
|
84
|
-
const directory=await open(path,constants.O_RDONLY|constants.O_DIRECTORY|constants.O_NOFOLLOW)
|
|
85
|
-
try {await directory.chmod(0o700)} catch(error) {throw Object.assign(error,{path})} finally {await directory.close()}
|
|
86
|
-
}
|
|
87
|
-
}
|
|
81
|
+
const parents=[join(base,'funfab'),join(base,'funfab','tokens'),join(base,'funfab','tokens',environment)]
|
|
82
|
+
await privateDirectories(base,parents,{create:true})
|
|
88
83
|
if(mutationId!==undefined&&!/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(mutationId))throw Error('private_file_unavailable')
|
|
89
84
|
const path=join(parents.at(-1),`${scope.scope==='staff'?'staff':slug(scope.game)}-${slug(name)}${mutationId?'-'+mutationId:''}`)
|
|
90
85
|
return path
|
|
@@ -146,9 +141,9 @@ export async function runToken(intent,{call,load,output,approvals,asJson=false})
|
|
|
146
141
|
const own=await read('whoami',{});if(!own)return
|
|
147
142
|
const active=result.tokens.filter(activeToken)
|
|
148
143
|
const rows=active.map(t=>{
|
|
149
|
-
const powers=
|
|
144
|
+
const powers=formatPowers(t.ticks)
|
|
150
145
|
const age=t.lastUsedAt?Math.max(0,Math.floor((Date.now()-Date.parse(t.lastUsedAt))/60000)):null
|
|
151
|
-
return [t.name,t.authorizerAccountId===own.accountId?'you':'a staff member',`
|
|
146
|
+
return [t.name,t.authorizerAccountId===own.accountId?'you':'a staff member',`Can: ${powers}`,t.expiresAt?`ends ${date(t.expiresAt)}`:'until revoked',age===null?'never used':`last used ${age} min ago`]
|
|
152
147
|
})
|
|
153
148
|
const table=alignedRows(asJson?null:['Name','Created by','Permissions','Ends','Last used'],rows).split('\n')
|
|
154
149
|
const powers={status:'change the status of',switchOff:'stop and start',access:'change access to'}
|
|
@@ -183,8 +178,8 @@ export async function runToken(intent,{call,load,output,approvals,asJson=false})
|
|
|
183
178
|
const mutationId=randomUUID()
|
|
184
179
|
await preflight(environment,intent,mutationId)
|
|
185
180
|
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}:{})}
|
|
186
|
-
const powers=
|
|
187
|
-
const prompt=`Create "${intent.name}" for ${scopeName}? It can ${powers
|
|
181
|
+
const powers=formatPowers(intent.ticks)
|
|
182
|
+
const prompt=`Create "${intent.name}" for ${scopeName}? It can ${powers}. [y/N]`
|
|
188
183
|
let response
|
|
189
184
|
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.'})}
|
|
190
185
|
catch(error) {
|
|
@@ -203,7 +198,7 @@ export async function runToken(intent,{call,load,output,approvals,asJson=false})
|
|
|
203
198
|
catch {throw failure('token_delivery_lost',madeButNotSaved(intent),revokeCommand(intent))}
|
|
204
199
|
const shown=displayPath(path)
|
|
205
200
|
const paidLine=response.paidGameName?`\n${response.paidGameName} costs money each time it's played. Starting it and letting players in will spend money.`:''
|
|
206
|
-
const message=`Token created: ${intent.name} (${scopeName}, ${environmentLabel(environment)})\nSaved to ${shown}\n (readable only by you; shown nowhere else)\nCan: ${powers
|
|
201
|
+
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)}`
|
|
207
202
|
output({environment,name:intent.name,path,message})
|
|
208
203
|
if(intent.print)process.stdout.write(response.tokenValue+'\n')
|
|
209
204
|
}
|