@shotik/mcp 0.1.1 → 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
+ }