Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.
JavaScript agent-skillsai-agentsai-seoclaudeclaude-codeclaude-code-pluginclaude-skillscodexcontent-marketingconversion-rate-optimizationcopywritingcursoremail-marketinggenerative-engine-optimizationgrowth-marketingmarketingmarketing-automationsaas-marketingseoskill-md
fix: authenticate GA4 Measurement Protocol independently of OAuth
Rudy Celekliaf260f85c787
diff --git a/tests/clis/ga4-mp-auth.test.cjs b/tests/clis/ga4-mp-auth.test.cjsnew file mode 100644index 0000000..7fa296a--- /dev/null+++ b/tests/clis/ga4-mp-auth.test.cjs@@ -0,0 +1,51 @@+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/ga4.js')+function run(argv, env, response = "throw new Error('unexpected network request')") {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'marketing-cli-'))+ 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, value] of Object.entries(env)) if (value === 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 mpArgs=['events','send','--measurement-id','G-FIXTURE','--api-secret','fixture-secret','--client-id','123.456','--event-name','purchase']+test('Measurement Protocol works with its API secret and no OAuth token', () => {+ const result=run(mpArgs,{GA4_ACCESS_TOKEN:undefined},`+ const query=new URL(url).searchParams; assert.equal(query.get('api_secret'),'fixture-secret');+ assert.equal(opts.headers.Authorization,undefined); assert.equal(opts.method,'POST');+ assert.equal(JSON.parse(opts.body).events[0].name,'purchase');+ return new Response(null,{status:204});`)+ assert.deepEqual(value(result),{status:204,success:true})+})+test('Measurement Protocol dry-run needs no unrelated OAuth token and masks secret', () => {+ const result=run([...mpArgs,'--dry-run'],{GA4_ACCESS_TOKEN:undefined})+ assert.equal(value(result)._dry_run,true)+ assert.equal(new URL(value(result).url).searchParams.get('api_secret'),'***')+ assert.equal(result.stdout.includes('fixture-secret'),false)+})+test('report commands still reject absent OAuth before any request', () => {+ const result=run(['reports','run','--property','123'],{GA4_ACCESS_TOKEN:undefined})+ assert.equal(result.status,1)+ assert.match(result.stderr,/GA4_ACCESS_TOKEN/)+})+test('report commands continue using OAuth when configured', () => {+ const result=run(['reports','run','--property','123'],{GA4_ACCESS_TOKEN:'fixture-token'},`+ assert.equal(opts.headers.Authorization,'Bearer fixture-token');+ return new Response(JSON.stringify({rows:[]}));`)+ assert.deepEqual(value(result),{rows:[]})+})diff --git a/tools/clis/ga4.js b/tools/clis/ga4.jsindex ed91886..8c44c24 100755--- a/tools/clis/ga4.js+++ b/tools/clis/ga4.js@@ -5,11 +5,6 @@ const DATA_API = 'https://analyticsdata.googleapis.com/v1beta'const ADMIN_API = 'https://analyticsadmin.googleapis.com/v1beta'const MP_URL = 'https://www.google-analytics.com/mp/collect'-if (!ACCESS_TOKEN) {- console.error(JSON.stringify({ error: 'GA4_ACCESS_TOKEN environment variable required' }))- process.exit(1)-}-async function api(method, baseUrl, path, body) {if (args['dry-run']) {return { _dry_run: true, method, url: `${baseUrl}${path}`, headers: { Authorization: '***', 'Content-Type': 'application/json' }, body: body || undefined }@@ -72,6 +67,12 @@ function parseArgs(args) {const args = parseArgs(process.argv.slice(2))const [cmd, sub, ...rest] = args._+// Measurement Protocol uses its API secret, independently of OAuth.+if (!ACCESS_TOKEN && !(cmd === 'events' && sub === 'send')) {+ console.error(JSON.stringify({ error: 'GA4_ACCESS_TOKEN environment variable required' }))+ process.exit(1)+}+async function main() {let resultdiff --git a/tools/integrations/ga4.md b/tools/integrations/ga4.mdindex f1b976b..a15f9be 100644--- a/tools/integrations/ga4.md+++ b/tools/integrations/ga4.md@@ -13,9 +13,12 @@ Web analytics platform for tracking user behavior, conversions, and marketing pe## Authentication-- **Type**: OAuth 2.0 or Service Account+- **Data/Admin APIs**: OAuth 2.0 or Service Account- **Scopes**: `https://www.googleapis.com/auth/analytics.readonly` (read), `https://www.googleapis.com/auth/analytics.edit` (write)- **Setup**: Create credentials in Google Cloud Console+- **Measurement Protocol**: Authenticate with a stream API secret and measurement ID,+ independently of OAuth. The CLI `events send` command requires `--api-secret`,+ `--measurement-id`, and `--client-id`; it does not require `GA4_ACCESS_TOKEN`.## Common Agent Operations