@totalaudiopromo/spotcheck 0.0.0-stage → 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,89 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module';
3
+ import { checkPlaylist, scanWarningPlaylists, CheckError } from './check.js';
4
+ import { formatCheck, formatScan } from './format.js';
5
+ import { SpotifyConfigError } from './spotify.js';
6
+ const require = createRequire(import.meta.url);
7
+ const { version } = require('../package.json');
8
+ const HELP = `spotcheck ${version}
9
+
10
+ Checks a Spotify playlist for bot-farm patterns, using public data only.
11
+
12
+ Usage
13
+ spotcheck <playlist-url-or-id> Check one playlist
14
+ spotcheck scan <url-or-id>... Score several playlists from a warning
15
+ (or pipe links in on stdin with "scan -")
16
+ spotcheck mcp Run the MCP server on stdio
17
+
18
+ Options
19
+ --json Print the report as JSON
20
+ -h, --help Show this help
21
+ -v, --version
22
+
23
+ Environment
24
+ SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET Required. Create a Spotify developer app
25
+ at https://developer.spotify.com/dashboard
26
+ TYPESAFE_API_KEY Optional. Adds the Jev model to the score.
27
+ Without it the heuristic runs alone.
28
+ `;
29
+ function credentials() {
30
+ return {
31
+ spotifyClientId: process.env.SPOTIFY_CLIENT_ID,
32
+ spotifyClientSecret: process.env.SPOTIFY_CLIENT_SECRET,
33
+ jevApiKey: process.env.TYPESAFE_API_KEY || undefined,
34
+ };
35
+ }
36
+ async function readStdin() {
37
+ const chunks = [];
38
+ for await (const chunk of process.stdin)
39
+ chunks.push(chunk);
40
+ return Buffer.concat(chunks).toString('utf8');
41
+ }
42
+ async function main(argv) {
43
+ const json = argv.includes('--json');
44
+ const args = argv.filter(a => a !== '--json');
45
+ if (args.includes('-h') || args.includes('--help') || args.length === 0) {
46
+ process.stdout.write(HELP);
47
+ return args.length === 0 ? 2 : 0;
48
+ }
49
+ if (args.includes('-v') || args.includes('--version')) {
50
+ process.stdout.write(`${version}\n`);
51
+ return 0;
52
+ }
53
+ const [first, ...rest] = args;
54
+ if (first === 'mcp') {
55
+ const { runMcpServer } = await import('./mcp.js');
56
+ await runMcpServer();
57
+ return -1;
58
+ }
59
+ if (first === 'scan') {
60
+ if (rest.length === 0) {
61
+ process.stderr.write('Give at least one playlist link, or "-" to read links from stdin.\n');
62
+ return 2;
63
+ }
64
+ const input = rest[0] === '-' ? await readStdin() : rest;
65
+ const scan = await scanWarningPlaylists(input, credentials());
66
+ process.stdout.write(json ? `${JSON.stringify(scan, null, 2)}\n` : `${formatScan(scan)}\n`);
67
+ return 0;
68
+ }
69
+ const target = first === 'check' ? rest[0] : first;
70
+ if (!target) {
71
+ process.stderr.write('Give a playlist link or id.\n');
72
+ return 2;
73
+ }
74
+ const report = await checkPlaylist(target, credentials());
75
+ process.stdout.write(json ? `${JSON.stringify(report, null, 2)}\n` : `${formatCheck(report)}\n`);
76
+ return 0;
77
+ }
78
+ main(process.argv.slice(2)).then(code => {
79
+ if (code >= 0)
80
+ process.exitCode = code;
81
+ }, error => {
82
+ if (error instanceof CheckError || error instanceof SpotifyConfigError) {
83
+ process.stderr.write(`${error.message}\n`);
84
+ }
85
+ else {
86
+ process.stderr.write(`spotcheck failed: ${error instanceof Error ? error.message : String(error)}\n`);
87
+ }
88
+ process.exitCode = 1;
89
+ });
@@ -0,0 +1,4 @@
1
+ /** Plain-text reports for the command line tool and the MCP server. */
2
+ import type { CheckReport, ScanReport } from './check.js';
3
+ export declare function formatCheck(report: CheckReport): string;
4
+ export declare function formatScan(scan: ScanReport): string;
package/dist/format.js ADDED
@@ -0,0 +1,56 @@
1
+ /** Plain-text reports for the command line tool and the MCP server. */
2
+ const LEVEL_WORDS = { low: 'Low', medium: 'Medium', high: 'High' };
3
+ const SKIP_WORDS = {
4
+ invalid: 'not a Spotify playlist link',
5
+ duplicate: 'listed more than once',
6
+ spotify_owned: "Spotify's own playlist, which outside tools cannot read",
7
+ not_found: 'not found, it may be private or deleted',
8
+ error: 'Spotify did not answer, try again',
9
+ };
10
+ function streamFarmLine(signals) {
11
+ const pct = (n) => `${Math.round(n * 100)}%`;
12
+ return (`Stream-farm signals (measured, not scored): ${pct(signals.fanlessPlayShare)} of ${signals.sampled} sampled tracks ` +
13
+ `are played well beyond their artist's following, ${pct(signals.recentAddShare)} were added in the last 30 days, ` +
14
+ `median track popularity ${signals.medianPopularity}, median artist followers ${signals.medianArtistFollowers}.`);
15
+ }
16
+ export function formatCheck(report) {
17
+ const { playlist } = report;
18
+ const lines = [
19
+ `${playlist.name} by ${playlist.owner}`,
20
+ `${playlist.url}`,
21
+ `${playlist.followers.toLocaleString('en-GB')} followers, ${playlist.tracks.toLocaleString('en-GB')} tracks`,
22
+ '',
23
+ `Risk: ${LEVEL_WORDS[report.level]} (${report.score}/100)`,
24
+ '',
25
+ ...report.factors.map(f => `- ${f.label}: ${f.description}`),
26
+ ];
27
+ if (report.streamFarm)
28
+ lines.push('', streamFarmLine(report.streamFarm));
29
+ lines.push('', 'This shows bot-farm patterns in public data. It does not say why anything was flagged, and it cannot see inside Spotify.');
30
+ return lines.join('\n');
31
+ }
32
+ export function formatScan(scan) {
33
+ const { report } = scan;
34
+ const lines = [
35
+ `Scanned ${report.scanned} ${report.scanned === 1 ? 'playlist' : 'playlists'}, ${report.flagged} showing bot-farm patterns.`,
36
+ '',
37
+ ];
38
+ for (const row of report.rows) {
39
+ if (row.kind === 'scored') {
40
+ lines.push(`${row.score}/100 ${LEVEL_WORDS[row.level]} ${row.name} by ${row.owner} (${row.followers.toLocaleString('en-GB')} followers)`, ` ${row.reason}`, ` ${row.url}`);
41
+ }
42
+ else {
43
+ lines.push(`Skipped ${row.input}: ${SKIP_WORDS[row.why]}`);
44
+ }
45
+ }
46
+ if (scan.overCap > 0)
47
+ lines.push('', `${scan.overCap} further links were left out. The limit is 50 playlists a scan.`);
48
+ const signalled = report.rows.flatMap(row => row.kind === 'scored' && scan.streamFarm[row.playlistId] ? [{ row, s: scan.streamFarm[row.playlistId] }] : []);
49
+ if (signalled.length > 0) {
50
+ lines.push('', 'Stream-farm signals (measured, not scored):');
51
+ for (const { row, s } of signalled)
52
+ lines.push(`- ${row.name}: ${streamFarmLine(s).replace(/^Stream-farm signals \(measured, not scored\): /, '')}`);
53
+ }
54
+ lines.push('', 'This shows bot-farm patterns in public data. It does not say why a distributor flagged anything.');
55
+ return lines.join('\n');
56
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Follower-history maths: the latest follower count, a 24h/7d change, and a
3
+ * spike/drop verdict over a series of snapshots.
4
+ *
5
+ * The scorer only uses history when a caller supplies it. Nothing in this
6
+ * package stores snapshots; a caller that tracks followers over time can pass
7
+ * the series in (newest first) to add the spike and drop signals.
8
+ */
9
+ export type Snap = {
10
+ followers: number | null;
11
+ snapshot_at: string;
12
+ };
13
+ /** Spike/drop thresholds (tunable). */
14
+ export declare const SPIKE_PCT = 20;
15
+ export declare const SPIKE_ABS = 5000;
16
+ export declare const DROP_PCT = -10;
17
+ /**
18
+ * Earliest follower count that is at least `ms` old, given snapshots ordered
19
+ * newest-first. Returns null when no snapshot is that old.
20
+ */
21
+ export declare function refAtLeast(snaps: Snap[], ms: number): number | null;
22
+ /**
23
+ * Latest followers plus rounded percentage change over ~24h and ~7d.
24
+ */
25
+ export declare function trend(snaps: Snap[]): {
26
+ followers: number | null;
27
+ change24h: number | null;
28
+ change7d: number | null;
29
+ };
30
+ /**
31
+ * Spike/drop verdict, with the reference points used so a caller can quote the
32
+ * before and after numbers.
33
+ * spike: +>=SPIKE_PCT% OR +>=SPIKE_ABS followers vs ~24h ago
34
+ * drop: <=DROP_PCT% vs ~7 days ago
35
+ */
36
+ export declare function verdict(snaps: Snap[]): {
37
+ spike: boolean;
38
+ drop: boolean;
39
+ latest: number | null;
40
+ ref24h: number | null;
41
+ ref7d: number | null;
42
+ };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Follower-history maths: the latest follower count, a 24h/7d change, and a
3
+ * spike/drop verdict over a series of snapshots.
4
+ *
5
+ * The scorer only uses history when a caller supplies it. Nothing in this
6
+ * package stores snapshots; a caller that tracks followers over time can pass
7
+ * the series in (newest first) to add the spike and drop signals.
8
+ */
9
+ /** Spike/drop thresholds (tunable). */
10
+ export const SPIKE_PCT = 20;
11
+ export const SPIKE_ABS = 5000;
12
+ export const DROP_PCT = -10;
13
+ /**
14
+ * Earliest follower count that is at least `ms` old, given snapshots ordered
15
+ * newest-first. Returns null when no snapshot is that old.
16
+ */
17
+ export function refAtLeast(snaps, ms) {
18
+ const now = Date.now();
19
+ return snaps.find(s => now - new Date(s.snapshot_at).getTime() >= ms)?.followers ?? null;
20
+ }
21
+ /**
22
+ * Latest followers plus rounded percentage change over ~24h and ~7d.
23
+ */
24
+ export function trend(snaps) {
25
+ if (snaps.length === 0)
26
+ return { followers: null, change24h: null, change7d: null };
27
+ const latest = snaps[0].followers;
28
+ // `to` is compared against null rather than tested for truthiness: a playlist
29
+ // whose followers have gone to 0 is the strongest signal the product has, and
30
+ // a falsy check reported it as "no change" instead of -100%.
31
+ const pct = (from, to) => from != null && to != null && from > 0 ? Math.round(((to - from) / from) * 1000) / 10 : null;
32
+ return {
33
+ followers: latest,
34
+ change24h: pct(refAtLeast(snaps, 24 * 3600_000), latest),
35
+ change7d: pct(refAtLeast(snaps, 7 * 24 * 3600_000), latest),
36
+ };
37
+ }
38
+ /**
39
+ * Spike/drop verdict, with the reference points used so a caller can quote the
40
+ * before and after numbers.
41
+ * spike: +>=SPIKE_PCT% OR +>=SPIKE_ABS followers vs ~24h ago
42
+ * drop: <=DROP_PCT% vs ~7 days ago
43
+ */
44
+ export function verdict(snaps) {
45
+ const latest = snaps[0]?.followers ?? null;
46
+ if (latest == null)
47
+ return { spike: false, drop: false, latest, ref24h: null, ref7d: null };
48
+ const ref24h = refAtLeast(snaps, 24 * 3600_000);
49
+ const ref7d = refAtLeast(snaps, 7 * 24 * 3600_000);
50
+ const spike = ref24h != null &&
51
+ ref24h > 0 &&
52
+ (latest - ref24h >= SPIKE_ABS || ((latest - ref24h) / ref24h) * 100 >= SPIKE_PCT);
53
+ const drop = ref7d != null && ref7d > 0 && ((latest - ref7d) / ref7d) * 100 <= DROP_PCT;
54
+ return { spike, drop, latest, ref24h, ref7d };
55
+ }
@@ -0,0 +1,13 @@
1
+ export { checkPlaylist, scanWarningPlaylists, CheckError } from './check.js';
2
+ export type { CheckOptions, ScanOptions, CheckReport, ScanReport, PlaylistSummary, CheckErrorCode } from './check.js';
3
+ export { formatCheck, formatScan } from './format.js';
4
+ export { scoreWithHistory, trackListening, bandFor } from './bot-scorer.js';
5
+ export type { ScoreFactor, ScoreInput, ScoreLevel, ScoreResult } from './bot-scorer.js';
6
+ export { streamFarmSignals } from './stream-farm-signals.js';
7
+ export type { StreamFarmSignals } from './stream-farm-signals.js';
8
+ export { extractPlaylistId, SpotifyConfigError, SpotifyApiError } from './spotify.js';
9
+ export type { SpotifyCredentials } from './spotify.js';
10
+ export { MAX_SCAN_LINKS, distributorReply, removalRequest } from './warning-scan.js';
11
+ export type { FullReport, FullRow, ScoredRow, SkippedRow, DraftFields } from './warning-scan.js';
12
+ export type { Snap } from './history.js';
13
+ export type { JevResult } from './jev.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { checkPlaylist, scanWarningPlaylists, CheckError } from './check.js';
2
+ export { formatCheck, formatScan } from './format.js';
3
+ export { scoreWithHistory, trackListening, bandFor } from './bot-scorer.js';
4
+ export { streamFarmSignals } from './stream-farm-signals.js';
5
+ export { extractPlaylistId, SpotifyConfigError, SpotifyApiError } from './spotify.js';
6
+ export { MAX_SCAN_LINKS, distributorReply, removalRequest } from './warning-scan.js';
package/dist/jev.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Jev, TypeSafe's decision model, asked one typed question about a playlist:
3
+ * is its audience inorganic? Optional, and off unless the caller supplies their
4
+ * own TypeSafe API key. Without a key the heuristic scorer runs alone.
5
+ *
6
+ * Jev only sees the public playlist data the scorer already holds. Every
7
+ * failure becomes an `unavailable` result, so a caller can always fall back to
8
+ * the heuristic.
9
+ */
10
+ import { type ScoreInput } from './bot-scorer.js';
11
+ export declare const JEV_TIMEOUT_MS = 2500;
12
+ export declare const INORGANIC_QUESTION = "This Spotify playlist's audience is inorganic: bought followers, a bot farm, or a purchased batch of followers now being culled. Round package-sized follower counts, sudden 24-hour spikes, steady week-on-week follower losses and implausible follower-to-track ratios are warning signs. So is a large following whose tracks have near-zero Spotify popularity (a median track popularity close to 0 out of 100), because real followers play what they follow. Small personal playlists with few followers are normal and not inorganic.";
13
+ export type JevUnavailableReason = 'timeout' | 'rate_limited' | 'auth' | 'no_credit' | 'error';
14
+ export type JevResult = {
15
+ status: 'ok';
16
+ probability: number;
17
+ inputTokens?: number;
18
+ } | {
19
+ status: 'unavailable';
20
+ reason: JevUnavailableReason;
21
+ };
22
+ export type JevOptions = {
23
+ /** Your own TypeSafe API key. Without one, askJev returns `unavailable` and sends nothing. */
24
+ apiKey?: string;
25
+ timeoutMs?: number;
26
+ fetch?: typeof fetch;
27
+ };
28
+ /** Newest-first follower history, as days ago, so Jev reads recency directly. */
29
+ export declare function jevState(input: ScoreInput, now?: number): string;
30
+ export declare function jevRequestBody(input: ScoreInput, now?: number): string;
31
+ /** Never throws. Retries 429/529s only while the timeout budget allows. */
32
+ export declare function askJev(input: ScoreInput, options?: JevOptions): Promise<JevResult>;
package/dist/jev.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Jev, TypeSafe's decision model, asked one typed question about a playlist:
3
+ * is its audience inorganic? Optional, and off unless the caller supplies their
4
+ * own TypeSafe API key. Without a key the heuristic scorer runs alone.
5
+ *
6
+ * Jev only sees the public playlist data the scorer already holds. Every
7
+ * failure becomes an `unavailable` result, so a caller can always fall back to
8
+ * the heuristic.
9
+ */
10
+ import { trackListening } from './bot-scorer.js';
11
+ const TYPESAFE_URL = 'https://api.typesafe.ai/v1/systemone';
12
+ /** Pinned: aliases like jev-latest move underneath a caller without notice. */
13
+ const MODEL_ID = 'jev-1.13.0';
14
+ export const JEV_TIMEOUT_MS = 2500;
15
+ const BACKOFF_BASE_MS = 200;
16
+ const DAY_MS = 86_400_000;
17
+ export const INORGANIC_QUESTION = "This Spotify playlist's audience is inorganic: bought followers, a bot farm, or a purchased batch of followers now being culled. Round package-sized follower counts, sudden 24-hour spikes, steady week-on-week follower losses and implausible follower-to-track ratios are warning signs. So is a large following whose tracks have near-zero Spotify popularity (a median track popularity close to 0 out of 100), because real followers play what they follow. Small personal playlists with few followers are normal and not inorganic.";
18
+ const unavailable = (reason) => ({ status: 'unavailable', reason });
19
+ /** Newest-first follower history, as days ago, so Jev reads recency directly. */
20
+ export function jevState(input, now = Date.now()) {
21
+ const history = (input.snapshots ?? []).map(s => ({
22
+ days_ago: Math.round(((now - Date.parse(s.snapshot_at)) / DAY_MS) * 10) / 10,
23
+ followers: s.followers,
24
+ }));
25
+ const listening = trackListening(input.trackPopularity);
26
+ return JSON.stringify({
27
+ playlist_name: input.name ?? '',
28
+ description: input.description ?? '',
29
+ followers: input.followers,
30
+ tracks: input.tracks,
31
+ follower_history_newest_first: history,
32
+ ...(listening && {
33
+ median_track_popularity_0_to_100: listening.medianPopularity,
34
+ share_of_tracks_with_popularity_5_or_less: listening.nearZeroShare,
35
+ }),
36
+ });
37
+ }
38
+ export function jevRequestBody(input, now = Date.now()) {
39
+ return JSON.stringify({
40
+ model: MODEL_ID,
41
+ state: jevState(input, now),
42
+ questions: { inorganic: { type: 'noul', instructions: INORGANIC_QUESTION } },
43
+ });
44
+ }
45
+ function reasonForStatus(status) {
46
+ if (status === 401)
47
+ return 'auth';
48
+ if (status === 429)
49
+ return 'rate_limited';
50
+ return 'error';
51
+ }
52
+ function parseAnswer(body) {
53
+ const answer = body?.answers?.inorganic;
54
+ const probability = answer?.noul;
55
+ if (typeof probability !== 'number' || !(probability >= 0 && probability <= 1)) {
56
+ return unavailable('error');
57
+ }
58
+ const inputTokens = body.usage?.input_tokens;
59
+ return typeof inputTokens === 'number'
60
+ ? { status: 'ok', probability, inputTokens }
61
+ : { status: 'ok', probability };
62
+ }
63
+ async function settle(res) {
64
+ if (!res.ok)
65
+ return unavailable(reasonForStatus(res.status));
66
+ return parseAnswer(await res.json().catch(() => null));
67
+ }
68
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
69
+ /** TypeSafe returns 429 (rate limit) and 529 (overloaded) as retryable. */
70
+ const isRetryableStatus = (status) => status === 429 || status === 529;
71
+ async function postWithBackoff(apiKey, body, signal, deadline, fetchImpl) {
72
+ for (let attempt = 0;; attempt++) {
73
+ const res = await fetchImpl(TYPESAFE_URL, {
74
+ method: 'POST',
75
+ headers: {
76
+ Authorization: `Bearer ${apiKey}`,
77
+ 'content-type': 'application/json',
78
+ },
79
+ body,
80
+ signal,
81
+ });
82
+ if (!isRetryableStatus(res.status))
83
+ return settle(res);
84
+ const wait = BACKOFF_BASE_MS * 2 ** attempt;
85
+ if (Date.now() + wait >= deadline)
86
+ return unavailable(reasonForStatus(res.status));
87
+ await sleep(wait);
88
+ }
89
+ }
90
+ /** Never throws. Retries 429/529s only while the timeout budget allows. */
91
+ export async function askJev(input, options = {}) {
92
+ const apiKey = options.apiKey || null;
93
+ if (!apiKey)
94
+ return unavailable('auth');
95
+ const timeoutMs = options.timeoutMs ?? JEV_TIMEOUT_MS;
96
+ const controller = new AbortController();
97
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
98
+ try {
99
+ return await postWithBackoff(apiKey, jevRequestBody(input), controller.signal, Date.now() + timeoutMs, options.fetch ?? fetch);
100
+ }
101
+ catch {
102
+ return unavailable(controller.signal.aborted ? 'timeout' : 'error');
103
+ }
104
+ finally {
105
+ clearTimeout(timer);
106
+ }
107
+ }
@@ -0,0 +1,2 @@
1
+ /** True when the User-Agent is clearly not a human in a browser. */
2
+ export declare function isLikelyLinkScanner(userAgent: string | null | undefined): boolean;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Link scanners and monitoring bots, kept in one place.
3
+ *
4
+ * Mail security appliances, link previewers and crawlers open every URL they
5
+ * see. A tool that counts visits or clicks needs to tell those apart from a
6
+ * person. This list matches non-browser user agents only, so a human in
7
+ * Safari, Chrome, Firefox or Edge is never filtered. A missing user agent is
8
+ * treated as suspicious, because every real browser sends one.
9
+ */
10
+ const LINK_SCANNER_PATTERNS = [
11
+ // Email security appliances and link sandboxes. These are the ones that
12
+ // actually pre-open marketing links.
13
+ /proofpoint/i,
14
+ /urldefense/i,
15
+ /barracuda/i,
16
+ /mimecast/i,
17
+ /outsidesecurity|symantec|messagelabs/i,
18
+ /forcepoint|websense/i,
19
+ /trendmicro|trend micro/i,
20
+ // Mail clients and providers prefetching links to build previews.
21
+ /googleimageproxy/i,
22
+ /yahoomailproxy/i,
23
+ /feedfetcher/i,
24
+ /outlook-ios|outlook-android|microsoft office|ms-office/i,
25
+ // Search, social and chat unfurlers.
26
+ /googlebot|bingbot|duckduckbot|baiduspider|yandexbot|petalbot|bytespider/i,
27
+ /slurp/i,
28
+ /facebookexternalhit|facebookcatalog/i,
29
+ /twitterbot|linkedinbot|slackbot|discordbot|telegrambot|whatsapp/i,
30
+ /applebot|skypeuripreview/i,
31
+ // SEO and analytics crawlers.
32
+ /ahrefsbot|semrushbot|mj12bot|dotbot|seokicks|screaming frog/i,
33
+ // Uptime monitors, which hit every URL on a schedule.
34
+ /pingdom|uptimerobot|statuscake|better uptime|betterstack|checkly|hetrix/i,
35
+ // Headless browsers and plain HTTP clients.
36
+ /headlesschrome|phantomjs|puppeteer|playwright|selenium/i,
37
+ /python-requests|aiohttp|httpx|curl\/|wget\/|go-http-client|java\/|okhttp/i,
38
+ /node-fetch|undici|axios|got \(/i,
39
+ // Performance and screenshot tooling.
40
+ /vercel-screenshot|chrome-lighthouse|lighthouse/i,
41
+ // AI crawlers and assistant fetchers. Most wear a browser-shaped
42
+ // "Mozilla/5.0 ... (compatible; X)" UA, so no pattern above catches them.
43
+ /gptbot|chatgpt-user|oai-searchbot|claudebot|claude-user|claude-searchbot|anthropic-ai/i,
44
+ /perplexitybot|perplexity-user|ccbot|amazonbot|meta-externalagent|meta-externalfetcher/i,
45
+ /googleother|google-inspectiontool|diffbot|youbot|cohere-ai|ai2bot|timpibot|imagesiftbot/i,
46
+ /duckassistbot|mistralai-user|omgili|bravebot|kagibot/i,
47
+ // Catch-alls for crawlers not named above. A browser never puts a "+http"
48
+ // contact URL, "crawler", "spider" or a "somethingbot/1.0" token in its UA.
49
+ /\+https?:\/\/|crawler|spider|bot\//i,
50
+ ];
51
+ /** True when the User-Agent is clearly not a human in a browser. */
52
+ export function isLikelyLinkScanner(userAgent) {
53
+ if (!userAgent || !userAgent.trim())
54
+ return true;
55
+ return LINK_SCANNER_PATTERNS.some(pattern => pattern.test(userAgent));
56
+ }
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Local stdio MCP server. It runs on your machine with your own Spotify
3
+ * credentials; nothing is sent to anyone else. Stdout carries JSON-RPC only.
4
+ * The server starts and lists its tools without credentials and fails at call
5
+ * time with a clear message.
6
+ */
7
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
+ export declare function createServer(): McpServer;
9
+ export declare function runMcpServer(): Promise<void>;
package/dist/mcp.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Local stdio MCP server. It runs on your machine with your own Spotify
3
+ * credentials; nothing is sent to anyone else. Stdout carries JSON-RPC only.
4
+ * The server starts and lists its tools without credentials and fails at call
5
+ * time with a clear message.
6
+ */
7
+ import { createRequire } from 'node:module';
8
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
9
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
10
+ import { z } from 'zod';
11
+ import { checkPlaylist, scanWarningPlaylists, CheckError } from './check.js';
12
+ import { formatCheck, formatScan } from './format.js';
13
+ import { SpotifyConfigError } from './spotify.js';
14
+ const require = createRequire(import.meta.url);
15
+ const { version } = require('../package.json');
16
+ function credentials() {
17
+ return {
18
+ spotifyClientId: process.env.SPOTIFY_CLIENT_ID,
19
+ spotifyClientSecret: process.env.SPOTIFY_CLIENT_SECRET,
20
+ jevApiKey: process.env.TYPESAFE_API_KEY || undefined,
21
+ };
22
+ }
23
+ async function run(work) {
24
+ try {
25
+ return { content: [{ type: 'text', text: await work() }] };
26
+ }
27
+ catch (error) {
28
+ const message = error instanceof CheckError || error instanceof SpotifyConfigError
29
+ ? error.message
30
+ : `Check failed: ${error instanceof Error ? error.message : String(error)}`;
31
+ return { content: [{ type: 'text', text: message }], isError: true };
32
+ }
33
+ }
34
+ export function createServer() {
35
+ const server = new McpServer({ name: 'spotcheck', version });
36
+ server.registerTool('check_playlist', {
37
+ title: 'Check a Spotify playlist',
38
+ description: 'Score one public Spotify playlist for bot-farm patterns using public data. Returns a risk level, a 0 to 100 score and the signals behind it. Spotify-owned editorial playlists cannot be read.',
39
+ inputSchema: { url: z.string().describe('A Spotify playlist URL, URI or 22 character id') },
40
+ annotations: { readOnlyHint: true, openWorldHint: true },
41
+ }, ({ url }) => run(async () => formatCheck(await checkPlaylist(url, credentials()))));
42
+ server.registerTool('scan_warning_playlists', {
43
+ title: 'Scan playlists after an artificial streaming warning',
44
+ description: 'Score up to 50 Spotify playlists at once, for example the playlists listed in Spotify for Artists after a distributor warns about artificial streams. Returns them ranked by score.',
45
+ inputSchema: {
46
+ links: z.string().describe('Spotify playlist links or ids, separated by spaces, commas or new lines'),
47
+ },
48
+ annotations: { readOnlyHint: true, openWorldHint: true },
49
+ }, ({ links }) => run(async () => formatScan(await scanWarningPlaylists(links, credentials()))));
50
+ return server;
51
+ }
52
+ export async function runMcpServer() {
53
+ await createServer().connect(new StdioServerTransport());
54
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The playlist verdict every check returns: the heuristic score, lifted by Jev
3
+ * when Jev rates the audience as inorganic. Jev can raise a score to a floor but
4
+ * never lower one, and an unavailable Jev leaves the heuristic untouched.
5
+ * Jev runs only when the caller passes a key.
6
+ */
7
+ import { type ScoreInput, type ScoreResult } from './bot-scorer.js';
8
+ import { type JevOptions, type JevResult } from './jev.js';
9
+ import type { Snap } from './history.js';
10
+ import type { PlaylistFull } from './spotify.js';
11
+ export declare const JEV_MEDIUM_PROBABILITY = 0.3;
12
+ export declare const JEV_HIGH_PROBABILITY = 0.6;
13
+ export declare const JEV_FACTOR_LABEL = "Audience pattern looks inorganic";
14
+ export type PlaylistVerdict = ScoreResult & {
15
+ jev: JevResult;
16
+ };
17
+ /**
18
+ * Below this many followers Jev never lifts a score. Artificial streams reach an
19
+ * artist through a playlist's followers, and a few dozen followers cannot carry
20
+ * a meaningful number of them, so there is nothing to warn a buyer about. Small
21
+ * playlists are also where Jev and the heuristic misread personal, organic
22
+ * lists as suspicious.
23
+ */
24
+ export declare const JEV_MIN_FOLLOWERS = 1000;
25
+ export declare function combineWithJev(result: ScoreResult, jev: JevResult, followers: number): ScoreResult;
26
+ export declare function scoreInputFor(playlist: PlaylistFull, snapshots?: Snap[]): ScoreInput;
27
+ export declare function scorePlaylist(input: ScoreInput, jevOptions?: JevOptions): Promise<PlaylistVerdict>;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The playlist verdict every check returns: the heuristic score, lifted by Jev
3
+ * when Jev rates the audience as inorganic. Jev can raise a score to a floor but
4
+ * never lower one, and an unavailable Jev leaves the heuristic untouched.
5
+ * Jev runs only when the caller passes a key.
6
+ */
7
+ import { bandFor, NO_RED_FLAGS_LABEL, scoreWithHistory, } from './bot-scorer.js';
8
+ import { askJev } from './jev.js';
9
+ export const JEV_MEDIUM_PROBABILITY = 0.3;
10
+ export const JEV_HIGH_PROBABILITY = 0.6;
11
+ const MEDIUM_FLOOR = 25;
12
+ const HIGH_FLOOR = 50;
13
+ export const JEV_FACTOR_LABEL = 'Audience pattern looks inorganic';
14
+ /**
15
+ * Below this many followers Jev never lifts a score. Artificial streams reach an
16
+ * artist through a playlist's followers, and a few dozen followers cannot carry
17
+ * a meaningful number of them, so there is nothing to warn a buyer about. Small
18
+ * playlists are also where Jev and the heuristic misread personal, organic
19
+ * lists as suspicious.
20
+ */
21
+ export const JEV_MIN_FOLLOWERS = 1000;
22
+ const HIGH_LIFT = {
23
+ floor: HIGH_FLOOR,
24
+ level: 'danger',
25
+ description: "Our pattern model rates this playlist's follower history and counts as very likely bought or botted.",
26
+ };
27
+ const MEDIUM_LIFT = {
28
+ floor: MEDIUM_FLOOR,
29
+ level: 'warning',
30
+ description: "Our pattern model rates this playlist's follower history and counts as likely bought or botted.",
31
+ };
32
+ /**
33
+ * A medium lift needs the heuristic to have seen at least one warning sign.
34
+ * On 22 Sep 2026 a clean, organic-looking indie playlist (59,813 followers,
35
+ * 383 tracks) scored exactly 0.30, the same band as the corpus bots Jev caught,
36
+ * and every one of those bots also carried one weak heuristic signal.
37
+ */
38
+ function liftFor(probability, heuristicSawWarning, followers) {
39
+ if (followers < JEV_MIN_FOLLOWERS)
40
+ return null;
41
+ if (probability >= JEV_HIGH_PROBABILITY)
42
+ return HIGH_LIFT;
43
+ if (probability >= JEV_MEDIUM_PROBABILITY && heuristicSawWarning)
44
+ return MEDIUM_LIFT;
45
+ return null;
46
+ }
47
+ export function combineWithJev(result, jev, followers) {
48
+ if (jev.status !== 'ok')
49
+ return result;
50
+ const lift = liftFor(jev.probability, result.score > 0, followers);
51
+ if (!lift)
52
+ return result;
53
+ const score = Math.max(result.score, lift.floor);
54
+ const factor = { label: JEV_FACTOR_LABEL, level: lift.level, description: lift.description };
55
+ return {
56
+ ...result,
57
+ score,
58
+ level: bandFor(score),
59
+ factors: [...result.factors.filter(f => f.label !== NO_RED_FLAGS_LABEL), factor],
60
+ };
61
+ }
62
+ export function scoreInputFor(playlist, snapshots = []) {
63
+ return {
64
+ name: playlist.name ?? undefined,
65
+ description: playlist.description,
66
+ followers: playlist.followers.total,
67
+ tracks: playlist.tracks.total,
68
+ trackPopularity: playlist.trackPopularity,
69
+ snapshots,
70
+ };
71
+ }
72
+ export async function scorePlaylist(input, jevOptions = {}) {
73
+ const jev = await askJev(input, jevOptions);
74
+ return { ...combineWithJev(scoreWithHistory(input), jev, input.followers), jev };
75
+ }