Skip to content

Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.

fix(mixpanel): prefer service accounts with legacy auth fallback

RudyCelekli5edc8a789626
diff --git a/tests/clis/mixpanel-service-first.test.cjs b/tests/clis/mixpanel-service-first.test.cjs
new file mode 100644
index 0000000..62a763f
--- /dev/null
+++ b/tests/clis/mixpanel-service-first.test.cjs
@@ -0,0 +1,83 @@
+const assert = require('node:assert/strict')
+const { spawnSync } = require('node:child_process')
+const fs = require('node:fs')
+const os = require('node:os')
+const path = require('node:path')
+const { test } = require('node:test')
+const cli = path.resolve(__dirname, '../../tools/clis/mixpanel.js')
+function run(argv, env = {}, response = "throw new Error('unexpected network request')") {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'marketing-contract-'))
+ const mock = path.join(tmp, 'fetch.cjs')
+ fs.writeFileSync(mock, `const assert = require('node:assert/strict'); global.fetch = async (url, opts) => { ${response} };`)
+ const childEnv = { ...process.env, ...env }
+ for (const [key, val] of Object.entries(env)) if (val === undefined) delete childEnv[key]
+ try {
+ return spawnSync(process.execPath, ['--require', mock, cli, ...argv], { env: childEnv, encoding: 'utf8', timeout: 10000 })
+ } finally { fs.rmSync(tmp, { recursive: true, force: true }) }
+}
+function value(result) {
+ assert.equal(result.status, 0, result.stderr)
+ return JSON.parse(result.stdout)
+}
+
+const dates = ['--from-date', '2026-09-01', '--to-date', '2026-09-30']
+const operations = [
+ ['export', 'events', ...dates],
+ ['funnels', 'get', '--funnel-id', '7', ...dates],
+ ['retention', 'get', '--born-event', 'Signup', ...dates],
+ ['query', 'events', ...dates, '--project-id', '42'],
+]
+const clean = { MIXPANEL_TOKEN: undefined, MIXPANEL_API_KEY: undefined, MIXPANEL_SECRET: undefined, MIXPANEL_PROJECT_SECRET: undefined }
+for (const argv of operations) {
+ test(`${argv[0]} keeps service account auth ahead of project secret`, () => {
+ const result = run([...argv, '--project-id', '42'], { ...clean, MIXPANEL_API_KEY: 'service-user', MIXPANEL_SECRET: 'service-secret', MIXPANEL_PROJECT_SECRET: 'legacy-secret' }, `
+ assert.equal(opts.headers.Authorization, 'Basic ' + Buffer.from('service-user:service-secret').toString('base64'));
+ if (opts.method === 'GET') assert.equal(new URL(url).searchParams.get('project_id'), '42');
+ else assert.equal(JSON.parse(opts.body).project_id, 42);
+ return new Response('{"accepted":true}');`)
+ assert.deepEqual(value(result), { accepted: true })
+ })
+ for (const key of ['MIXPANEL_PROJECT_SECRET', 'MIXPANEL_SECRET']) {
+ test(`${argv[0]} supports ${key} only when no service username is configured`, () => {
+ const result = run(argv, { ...clean, [key]: 'legacy-secret' }, `
+ assert.equal(opts.headers.Authorization, 'Basic ' + Buffer.from('legacy-secret:').toString('base64'));
+ return new Response('{"accepted":true}');`)
+ assert.deepEqual(value(result), { accepted: true })
+ })
+ }
+}
+test('incomplete service account does not downgrade to project-secret auth', () => {
+ const result = run(operations[0], { ...clean, MIXPANEL_API_KEY: 'service-user', MIXPANEL_PROJECT_SECRET: 'legacy-secret' })
+ assert.equal(result.status, 1)
+ assert.match(result.stderr, /MIXPANEL_SECRET/)
+})
+for (const argv of operations.slice(0, 3)) {
+ test(`${argv[0]} requires project selection for service accounts`, () => {
+ const result = run(argv, { ...clean, MIXPANEL_API_KEY: 'service-user', MIXPANEL_SECRET: 'service-secret' })
+ assert.equal(result.status, 1)
+ assert.match(result.stderr, /--project-id/)
+ })
+}
+test('explicit project secret takes precedence over legacy secret-only fallback', () => {
+ const result = run(operations[0], { ...clean, MIXPANEL_PROJECT_SECRET: 'explicit', MIXPANEL_SECRET: 'legacy' }, `
+ assert.equal(opts.headers.Authorization, 'Basic ' + Buffer.from('explicit:').toString('base64'));
+ return new Response('{"accepted":true}');`)
+ assert.deepEqual(value(result), { accepted: true })
+})
+test('query dry-run redacts credentials and does not fetch', () => {
+ const result = run([...operations[0], '--project-id', '42', '--dry-run'], { ...clean, MIXPANEL_API_KEY: 'service-user', MIXPANEL_SECRET: 'service-secret' })
+ assert.equal(value(result).headers.Authorization, '***')
+ assert.equal(new URL(value(result).url).searchParams.get('project_id'), '42')
+ assert.equal(result.stdout.includes('service-secret'), false)
+})
+test('tracking still uses the project token independently of query credentials', () => {
+ const result = run(['track', 'event', '--distinct-id', 'fixture', '--event', 'Signup'], { ...clean, MIXPANEL_TOKEN: 'project-token' }, `
+ assert.equal(url, 'https://api.mixpanel.com/track');
+ assert.equal(JSON.parse(opts.body)[0].properties.token, 'project-token');
+ assert.equal(opts.headers.Authorization, undefined);
+ return new Response('1');`)
+ assert.equal(value(result), 1)
+})
+test('no credentials still prints usage', () => {
+ assert.ok(value(run([], clean)).usage)
+})
diff --git a/tools/clis/mixpanel.js b/tools/clis/mixpanel.js
index f21fc26..5423cc7 100755
--- a/tools/clis/mixpanel.js
+++ b/tools/clis/mixpanel.js
@@ -4,12 +4,13 @@ const rawArgs = process.argv.slice(2)
const TOKEN = process.env.MIXPANEL_TOKEN
const API_KEY = process.env.MIXPANEL_API_KEY
const SECRET = process.env.MIXPANEL_SECRET
+const PROJECT_SECRET = process.env.MIXPANEL_PROJECT_SECRET
const INGESTION_URL = 'https://api.mixpanel.com'
const QUERY_URL = 'https://mixpanel.com/api/2.0'
const EXPORT_URL = 'https://data.mixpanel.com/api/2.0'
-if ((!TOKEN && !API_KEY) && rawArgs.length > 0) {
- console.error(JSON.stringify({ error: 'MIXPANEL_TOKEN (for ingestion) or MIXPANEL_API_KEY + MIXPANEL_SECRET (for query/export) environment variables required' }))
+if ((!TOKEN && !API_KEY && !SECRET && !PROJECT_SECRET) && rawArgs.length > 0) {
+ console.error(JSON.stringify({ error: 'MIXPANEL_TOKEN (ingestion), MIXPANEL_API_KEY + MIXPANEL_SECRET (service account), or MIXPANEL_PROJECT_SECRET (legacy project auth) required' }))
process.exit(1)
}
@@ -36,11 +37,21 @@ async function ingestApi(method, path, body) {
}
}
-async function queryApi(method, baseUrl, path, params) {
- if (!API_KEY || !SECRET) {
- return { error: 'MIXPANEL_API_KEY and MIXPANEL_SECRET required for query/export operations' }
+function queryAuth() {
+ // Existing KEY:SECRET credentials are a service account, and always win.
+ if (API_KEY) {
+ if (!SECRET) throw new Error('MIXPANEL_SECRET required with MIXPANEL_API_KEY for service-account auth')
+ if (!args['project-id']) throw new Error('--project-id required for service-account query/export operations')
+ return Buffer.from(`${API_KEY}:${SECRET}`).toString('base64')
}
- const auth = Buffer.from(`${API_KEY}:${SECRET}`).toString('base64')
+ const secret = PROJECT_SECRET || SECRET
+ if (!secret) throw new Error('Service-account credentials or MIXPANEL_PROJECT_SECRET required for query/export operations')
+ return Buffer.from(`${secret}:`).toString('base64')
+}
+
+async function queryApi(method, baseUrl, path, params) {
+ const auth = queryAuth()
+ if (args['project-id']) params.set('project_id', args['project-id'])
const url = params ? `${baseUrl}${path}?${params}` : `${baseUrl}${path}`
const headers = {
'Authorization': `Basic ${auth}`,
@@ -62,10 +73,7 @@ async function queryApi(method, baseUrl, path, params) {
}
async function queryApiPost(path, body) {
- if (!API_KEY || !SECRET) {
- return { error: 'MIXPANEL_API_KEY and MIXPANEL_SECRET required for query/export operations' }
- }
- const auth = Buffer.from(`${API_KEY}:${SECRET}`).toString('base64')
+ const auth = queryAuth()
const headers = {
'Authorization': `Basic ${auth}`,
'Content-Type': 'application/json',
@@ -233,9 +241,9 @@ async function main() {
track: 'track event --distinct-id <id> --event <name> [--properties <json>]',
profiles: 'profiles set --distinct-id <id> [--properties <json>]',
query: 'query events --project-id <id> [--event <name>] [--from-date <date>] [--to-date <date>]',
- funnels: 'funnels get --funnel-id <id> [--from-date <date>] [--to-date <date>]',
- retention: 'retention get [--from-date <date>] [--to-date <date>] [--born-event <event>]',
- export: 'export events --from-date <date> --to-date <date>',
+ funnels: 'funnels get --funnel-id <id> [--project-id <id>] [--from-date <date>] [--to-date <date>]',
+ retention: 'retention get [--project-id <id>] [--from-date <date>] [--to-date <date>] [--born-event <event>]',
+ export: 'export events --from-date <date> --to-date <date> [--project-id <id>]',
}
}
}
diff --git a/tools/integrations/mixpanel.md b/tools/integrations/mixpanel.md
index a44ca64..15d1654 100644
--- a/tools/integrations/mixpanel.md
+++ b/tools/integrations/mixpanel.md
@@ -8,14 +8,28 @@ Product analytics platform for tracking user behavior and retention.
|-------------|-----------|-------|
| API | ✓ | Ingestion API, Query API, Data Export |
| MCP | - | Not available |
-| CLI | - | Not available |
+| CLI | ✓ | [mixpanel.js](../clis/mixpanel.js) |
| SDK | ✓ | JavaScript, iOS, Android, Python, etc. |
## Authentication
- **Ingestion**: Project token (public)
-- **Query API**: Service Account (username:secret as Basic auth)
-- **Export**: API Secret
+- **Query API / Export**: Service Account (username:secret as Basic auth). Set
+ `MIXPANEL_API_KEY` to the service-account username and `MIXPANEL_SECRET` to its secret.
+ Supply `--project-id` for query/export commands; GET requests send it as `project_id`.
+- **Legacy fallback**: When `MIXPANEL_API_KEY` is absent, `MIXPANEL_PROJECT_SECRET`
+ (or `MIXPANEL_SECRET` alone) is sent as the Basic auth username with an empty password.
+ A configured service account always takes precedence; a username without its secret
+ is an error and does not fall back.
+- **Deprecation**: Project-secret authentication retires on March 3, 2027 and is
+ unavailable for new projects. Use service accounts for new integrations. See
+ [Service Accounts](https://docs.mixpanel.com/reference/service-accounts) and
+ [Project Secret](https://docs.mixpanel.com/reference/project-secret).
+
+```bash
+node tools/clis/mixpanel.js export events --project-id 123 \
+ --from-date 2024-01-01 --to-date 2024-01-31 --dry-run
+```
## Common Agent Operations
@@ -72,19 +86,19 @@ POST https://mixpanel.com/api/2.0/insights
### Get funnel data
```bash
-GET https://mixpanel.com/api/2.0/funnels?funnel_id={funnel_id}&from_date=2024-01-01&to_date=2024-01-31
+GET https://mixpanel.com/api/2.0/funnels?project_id={project_id}&funnel_id={funnel_id}&from_date=2024-01-01&to_date=2024-01-31
```
### Export raw events
```bash
-GET https://data.mixpanel.com/api/2.0/export?from_date=2024-01-01&to_date=2024-01-01
+GET https://data.mixpanel.com/api/2.0/export?project_id={project_id}&from_date=2024-01-01&to_date=2024-01-01
```
### Get retention data
```bash
-GET https://mixpanel.com/api/2.0/retention?from_date=2024-01-01&to_date=2024-01-31&retention_type=birth&born_event=signup_completed
+GET https://mixpanel.com/api/2.0/retention?project_id={project_id}&from_date=2024-01-01&to_date=2024-01-31&retention_type=birth&born_event=signup_completed
```
## JavaScript SDK