@shotik/cli 0.0.0-stage → 0.2.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.
@@ -0,0 +1,127 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { dirname, join, resolve } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const here = dirname(fileURLToPath(import.meta.url))
6
+ const SEVERITIES = ['high', 'medium', 'low']
7
+ const AREAS = ['onboarding', 'paywall', 'purchase', 'apple-rule']
8
+ const PLATFORMS = ['ios', 'android', 'both']
9
+ const EVIDENCE_RE = /^brain:[a-z0-9-]+\/[A-Za-z0-9._-]+$/
10
+ const SECRET_FILE_RE = /(^|\/)(\.env[^/]*|[^/]*\.(pem|p8|key|p12|keystore|jks))$/i
11
+ const SECRET_TEXT_RE = /sk-[A-Za-z0-9]{8,}|AKIA[0-9A-Z]{8,}|-----BEGIN/
12
+ const CODE_RE = /^[A-Za-z0-9]{6,8}$/
13
+
14
+ export const base = () => (process.env.SHOTIK_WEB || 'https://shotik.app').replace(/\/+$/, '')
15
+
16
+ export function loadChecklist() {
17
+ const found = [join(here, '..', 'data', 'brain', 'audit', 'checklist.json'), resolve(here, '..', '..', '..', 'brain', 'audit', 'checklist.json'), join(here, 'checklist.json')].find(existsSync)
18
+ return JSON.parse(readFileSync(found, 'utf8'))
19
+ }
20
+
21
+ const stackKey = (s) => String(s).toLowerCase().replace(/[\s_]+/g, '-').replace(/^(rn|reactnative)$/, 'react-native').replace(/^jetpack-compose$|^android$/, 'kotlin').replace(/^ios$/, 'swift')
22
+
23
+ export function checklistText(stack) {
24
+ const c = loadChecklist()
25
+ const wanted = [stack ?? []].flat().map(stackKey).filter((s) => c.stacks.includes(s))
26
+ const stacks = wanted.length ? wanted : c.stacks
27
+ const lookFor = (look, s) => look[s] ?? look[c.fallback?.[s]]
28
+ const out = ['# Shotik audit checklist (' + c.schema + ')', 'Stacks: ' + stacks.join(', '), '', 'Walk every item against the app code. Report only what you found in a real file and line, with the item\'s evidence ref.', '']
29
+ out.push('## Where to look', ...stacks.map((s) => '- ' + s + ': purchases via ' + c.benchmarks[s].purchases.join(' or ') + '; read ' + c.benchmarks[s].look.join(', ')), '')
30
+ for (const area of c.areas) {
31
+ out.push('## ' + area)
32
+ for (const i of c.items.filter((x) => x.area === area)) {
33
+ out.push('', '### ' + i.id + ' [' + i.severity + '] ' + i.title)
34
+ for (const s of stacks) if (lookFor(i.look, s)) out.push('- look (' + s + '): ' + lookFor(i.look, s))
35
+ out.push('- why it costs money: ' + i.why, '- evidence: ' + i.evidence, '- fix (' + i.fix.stack + '):', '```', i.fix.code, '```')
36
+ }
37
+ out.push('')
38
+ }
39
+ return out.join('\n')
40
+ }
41
+
42
+ export const SCHEMA_TEXT = [
43
+ 'POST <base>/api/session/<code>/findings with JSON:',
44
+ '{ "app": { "name": string <=100, "platform": "ios"|"android"|"both", "stack": string[1..8] },',
45
+ ' "findings": [ { "severity": "high"|"medium"|"low", "area": "onboarding"|"paywall"|"purchase"|"apple-rule",',
46
+ ' "file": repo-relative path (no leading /, no .., no .env/.pem/.p8/.key/.p12/.keystore/.jks), "line": integer >= 1,',
47
+ ' "title": string <=120, "why": string <=600, "evidence"?: "brain:<topic>/<id>", "diff"?: string <=20 lines and <=2000 chars } ] (1..60),',
48
+ ' "done"?: boolean }',
49
+ 'Never include secrets (sk-..., AKIA..., -----BEGIN) or whole files. Send app on the first post; set done:true on the last.',
50
+ ].join('\n')
51
+
52
+ export function validateFindings(body, first) {
53
+ const bad = (error, field) => ({ error: { error, field } })
54
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return bad('bad_json')
55
+ let app = null
56
+ if (body.app !== undefined) {
57
+ const a = body.app
58
+ if (!a || typeof a !== 'object' || Array.isArray(a)) return bad('bad_schema', 'app')
59
+ if (typeof a.name !== 'string' || !a.name.trim() || a.name.length > 100) return bad('bad_schema', 'app.name')
60
+ if (!PLATFORMS.includes(a.platform)) return bad('bad_schema', 'app.platform')
61
+ if (!Array.isArray(a.stack) || a.stack.length < 1 || a.stack.length > 8 || a.stack.some((s) => typeof s !== 'string' || !s || s.length > 40)) return bad('bad_schema', 'app.stack')
62
+ app = { name: a.name.trim(), platform: a.platform, stack: a.stack }
63
+ } else if (first) return bad('bad_schema', 'app')
64
+ if (!Array.isArray(body.findings) || body.findings.length < 1) return bad('bad_schema', 'findings')
65
+ if (body.findings.length > 60) return bad('too_many', 'findings')
66
+ if (body.done !== undefined && typeof body.done !== 'boolean') return bad('bad_schema', 'done')
67
+ const findings = []
68
+ for (let i = 0; i < body.findings.length; i++) {
69
+ const f = body.findings[i]
70
+ const at = (k) => 'findings[' + i + '].' + k
71
+ if (!f || typeof f !== 'object' || Array.isArray(f)) return bad('bad_schema', 'findings[' + i + ']')
72
+ if (!SEVERITIES.includes(f.severity)) return bad('bad_schema', at('severity'))
73
+ if (!AREAS.includes(f.area)) return bad('bad_schema', at('area'))
74
+ if (typeof f.file !== 'string' || !f.file || f.file.length > 200 || f.file.startsWith('/') || f.file.split(/[\\/]/).includes('..') || /^[A-Za-z]:/.test(f.file) || SECRET_FILE_RE.test(f.file)) return bad('bad_schema', at('file'))
75
+ if (!Number.isInteger(f.line) || f.line < 1 || f.line > 1000000) return bad('bad_schema', at('line'))
76
+ if (typeof f.title !== 'string' || !f.title.trim() || f.title.length > 120) return bad('bad_schema', at('title'))
77
+ if (typeof f.why !== 'string' || !f.why.trim() || f.why.length > 600) return bad('bad_schema', at('why'))
78
+ if (f.evidence !== undefined && (typeof f.evidence !== 'string' || !EVIDENCE_RE.test(f.evidence))) return bad('bad_schema', at('evidence'))
79
+ if (f.diff !== undefined) {
80
+ if (typeof f.diff !== 'string') return bad('bad_schema', at('diff'))
81
+ if (f.diff.length > 2000 || f.diff.split('\n').length > 20) return bad('diff_too_long', at('diff'))
82
+ if (SECRET_TEXT_RE.test(f.diff)) return bad('secret_in_diff', at('diff'))
83
+ }
84
+ if (SECRET_TEXT_RE.test(f.why) || SECRET_TEXT_RE.test(f.title)) return bad('secret_in_diff', at('why'))
85
+ const out = { severity: f.severity, area: f.area, file: f.file, line: f.line, title: f.title.trim(), why: f.why.trim() }
86
+ if (f.evidence) out.evidence = f.evidence
87
+ if (f.diff) out.diff = f.diff
88
+ findings.push(out)
89
+ }
90
+ return { app, findings, done: body.done === true }
91
+ }
92
+
93
+ function codeOf(code) {
94
+ if (typeof code !== 'string' || !CODE_RE.test(code.trim())) throw new Error('Pass the audit code from shotik.app/start (6-8 letters and digits).')
95
+ return code.trim().toUpperCase()
96
+ }
97
+
98
+ async function post(path, body) {
99
+ let res
100
+ try {
101
+ res = await fetch(base() + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
102
+ } catch (e) {
103
+ throw new Error("Couldn't reach " + base() + ': ' + e.message)
104
+ }
105
+ const data = await res.json().catch(() => ({}))
106
+ if (res.status === 404) throw new Error('Unknown or expired audit code. Start a new audit at ' + base() + '/start.')
107
+ if (!res.ok) throw new Error('Shotik refused the request (' + res.status + '): ' + (data.error || 'error') + (data.field ? ' at ' + data.field : ''))
108
+ return data
109
+ }
110
+
111
+ export async function hello(code) {
112
+ return post('/api/session/' + codeOf(code) + '/hello', {})
113
+ }
114
+
115
+ export async function auditChecklist(a = {}) {
116
+ await hello(a.code)
117
+ return checklistText(a.stack) + '\n## Publish\n' + SCHEMA_TEXT + '\nThen call shotik_publish_findings with code ' + codeOf(a.code) + '.'
118
+ }
119
+
120
+ export async function publishFindings(a = {}) {
121
+ const code = codeOf(a.code)
122
+ const v = validateFindings({ app: a.app, findings: a.findings, done: a.done }, true)
123
+ if (v.error) throw new Error('Invalid findings: ' + v.error.error + (v.error.field ? ' at ' + v.error.field : ''))
124
+ const r = await post('/api/session/' + code + '/findings', { app: v.app, findings: v.findings, done: v.done })
125
+ const url = base() + r.projectUrl
126
+ return { accepted: r.accepted, total: r.total, status: r.status, url, say: 'Project: ' + url + '. Download Shotik to watch 40 personas walk your real build.' }
127
+ }
package/bin/shotik.mjs ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.mjs'
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => process.exit(code),
6
+ (err) => {
7
+ process.stderr.write(`shotik: ${err.message}\n`)
8
+ process.exit(err.exitCode ?? 1)
9
+ }
10
+ )
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@shotik/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Set up Shotik in your app with your coding agent",
5
+ "type": "module",
6
+ "bin": {
7
+ "shotik": "bin/shotik.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "audit",
13
+ "README.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "license": "MIT",
19
+ "scripts": {
20
+ "prepack": "node -e \"require('node:fs').cpSync('../mcp/audit', 'audit', { recursive: true })\"",
21
+ "test": "node --test test/cli.test.mjs test/audit.test.mjs"
22
+ }
23
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,272 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { spawnSync } from 'node:child_process'
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, chmodSync } from 'node:fs'
4
+ import { homedir, hostname } from 'node:os'
5
+ import { basename, dirname, join, resolve } from 'node:path'
6
+ import { fileURLToPath, pathToFileURL } from 'node:url'
7
+
8
+ const SWIFT_URL = 'https://github.com/rahimwws/shotik-app'
9
+
10
+ class CliError extends Error {
11
+ constructor(message, exitCode = 1) {
12
+ super(message)
13
+ this.exitCode = exitCode
14
+ }
15
+ }
16
+
17
+ const home = () => process.env.SHOTIK_HOME || join(homedir(), '.shotik')
18
+ const readJson = (file) => {
19
+ try {
20
+ return JSON.parse(readFileSync(file, 'utf8'))
21
+ } catch {
22
+ return null
23
+ }
24
+ }
25
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
26
+
27
+ function writePrivate(file, data) {
28
+ mkdirSync(join(file, '..'), { recursive: true })
29
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 })
30
+ chmodSync(file, 0o600)
31
+ }
32
+
33
+ function parseArgs(argv) {
34
+ const flags = { json: false }
35
+ const rest = []
36
+ for (const a of argv) {
37
+ if (a === '--json') flags.json = true
38
+ else if (a === '--help' || a === '-h') flags.help = true
39
+ else rest.push(a)
40
+ }
41
+ return { flags, command: rest[0], args: rest.slice(1) }
42
+ }
43
+
44
+ function makeOut(json) {
45
+ return {
46
+ json,
47
+ say: (line = '') => {
48
+ if (!json) process.stdout.write(line + '\n')
49
+ },
50
+ result: (obj) => {
51
+ if (json) process.stdout.write(JSON.stringify(obj) + '\n')
52
+ }
53
+ }
54
+ }
55
+
56
+ function discover() {
57
+ const info = readJson(join(home(), 'local.json'))
58
+ if (!info || !info.port) throw new CliError("Shotik isn't running. Open the Shotik app and try again.", 3)
59
+ try {
60
+ process.kill(info.pid, 0)
61
+ } catch (e) {
62
+ if (e.code !== 'EPERM') throw new CliError("Shotik isn't running. Open the Shotik app and try again.", 3)
63
+ }
64
+ return info
65
+ }
66
+
67
+ async function call(info, method, path, { body, token, headers } = {}) {
68
+ let res
69
+ try {
70
+ res = await fetch(`http://127.0.0.1:${info.port}${path}`, {
71
+ method,
72
+ headers: {
73
+ ...(body ? { 'content-type': 'application/json' } : {}),
74
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
75
+ ...headers
76
+ },
77
+ body: body ? JSON.stringify(body) : undefined
78
+ })
79
+ } catch {
80
+ throw new CliError("Shotik isn't running. Open the Shotik app and try again.", 3)
81
+ }
82
+ const data = await res.json().catch(() => ({}))
83
+ if (!res.ok) {
84
+ const err = new CliError(data.message || `Request failed (${res.status})`)
85
+ err.status = res.status
86
+ throw err
87
+ }
88
+ return data
89
+ }
90
+
91
+ async function login(info, out) {
92
+ const pollSecret = randomBytes(32).toString('base64url')
93
+ const started = await call(info, 'POST', '/v1/cli/login', {
94
+ body: { pollSecret, host: hostname(), cwd: process.cwd(), agent: process.env.SHOTIK_AGENT || undefined }
95
+ })
96
+ out.say(`Code: ${started.code}`)
97
+ out.say('Approve it in the Shotik app.')
98
+ out.result({ event: 'code', code: started.code })
99
+ const every = Number(process.env.SHOTIK_POLL_MS) || 1500
100
+ for (;;) {
101
+ const r = await call(info, 'GET', `/v1/cli/login/${started.id}`, { headers: { 'x-shotik-poll': pollSecret } })
102
+ if (r.status === 'approved') {
103
+ writePrivate(join(home(), 'auth.json'), { token: r.token, expiresAt: r.expiresAt })
104
+ out.say('Approved.')
105
+ return r.token
106
+ }
107
+ if (r.status === 'denied') throw new CliError('Login was denied in the Shotik app.', 2)
108
+ if (r.status === 'expired') throw new CliError('Login request expired. Run the command again.', 2)
109
+ if (r.status === 'gone') throw new CliError('Login request is no longer available. Run the command again.', 2)
110
+ await sleep(every)
111
+ }
112
+ }
113
+
114
+ async function ensureToken(info, out) {
115
+ const saved = readJson(join(home(), 'auth.json'))
116
+ if (saved?.token) {
117
+ try {
118
+ await call(info, 'GET', '/v1/cli/apps', { token: saved.token })
119
+ return saved.token
120
+ } catch (e) {
121
+ if (e.status !== 401 && e.status !== 403) throw e
122
+ }
123
+ }
124
+ return login(info, out)
125
+ }
126
+
127
+ function detect(dir) {
128
+ const pkg = readJson(join(dir, 'package.json'))
129
+ if (pkg) {
130
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies }
131
+ if (deps.expo || deps['react-native']) return { sdk: 'react-native', expo: Boolean(deps.expo), name: pkg.name }
132
+ }
133
+ const entries = readdirSync(dir)
134
+ if (entries.some((e) => e.endsWith('.xcodeproj')) || entries.includes('Package.swift')) return { sdk: 'swift' }
135
+ if (entries.includes('pubspec.yaml')) return { sdk: 'flutter' }
136
+ return null
137
+ }
138
+
139
+ function packageManager(dir) {
140
+ if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun'
141
+ if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm'
142
+ if (existsSync(join(dir, 'yarn.lock'))) return 'yarn'
143
+ return 'npm'
144
+ }
145
+
146
+ function installCommand(project, dir) {
147
+ if (project.sdk === 'flutter') return ['flutter', 'pub', 'add', 'shotik']
148
+ if (project.sdk !== 'react-native') return null
149
+ if (project.expo) return ['npx', 'expo', 'install', '@shotik/react-native']
150
+ const pm = packageManager(dir)
151
+ return [pm, pm === 'npm' ? 'install' : 'add', '@shotik/react-native']
152
+ }
153
+
154
+ async function setup(info, target, out) {
155
+ const dir = resolve(target || '.')
156
+ const project = detect(dir)
157
+ if (!project) throw new CliError('No supported project found (expo/react-native, Xcode/Swift package, flutter).')
158
+ const token = await ensureToken(info, out)
159
+ const { apps } = await call(info, 'GET', '/v1/cli/apps', { token })
160
+ const existing = apps.find((a) => a.repoPath === dir)
161
+ const linked = await call(info, 'POST', '/v1/cli/link', {
162
+ token,
163
+ body: {
164
+ ...(existing ? { appId: existing.id } : { name: project.name || basename(dir) }),
165
+ repoPath: dir,
166
+ sdk: project.sdk
167
+ }
168
+ })
169
+ const cmd = installCommand(project, dir)
170
+ let installed = false
171
+ if (cmd) {
172
+ const line = cmd.join(' ')
173
+ if (process.env.SHOTIK_DRY_RUN === '1') {
174
+ out.say(`Dry run, would run: ${line}`)
175
+ } else {
176
+ out.say(`Running: ${line}`)
177
+ const r = spawnSync(cmd[0], cmd.slice(1), { cwd: dir, stdio: out.json ? ['ignore', 'ignore', 'inherit'] : 'inherit' })
178
+ if (r.status !== 0) throw new CliError(`Install failed: ${line}`)
179
+ installed = true
180
+ }
181
+ } else {
182
+ out.say('Add the package in Xcode: File > Add Package Dependencies.')
183
+ out.say(`Package URL: ${SWIFT_URL} (from 0.1.0)`)
184
+ }
185
+ mkdirSync(join(dir, '.shotik'), { recursive: true })
186
+ writeFileSync(
187
+ join(dir, '.shotik', 'setup.json'),
188
+ JSON.stringify({ sdk: project.sdk, appId: linked.app.id, appKey: linked.appKey }, null, 2) + '\n'
189
+ )
190
+ if (installed) await call(info, 'POST', '/v1/cli/event', { token, body: { kind: 'installed', sdk: project.sdk } })
191
+ await call(info, 'POST', '/v1/cli/event', { token, body: { kind: 'test', sdk: project.sdk } })
192
+ out.say()
193
+ out.say('Next: use @shotik/mcp get_recipe for the remaining code edits, with these variables:')
194
+ out.say(`APP_KEY=${linked.appKey}`)
195
+ out.say(`SERVER_URL=${linked.serverUrl}`)
196
+ out.result({ ok: true, sdk: project.sdk, appId: linked.app.id, APP_KEY: linked.appKey, SERVER_URL: linked.serverUrl })
197
+ }
198
+
199
+ async function audit(code, out) {
200
+ if (!code) throw new CliError('Usage: shotik audit <code>')
201
+ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..')
202
+ const dir = existsSync(join(root, 'audit')) ? join(root, 'audit') : resolve(root, '..', 'mcp', 'audit')
203
+ const a = await import(pathToFileURL(join(dir, 'index.mjs')).href)
204
+ try {
205
+ await a.hello(code)
206
+ } catch (e) {
207
+ throw new CliError(e.message)
208
+ }
209
+ const upper = code.trim().toUpperCase()
210
+ const example = { app: { name: 'MyApp', platform: 'ios', stack: ['expo'] }, findings: [{ severity: 'high', area: 'paywall', file: 'app/paywall.tsx', line: 42, title: 'Hardcoded price', why: 'Users outside the US see the wrong currency.', evidence: 'brain:onboarding/pl-hardcoded-price' }], done: true }
211
+ const curl = `curl -sS -X POST ${a.base()}/api/session/${upper}/findings -H 'content-type: application/json' -d '${JSON.stringify(example)}'`
212
+ const checklist = a.checklistText()
213
+ out.say(checklist)
214
+ out.say('## Publish')
215
+ out.say(a.SCHEMA_TEXT)
216
+ out.say()
217
+ out.say(curl)
218
+ out.say()
219
+ out.say('The response has projectUrl; print ' + a.base() + '<projectUrl> to the user.')
220
+ out.result({ ok: true, code: upper, checklist, schema: a.SCHEMA_TEXT, curl })
221
+ }
222
+
223
+ export async function main(argv) {
224
+ const { flags, command, args } = parseArgs(argv)
225
+ const out = makeOut(flags.json)
226
+ if (!command || flags.help || !['login', 'setup', 'status', 'logout', 'audit'].includes(command)) {
227
+ process.stdout.write('Usage: shotik <login|setup [path]|status|logout|audit <code>> [--json]\n')
228
+ return command && !flags.help ? 1 : 0
229
+ }
230
+ try {
231
+ if (command === 'audit') {
232
+ await audit(args[0], out)
233
+ return 0
234
+ }
235
+ if (command === 'logout') {
236
+ const saved = readJson(join(home(), 'auth.json'))
237
+ if (saved?.token) {
238
+ try {
239
+ await call(discover(), 'POST', '/v1/cli/logout', { token: saved.token })
240
+ } catch {}
241
+ rmSync(join(home(), 'auth.json'), { force: true })
242
+ }
243
+ out.say('Logged out.')
244
+ out.result({ ok: true })
245
+ return 0
246
+ }
247
+ const info = discover()
248
+ if (command === 'login') {
249
+ await login(info, out)
250
+ out.result({ ok: true })
251
+ } else if (command === 'status') {
252
+ const saved = readJson(join(home(), 'auth.json'))
253
+ let loggedIn = false
254
+ if (saved?.token) {
255
+ try {
256
+ await call(info, 'GET', '/v1/cli/apps', { token: saved.token })
257
+ loggedIn = true
258
+ } catch {}
259
+ }
260
+ out.say(`Shotik is running on port ${info.port}. ${loggedIn ? 'Logged in.' : 'Not logged in.'}`)
261
+ out.result({ running: true, port: info.port, loggedIn })
262
+ } else {
263
+ await setup(info, args[0], out)
264
+ }
265
+ return 0
266
+ } catch (e) {
267
+ if (!(e instanceof CliError)) throw e
268
+ if (flags.json) process.stdout.write(JSON.stringify({ ok: false, error: e.message, exitCode: e.exitCode }) + '\n')
269
+ else process.stderr.write(`shotik: ${e.message}\n`)
270
+ return e.exitCode
271
+ }
272
+ }