@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 +75 -48
- package/cli/approvals.mjs +18 -20
- package/cli/credential.mjs +63 -0
- package/cli/funfab.mjs +240 -89
- package/cli/origins.mjs +6 -4
- package/cli/request-approval.mjs +322 -0
- package/cli/submit-help.mjs +41 -1
- package/cli/submit-probe-copy.mjs +6 -0
- package/cli/submit-probe.mjs +48 -16
- package/cli/tokens.mjs +68 -119
- package/cli/version.mjs +4 -0
- package/package.json +1 -1
- package/skills/funfab/SKILL.md +69 -25
- package/validation/capability-submit.mjs +120 -0
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto'
|
|
2
|
+
import {isConfirmationAddress} from './origins.mjs'
|
|
3
|
+
import {safeCredentialDiagnostic, tokenRefusal} from './credential.mjs'
|
|
4
|
+
import {prepareTokenDirectory, saveToken} from './tokens.mjs'
|
|
5
|
+
|
|
6
|
+
const invalid = () => { throw Error('account_unavailable') }
|
|
7
|
+
const handle = value => typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value)
|
|
8
|
+
const uuid = value => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value)
|
|
9
|
+
const slug = value => typeof value === 'string' && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(value)
|
|
10
|
+
const timestamp = value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value) && Number.isFinite(Date.parse(value))
|
|
11
|
+
const text = (value, max) => typeof value === 'string' && value.trim() && [...value].length <= max && safeCredentialDiagnostic(value) === value
|
|
12
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value)
|
|
13
|
+
const shape = (value, required, optional = []) => object(value) &&
|
|
14
|
+
required.every(key => Object.hasOwn(value, key)) && Object.keys(value).every(key => required.includes(key) || optional.includes(key))
|
|
15
|
+
const command = command => ({kind:'command', command})
|
|
16
|
+
const person = instruction => ({kind:'person', instruction})
|
|
17
|
+
const trouble = (error, display, nextAction = person(display), exit = 1, details = {}) =>
|
|
18
|
+
Object.assign(Error(error), {display, nextAction, exit, ...details})
|
|
19
|
+
const collected = "This token's value was delivered once and can't be shown again. If it's lost, revoke the token and ask for a new one."
|
|
20
|
+
const requestCommand = 'funfab token request'
|
|
21
|
+
const tooMany = 'Too many requests to FunFab right now. Wait a minute, then try again.'
|
|
22
|
+
const full = 'You already have five requests waiting. Finish, cancel or wait out one of them, then ask again.'
|
|
23
|
+
const missingDate = 'A staff token needs an end date. Add --expires with a date within 90 days.'
|
|
24
|
+
const defaultInterval = 5
|
|
25
|
+
const throttle = retry => trouble('slow_down', tooMany, command(retry), 1, {interval:defaultInterval + 5})
|
|
26
|
+
|
|
27
|
+
export const tokenRequestHelp = [
|
|
28
|
+
{command:'token request --status', arguments:'HANDLE', description:'See whether a token request was approved', example:'funfab token request --status HANDLE'},
|
|
29
|
+
{command:'token request --resume', arguments:'HANDLE', description:'Collect an approved token', example:'funfab token request --resume HANDLE'},
|
|
30
|
+
{command:'token request', arguments:'GAME --name NAME [--allow status|stop-start|access …] [--expires TIME|never] | --staff --name NAME [--allow …] --expires TIME', description:'Ask for an agent token; a person approves it in the browser', example:'funfab token request emote-defense --name "Balancing agent" --allow stop-start'}
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
export function tokenRequestIntent(args) {
|
|
34
|
+
const usage = () => { throw Error('usage') }
|
|
35
|
+
if (['--status', '--resume'].includes(args[0])) {
|
|
36
|
+
if (args.length !== 2 || !handle(args[1])) usage()
|
|
37
|
+
return {action:args[0] === '--status' ? 'read' : 'resume', requestId:args[1]}
|
|
38
|
+
}
|
|
39
|
+
const flags = new Map(), powers = new Set(), selectors = []
|
|
40
|
+
for (let i = 0; i < args.length; i++) {
|
|
41
|
+
const arg = args[i]
|
|
42
|
+
if (!arg.startsWith('--')) { selectors.push(arg); continue }
|
|
43
|
+
if (!['--staff', '--name', '--allow', '--expires'].includes(arg) || flags.has(arg)) usage()
|
|
44
|
+
if (arg === '--staff') { flags.set(arg, true); continue }
|
|
45
|
+
if (arg === '--allow') {
|
|
46
|
+
while (['status', 'stop-start', 'access'].includes(args[i+1]) && !powers.has(args[i+1])) powers.add(args[++i])
|
|
47
|
+
if (!powers.size || args[i+1] && !args[i+1].startsWith('--')) usage()
|
|
48
|
+
flags.set(arg, true)
|
|
49
|
+
continue
|
|
50
|
+
}
|
|
51
|
+
const value = args[++i]
|
|
52
|
+
if (!value || value.startsWith('--')) usage()
|
|
53
|
+
flags.set(arg, value)
|
|
54
|
+
}
|
|
55
|
+
const staff = flags.has('--staff'), name = flags.get('--name'), expiry = flags.get('--expires')
|
|
56
|
+
if (!text(name, 100) || name !== name.trim() || selectors.length !== (staff ? 0 : 1) ||
|
|
57
|
+
(!staff && !text(selectors[0], 200))) usage()
|
|
58
|
+
if (expiry && expiry !== 'never' && (!timestamp(expiry) || !/(?:Z|\+00:00)$/.test(expiry))) usage()
|
|
59
|
+
return {action:'request', scope:staff ? 'staff' : 'game', selector:selectors[0], name,
|
|
60
|
+
ticks:{status:powers.has('status'), switchOff:powers.has('stop-start'), access:powers.has('access')},
|
|
61
|
+
expiresAt:expiry && expiry !== 'never' ? new Date(expiry).toISOString() : null}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function validToken(token, env, gameId) {
|
|
65
|
+
const dates = ['expiresAt', 'lastUsedAt', 'revokedAt']
|
|
66
|
+
return shape(token, ['id', 'authorizerAccountId', 'environment', 'scope', 'gameId', 'name', 'ticks',
|
|
67
|
+
'createdAt', ...dates, 'revokedByAccountId', 'revocationReason']) &&
|
|
68
|
+
uuid(token.id) && uuid(token.authorizerAccountId) && token.environment === env &&
|
|
69
|
+
token.gameId === gameId && token.scope === (gameId === null ? 'staff' : 'game') &&
|
|
70
|
+
text(token.name, 100) && token.name === token.name.trim() &&
|
|
71
|
+
shape(token.ticks, ['status', 'switchOff', 'access']) && Object.values(token.ticks).every(x => typeof x === 'boolean') &&
|
|
72
|
+
timestamp(token.createdAt) && dates.every(key => token[key] === null || timestamp(token[key])) &&
|
|
73
|
+
(token.revokedByAccountId === null || uuid(token.revokedByAccountId)) &&
|
|
74
|
+
(token.revocationReason === null || text(token.revocationReason, 1000))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const stateFields = ['code', 'expiresAt', 'interval', 'approver']
|
|
78
|
+
const common = ['status', 'action', 'gameId', 'mutationId']
|
|
79
|
+
function validState(value, approver) {
|
|
80
|
+
return /^[A-Z0-9]{4}$/.test(value.code ?? '') && typeof value.code === 'string' &&
|
|
81
|
+
timestamp(value.expiresAt) && Number.isSafeInteger(value.interval) && value.interval >= defaultInterval &&
|
|
82
|
+
value.approver === approver
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function decodeApproval(status, value, {action, operation, address, bearer}) {
|
|
86
|
+
const expected = bearer ? 'unhold' : 'token-create'
|
|
87
|
+
const approver = bearer ? 'switch_off_authority' : 'maker'
|
|
88
|
+
if (status === 202 && action === 'request') {
|
|
89
|
+
const url = value?.confirmationUrl
|
|
90
|
+
if (!shape(value, ['status', ...stateFields, 'confirmationUrl', 'requestId', 'nextAction']) ||
|
|
91
|
+
value.status !== 'approval_needed' || !validState(value, approver) || !handle(value.requestId) ||
|
|
92
|
+
!isConfirmationAddress(url, value.requestId, address.loopback) ||
|
|
93
|
+
!shape(value.nextAction, ['kind','url']) || value.nextAction.kind !== 'open_url' || value.nextAction.url !== url) invalid()
|
|
94
|
+
const safeUrl = new URL('/account/cli-confirmation', new URL(url).origin)
|
|
95
|
+
safeUrl.searchParams.set('request', value.requestId)
|
|
96
|
+
return {...value, confirmationUrl:safeUrl.href, nextAction:{kind:'open_url', url:safeUrl.href}}
|
|
97
|
+
}
|
|
98
|
+
if (status !== 200 || !object(value) || value.action !== expected || !uuid(value.mutationId) ||
|
|
99
|
+
!(slug(value.gameId) || !bearer && value.gameId === null) ||
|
|
100
|
+
operation && (value.gameId !== (operation.game ?? null) || value.mutationId !== operation.mutationId)) invalid()
|
|
101
|
+
const env = address.environment.id
|
|
102
|
+
if (bearer) {
|
|
103
|
+
const committed = value.status === 'committed'
|
|
104
|
+
if (!shape(value, [...common, ...stateFields, ...(committed ? ['result'] : [])]) ||
|
|
105
|
+
!validState(value, approver) || !validReadState(value.status, action)) invalid()
|
|
106
|
+
if (!committed) return value
|
|
107
|
+
const result = value.result
|
|
108
|
+
if (!shape(result, ['game', 'mutationId', 'outcome']) || result.mutationId !== value.mutationId ||
|
|
109
|
+
result.outcome !== 'applied' || !validGame(result.game, env, value.gameId)) invalid()
|
|
110
|
+
return value
|
|
111
|
+
}
|
|
112
|
+
if (Object.hasOwn(value, 'tokenValue')) {
|
|
113
|
+
if (action !== 'resume' || value.status !== 'committed' ||
|
|
114
|
+
!shape(value, [...common, 'token', 'tokenValue'], ['paidGameName']) ||
|
|
115
|
+
!validToken(value.token, env, value.gameId) ||
|
|
116
|
+
typeof value.tokenValue !== 'string' || !new RegExp('^ffgt_'+env+'_[A-Za-z0-9_-]{43}$').test(value.tokenValue) ||
|
|
117
|
+
Object.hasOwn(value, 'paidGameName') && !(value.gameId && text(value.paidGameName, 120))) invalid()
|
|
118
|
+
return value
|
|
119
|
+
}
|
|
120
|
+
const committed = value.status === 'committed'
|
|
121
|
+
if (!shape(value, [...common, ...stateFields, ...(committed ? ['token', 'nextAction'] : [])]) ||
|
|
122
|
+
!validState(value, approver) ||
|
|
123
|
+
(committed ? !validToken(value.token, env, value.gameId) || !shape(value.nextAction, ['kind', 'instruction']) ||
|
|
124
|
+
value.nextAction.kind !== 'person' || value.nextAction.instruction !== collected :
|
|
125
|
+
!validReadState(value.status, action))) invalid()
|
|
126
|
+
return value
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function validReadState(status, action) {
|
|
130
|
+
return status === 'committed' || action !== 'request' &&
|
|
131
|
+
(['pending', 'cancelled', 'expired'].includes(status) || action === 'read' && status === 'approved')
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function validGame(game, environment, gameId) {
|
|
135
|
+
return shape(game, ['gameId','name','environment','revision','kind','tier','listing','access',
|
|
136
|
+
'switchedOff','lifecycle','displayStatus','accessText','titles']) &&
|
|
137
|
+
game.gameId === gameId && game.environment === environment && text(game.name, 120) &&
|
|
138
|
+
Number.isSafeInteger(game.revision) && game.revision >= 0 && game.kind === 'game' &&
|
|
139
|
+
['prototype','released'].includes(game.tier) && ['hidden','experimental','featured'].includes(game.listing) &&
|
|
140
|
+
['staff','invited','open'].includes(game.access) && game.switchedOff === true &&
|
|
141
|
+
['active','retiring','retired'].includes(game.lifecycle) && ['Internal','Playtest','Live','Stopped','Retiring','Retired'].includes(game.displayStatus) && text(game.accessText, Infinity) &&
|
|
142
|
+
Array.isArray(game.titles) && game.titles.every(title =>
|
|
143
|
+
shape(title, ['titleId','name','shown','retiredAt']) && slug(title.titleId) &&
|
|
144
|
+
text(title.name, 120) && typeof title.shown === 'boolean' &&
|
|
145
|
+
(title.retiredAt === null || timestamp(title.retiredAt)))
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const deadline = value => new Intl.DateTimeFormat('en-US', {hour:'numeric', minute:'2-digit', hour12:true})
|
|
149
|
+
.format(new Date(value)).toLowerCase().replace(/\u202f/g, ' ')
|
|
150
|
+
const end = value => value ? `Ends: ${new Intl.DateTimeFormat('en-US', {timeZone:'UTC', dateStyle:'medium', timeStyle:'short'}).format(new Date(value)).replace(/\b(AM|PM)\b/g, word => word.toLowerCase())} UTC`
|
|
151
|
+
: 'Lasts until revoked. It stops working if nobody uses it for a year.'
|
|
152
|
+
const can = ticks => ["See the game's status, setup and requests", ...(ticks.status ? ["Change the game's status"] : []),
|
|
153
|
+
...(ticks.switchOff ? ['Stop and start the game'] : []), ...(ticks.access ? ['Requests, allow and block lists'] : [])].join(' · ')
|
|
154
|
+
const shell = value => "'" + value.replaceAll("'", "'\\''") + "'"
|
|
155
|
+
const quoteName = value => '"' + value.replace(/[\\`"$]/g, '\\$&') + '"'
|
|
156
|
+
const tokenCommand = (action, id) => `${requestCommand} --${action === 'read' ? 'status' : 'resume'} ${id}`
|
|
157
|
+
|
|
158
|
+
function tokenReadOutput(value, intent) {
|
|
159
|
+
const {status, expiresAt} = value
|
|
160
|
+
const statusCommand = command(tokenCommand('read', intent.requestId))
|
|
161
|
+
const resumeCommand = command(tokenCommand('resume', intent.requestId))
|
|
162
|
+
const cancelled = 'This request was cancelled in the browser. No token was made. Ask again if you still need one.'
|
|
163
|
+
const expired = 'This request ran out of time. No token was made. Ask again if you still need one.'
|
|
164
|
+
const [message, nextAction] = {
|
|
165
|
+
pending:intent.action === 'resume' ?
|
|
166
|
+
["Not approved yet, so no token was made. Run this again once it's approved.", resumeCommand] :
|
|
167
|
+
[`Not approved yet. It ends at ${deadline(expiresAt)}.`, statusCommand],
|
|
168
|
+
approved:[`Approved. Collect the token before ${deadline(expiresAt)}:\n ${resumeCommand.command}`, resumeCommand],
|
|
169
|
+
committed:[`This token was already made.\n${collected}`, person(collected)],
|
|
170
|
+
cancelled:[cancelled, command(requestCommand)],
|
|
171
|
+
expired:[expired, command(requestCommand)]
|
|
172
|
+
}[status]
|
|
173
|
+
return {...value, message, nextAction}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function tokenApprovalError(error, intent, environment) {
|
|
177
|
+
const {message:code, httpStatus:status, reason} = error
|
|
178
|
+
const {action, requestId} = intent
|
|
179
|
+
if (status === 401 && code === 'authorization_required' && action !== 'request')
|
|
180
|
+
return trouble(code, 'No request found for that handle with this sign-in. Check the handle, or sign in again with funfab login.', command('funfab login'), 1, {noSignIn:true})
|
|
181
|
+
if (status === 429 && code === 'slow_down') {
|
|
182
|
+
if (action === 'read') return throttle(tokenCommand('read', requestId))
|
|
183
|
+
return trouble(code, tooMany, person('Wait a minute, then try again.'))
|
|
184
|
+
}
|
|
185
|
+
if (status === 429 && code === 'approval_requests_full' && action === 'request') return trouble(code, full)
|
|
186
|
+
if (status === 403 && code === 'delegate_tokens_disabled')
|
|
187
|
+
return trouble(code, `Agent tokens are switched off on ${environment.label} right now. Ask staff.`)
|
|
188
|
+
if (action === 'resume') {
|
|
189
|
+
const [message, next] = {
|
|
190
|
+
'400:game_request_invalid:expiry_elapsed':['The end date you asked for has passed, so no token was made. Ask again with a later date.', command(requestCommand)],
|
|
191
|
+
'400:game_request_invalid:input_invalid':["A staff token can last 90 days at most from when it's made, and this end date is later than that. No token was made. If the date comes within 90 days before this approval ends, run this again. Otherwise ask again with an earlier date.", command(tokenCommand('resume', requestId))],
|
|
192
|
+
'409:game_request_conflict:invalidated':['Another token is now using that name. No token was made. Ask again with a different name.', command(requestCommand)],
|
|
193
|
+
'409:game_revision_conflict:':["The game changed after you asked, so this approval can't be used. No token was made. Ask again.", command(requestCommand)],
|
|
194
|
+
'403:game_permission_denied:':["You can't make this token any more. No token was made."]
|
|
195
|
+
}[`${status}:${code}:${reason ?? ''}`] ?? []
|
|
196
|
+
if (message) return trouble(code, message, next, 1, {reason})
|
|
197
|
+
if (error.unreadableApproval || ['TypeError', 'TimeoutError', 'AbortError'].includes(error.name))
|
|
198
|
+
return trouble('account_unavailable', "Couldn't tell whether the token was made. Check with --status. If it says the token was made, its value is lost: revoke the token and ask for a new one.", command(tokenCommand('read', requestId)))
|
|
199
|
+
}
|
|
200
|
+
return error
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function runTokenRequest(intent, {load, call, approvals, print, address, asJson}) {
|
|
204
|
+
if (intent.scope === 'staff' && !intent.expiresAt) throw trouble('game_request_invalid', missingDate, command(requestCommand), 2)
|
|
205
|
+
const {ticket} = await load()
|
|
206
|
+
const {environment} = address
|
|
207
|
+
const {action, requestId} = intent
|
|
208
|
+
let game, operation
|
|
209
|
+
if (action === 'request') {
|
|
210
|
+
if (intent.scope === 'game') {
|
|
211
|
+
game = await call('game/status', {game:intent.selector}, ticket)
|
|
212
|
+
if (game.status === 'activation_needed') { await approvals.wait(ticket, game, {activation:true, pendingOnly:true}); return }
|
|
213
|
+
if (!slug(game.gameId) || !text(game.name, 120) || game.environment !== environment.id ||
|
|
214
|
+
!Number.isSafeInteger(game.revision) || game.revision < 0 || !Array.isArray(game.titles)) invalid()
|
|
215
|
+
}
|
|
216
|
+
const {scope, name, ticks, expiresAt} = intent
|
|
217
|
+
operation = {action:'token-create', environment:environment.id, scope, name, ticks, expiresAt,
|
|
218
|
+
...(game ? {game:game.gameId, revision:game.revision, affectedTitles:game.titles} : {}), mutationId:randomUUID()}
|
|
219
|
+
} else if (action === 'resume') {
|
|
220
|
+
try { await prepareTokenDirectory(environment.id) }
|
|
221
|
+
catch (error) {
|
|
222
|
+
const path = safeCredentialDiagnostic(error.path ?? environment.id)
|
|
223
|
+
throw trouble('account_unavailable', `The token file can't be created here: ${path}. No token was made. Fix the folder or path, then run the same command again.`, command(tokenCommand('resume', requestId)))
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const body = operation ? {action, operation} : {action, requestId}
|
|
228
|
+
let result
|
|
229
|
+
try { result = await call('approval', body, ticket) }
|
|
230
|
+
catch (error) { throw tokenApprovalError(error, intent, environment) }
|
|
231
|
+
if (result.status === 'activation_needed') { await approvals.wait(ticket, result, {activation:true, pendingOnly:true}); return }
|
|
232
|
+
if (result.status === 'approval_needed') {
|
|
233
|
+
const resume = tokenCommand('resume', result.requestId)
|
|
234
|
+
const message = asJson ?
|
|
235
|
+
"Give this link and code to the person signed in to FunFab in this CLI. They open it in their own browser, check the code matches and approve. The approval and the resume command both have to happen before the request ends. Don't open the link yourself." :
|
|
236
|
+
[`${environment.label} · ${game?.name ?? 'Every game you manage as staff'}`, 'A person has to approve this token in their own browser.',
|
|
237
|
+
` Open: ${result.confirmationUrl}`, ` Check code: ${result.code}`, `It can: ${can(intent.ticks)}`, end(intent.expiresAt),
|
|
238
|
+
`The approval and the next command both have to happen by ${deadline(result.expiresAt)}:`, ` ${resume}`].join('\n')
|
|
239
|
+
print({...result, message})
|
|
240
|
+
process.exitCode = 3
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
if (!Object.hasOwn(result, 'tokenValue')) {
|
|
244
|
+
print(tokenReadOutput(result, intent))
|
|
245
|
+
if (['cancelled', 'expired'].includes(result.status) || action === 'resume' && result.status === 'pending') process.exitCode = 1
|
|
246
|
+
return
|
|
247
|
+
}
|
|
248
|
+
const {tokenValue, token, paidGameName, ...safe} = result
|
|
249
|
+
const scope = token.scope === 'staff' ? {scope:'staff'} : {scope:'game', game:token.gameId}
|
|
250
|
+
const revoke = `funfab token revoke ${scope.game ?? '--staff'} ${quoteName(token.name)}`
|
|
251
|
+
let tokenFile
|
|
252
|
+
try { tokenFile = await saveToken(tokenValue, token.environment, scope, token.name, safe.mutationId) }
|
|
253
|
+
catch {
|
|
254
|
+
throw trouble('account_unavailable', `The token "${token.name}" was made, but it couldn't be saved here, and it can't be shown again. Revoke it, then make a new one:\n ${revoke}`, command(revoke))
|
|
255
|
+
}
|
|
256
|
+
const scopeName = token.scope === 'staff' ? 'staff, every game you manage' : 'one game'
|
|
257
|
+
const paid = paidGameName ? `\n${paidGameName} costs money each time it's played. Starting it and letting players in will spend money.` : ''
|
|
258
|
+
const message = `Token created: ${token.name} (${scopeName}, ${environment.label})\nSaved to ${tokenFile}\n (readable only by you; shown nowhere else)\nCan: ${can(token.ticks)}${paid}\n${end(token.expiresAt)}\n\nTo use it: export FUNFAB_TOKEN_FILE=${shell(tokenFile)}\nTo revoke: ${revoke}`
|
|
259
|
+
print({...safe, token, ...(paidGameName ? {paidGameName} : {}), tokenFile, message, nextAction:person(`export FUNFAB_TOKEN_FILE=${shell(tokenFile)}`)})
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export const approvalHelp = [
|
|
263
|
+
{command:'approval status', arguments:'HANDLE', description:'See whether a request was approved', example:'funfab approval status HANDLE'},
|
|
264
|
+
{command:'approval resume', arguments:'HANDLE', description:'Run a request that was approved', example:'funfab approval resume HANDLE'}
|
|
265
|
+
]
|
|
266
|
+
|
|
267
|
+
export function approvalIntent(args) {
|
|
268
|
+
if (args.length !== 3 || !handle(args[2])) throw Error('usage')
|
|
269
|
+
return {action:args[1] === 'status' ? 'read' : 'resume', requestId:args[2]}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const holdCommand = (action, id) => `funfab approval ${action === 'read' ? 'status' : 'resume'} ${id}`
|
|
273
|
+
const holdStatus = id => command(`funfab game status ${id}`)
|
|
274
|
+
|
|
275
|
+
function holdError(error, action, requestId, environment, game) {
|
|
276
|
+
const {message:code, httpStatus:status, reason} = error
|
|
277
|
+
if (status === 401 && code === 'authorization_required' && action !== 'request')
|
|
278
|
+
return trouble(code, `No request found for that handle with this token, or FunFab doesn't recognise this token on ${environment.label}. Check the handle, or ask the token's maker for a new token.`)
|
|
279
|
+
if (status === 429 && code === 'slow_down') {
|
|
280
|
+
if (action === 'read') return throttle(holdCommand('read', requestId))
|
|
281
|
+
return trouble(code, tooMany, person('Wait a minute, then try again.'))
|
|
282
|
+
}
|
|
283
|
+
if (status === 429 && code === 'approval_requests_full' && action === 'request') return trouble(code, full)
|
|
284
|
+
if (status === 409 && (code === 'game_revision_conflict' || code === 'game_request_conflict' && reason === 'invalidated'))
|
|
285
|
+
return trouble(code, "The game changed after you asked, so this approval can't be used. Nothing changed. Check its status, and ask again if it's still on hold.",
|
|
286
|
+
game && holdStatus(game.gameId), 1, {reason})
|
|
287
|
+
if (status === 403 && code === 'game_permission_denied')
|
|
288
|
+
return trouble(code, "This can't run right now, because someone's access to the game has changed. Nothing changed. Ask the game's owner or a staff member to check, then run this again or ask again.")
|
|
289
|
+
const message = tokenRefusal(error, environment, 'stop-start', game)
|
|
290
|
+
return message ? trouble(code, message) : error
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export async function runHoldApproval({action, requestId, operation, game}, {call, ticket, print, address, asJson}) {
|
|
294
|
+
let value
|
|
295
|
+
try { value = await call('approval', operation ? {action,operation} : {action,requestId}, ticket) }
|
|
296
|
+
catch (error) { throw holdError(error, action, requestId, address.environment, game) }
|
|
297
|
+
const {status, expiresAt} = value
|
|
298
|
+
if (status === 'approval_needed') {
|
|
299
|
+
const message = asJson ?
|
|
300
|
+
"Lifting this hold needs approval from someone who can switch the game off. Give them this link and code. They open it in their own browser, check the code matches and approve. The approval and the resume command both have to happen before the request ends. Don't open the link yourself." :
|
|
301
|
+
[`${address.environment.label} · ${game.name}`, 'Lifting a hold needs approval from someone who can switch the game off.',
|
|
302
|
+
` Open: ${value.confirmationUrl}`, ` Check code: ${value.code}`,
|
|
303
|
+
`The approval and the next command both have to happen by ${deadline(expiresAt)}:`, ` ${holdCommand('resume', value.requestId)}`].join('\n')
|
|
304
|
+
print({...value, message})
|
|
305
|
+
process.exitCode = 3
|
|
306
|
+
return
|
|
307
|
+
}
|
|
308
|
+
const resume = command(holdCommand('resume', requestId))
|
|
309
|
+
const cancelled = 'This request was cancelled in the browser. Nothing changed. Ask again if the game is still on hold.'
|
|
310
|
+
const expired = 'This request ran out of time. Nothing changed. Ask again if the game is still on hold.'
|
|
311
|
+
const [message, nextAction, exit] = {
|
|
312
|
+
pending:action === 'resume' ? ["Not approved yet, so nothing changed. Run this again once it's approved.", resume, 1] :
|
|
313
|
+
[`Not approved yet. It ends at ${deadline(expiresAt)}.`, command(holdCommand('read', requestId)), 0],
|
|
314
|
+
approved:[`Approved. Lift the hold before ${deadline(expiresAt)}:\n ${resume.command}`, resume, 0],
|
|
315
|
+
committed:[action === 'resume' ? `Hold lifted. ${value.result?.game.name} is still stopped.` :
|
|
316
|
+
'The hold was lifted. The game is still stopped.', holdStatus(value.gameId), 0],
|
|
317
|
+
cancelled:[cancelled, holdStatus(value.gameId), 1],
|
|
318
|
+
expired:[expired, holdStatus(value.gameId), 1]
|
|
319
|
+
}[status]
|
|
320
|
+
print({...value,message,nextAction})
|
|
321
|
+
process.exitCode = exit
|
|
322
|
+
}
|
package/cli/submit-help.mjs
CHANGED
|
@@ -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
|
+
}
|
package/cli/submit-probe.mjs
CHANGED
|
@@ -1,34 +1,66 @@
|
|
|
1
|
-
|
|
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
|
|
6
|
-
const
|
|
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)
|
|
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
|
-
|
|
16
|
-
|
|
17
|
-
|
|
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(
|
|
41
|
+
if(current.origin!==stable.origin||!https(current)) stop(redirectWrong)
|
|
21
42
|
const response=await request(current)
|
|
22
|
-
if(!
|
|
23
|
-
let next;try {next=new URL(response.headers.get('location'),current)} catch {stop(
|
|
24
|
-
if(
|
|
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(
|
|
28
|
-
|
|
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(
|
|
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
|
}
|