Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions src/frameworks/flutter/flutter-wizard-agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/* Flutter wizard using posthog-agent with PostHog MCP */
import type { WizardRunOptions } from '@utils/types';
import type { FrameworkConfig } from '@lib/framework-config';
import { Integration } from '@lib/constants';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { pubPackageManager } from '@lib/detection/package-manager';

/** Platform subtrees `flutter create` scaffolds; each needs its own setup notes. */
const FLUTTER_PLATFORM_DIRS = [
'android',
'ios',
'web',
'macos',
'linux',
'windows',
] as const;

type FlutterContext = {
platforms?: string[];
};

function readPubspec(installDir: string): string | undefined {
const pubspecPath = path.join(installDir, 'pubspec.yaml');
if (!fs.existsSync(pubspecPath)) return undefined;
return fs.readFileSync(pubspecPath, 'utf-8');
}

export const FLUTTER_AGENT_CONFIG: FrameworkConfig<FlutterContext> = {
metadata: {
name: 'Flutter',
integration: Integration.flutter,
docsUrl: 'https://posthog.com/docs/libraries/flutter',
gatherContext: (options: WizardRunOptions) => {
const platforms = FLUTTER_PLATFORM_DIRS.filter((dir) =>
fs.existsSync(path.join(options.installDir, dir)),
);
return Promise.resolve({ platforms });
},
},

detection: {
packageName: 'posthog_flutter',
packageDisplayName: 'Flutter',
usesPackageJson: false,
getVersion: () => undefined,
detectPackageManager: pubPackageManager,
// A pubspec.yaml alone is any Dart project; depending on the Flutter SDK
// (`sdk: flutter`) is what makes it a Flutter app. Anchored to a key/value
// line so comments (`# sdk: flutter`) don't match.
detect: (options) => {
const pubspec = readPubspec(options.installDir);
return Promise.resolve(/^\s*sdk:\s*flutter\s*$/m.test(pubspec ?? ''));
},
},

environment: {
uploadToHosting: false,
getEnvVars: (apiKey: string, host: string) => ({
POSTHOG_PROJECT_TOKEN: apiKey,
POSTHOG_HOST: host,
}),
},

analytics: {
getTags: (context) => ({
...(context.platforms?.length
? { platforms: context.platforms.join(',') }
: {}),
}),
},

prompts: {
projectTypeDetection:
'This is a Flutter project. Look for pubspec.yaml declaring a dependency on the Flutter SDK (flutter: sdk: flutter) and a lib/ directory with Dart source files to confirm.',
packageInstallation:
'Add the PostHog Flutter SDK with `flutter pub add posthog_flutter`. Do not edit pubspec.yaml by hand; the pub tool updates it and resolves the version automatically.',
getAdditionalContextLines: (context) => {
const lines = [
'Framework docs ID: flutter (use posthog://docs/frameworks/flutter for documentation)',
'Prefer manual initialization in Dart (PostHogConfig + Posthog().setup) over the platform auto-init so configuration lives in one place; when doing so, disable auto-init in the Android manifest and iOS Info.plist per the docs.',
];

if (context.platforms?.length) {
lines.push(
`Enabled target platforms: ${context.platforms.join(
', ',
)}. Apply the platform-specific setup steps from the docs for each (e.g. AndroidManifest.xml on Android, Info.plist on iOS/macOS, the JS snippet in web/index.html for web).`,
);
}

return lines;
},
},

ui: {
successMessage: 'PostHog integration complete',
estimatedDurationMinutes: 5,
getOutroChanges: () => [
'Analyzed your Flutter project structure',
'Added the posthog_flutter SDK to your pubspec',
'Configured PostHog initialization',
'Added event capture and user identification',
],
getOutroNextSteps: () => [
'Run your app to see PostHog in action',
'Visit your PostHog dashboard to see incoming events',
'Check out the PostHog Flutter docs for session replay, feature flags, and more',
],
},
};
17 changes: 17 additions & 0 deletions src/lib/__tests__/wizard-can-use-tool.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,23 @@ describe('bash fence — allows real toolchain commands (from skills + field log
expect(allow('mvn -B compile')).toBe('allow');
expect(allow('mvn dependency:tree')).toBe('allow');
});

it('flutter/dart ecosystem (the flutter field-log denial)', () => {
expect(allow('flutter pub add posthog_flutter')).toBe('allow');
expect(allow('flutter pub get')).toBe('allow');
expect(allow('flutter pub remove posthog_flutter')).toBe('allow');
expect(allow('flutter analyze')).toBe('allow');
expect(allow('flutter build apk --debug')).toBe('allow');
expect(allow('flutter clean')).toBe('allow');
expect(allow('dart pub add posthog_flutter')).toBe('allow');
expect(allow('dart pub get')).toBe('allow');
expect(allow('dart analyze')).toBe('allow');
// Arbitrary code execution stays out of contract, like xcodebuild test.
expect(allow('flutter run')).toBe('deny');
expect(allow('flutter test')).toBe('deny');
expect(allow('dart run bin/main.dart')).toBe('deny');
expect(allow('flutter pub run build_runner build')).toBe('deny');
});
});

describe('bash fence — attack corpus (one test per bypass vector)', () => {
Expand Down
31 changes: 30 additions & 1 deletion src/lib/agent/bash-fence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ const SIMPLE_MANAGERS: Record<string, readonly string[]> = {
xcodegen: ['generate'],
};

// `pub run` executes arbitrary packages, so it is excluded like npm exec.
const PUB_SUBCOMMANDS = ['add', 'remove', 'get', 'upgrade', 'outdated', 'deps'];
// flutter/dart verbs beyond `pub`. build (native build scripts) and analyze
// (analyzer plugins) can run project-defined code, same contract as
// `xcodebuild build`/`gradle assemble`. run/test/`pub run` are excluded only
// because they execute *arbitrary* code by design, like `xcodebuild test`.
const FLUTTER_DART_SUBCOMMANDS = ['analyze', 'build', 'clean', 'doctor'];

// Gradle tasks are verb-anchored camelCase: assembleDebug yes, publishToMavenCentral no.
const GRADLE_EXACT_TASKS = new Set(['build', 'clean', 'dependencies']);
const GRADLE_TASK_VERBS = ['assemble', 'compile', 'bundle', 'lint'];
Expand All @@ -111,7 +119,8 @@ const ALLOWED_TOOLS_SUMMARY =
'composer (install|require|update|remove|show), bundle (install|add|remove|update|show|exec <lint tool>), ' +
'gem (install|uninstall|list|search), swift (package|build), pod (install|update|search), carthage (bootstrap|update), ' +
'xcodegen (generate), xcodebuild (build/clean/archive actions), gradle/gradlew (build|clean|dependencies|assemble*/compile*/bundle*/lint* tasks), ' +
'mvn (install|compile|package|verify|dependency:tree).';
'mvn (install|compile|package|verify|dependency:tree), ' +
'flutter/dart (pub add/remove/get/upgrade/outdated/deps, analyze, build, clean, doctor).';

function deny(analyticsReason: string, message: string): BashFenceDecision {
return { allowed: false, message, analyticsReason };
Expand Down Expand Up @@ -315,6 +324,26 @@ function commandDecision(command: string): BashFenceDecision {
)}>, -m compileall <files>, -m <lint tool>, manage.py check.`,
);
}
if (bin === 'flutter' || bin === 'dart') {
if (parts[1] === 'pub') {
if (parts[2] && PUB_SUBCOMMANDS.includes(parts[2]))
return { allowed: true };
return denyCommand(
command,
`Allowed ${bin} pub subcommands: ${PUB_SUBCOMMANDS.join(', ')}.`,
);
}
if (parts[1] && FLUTTER_DART_SUBCOMMANDS.includes(parts[1]))
return { allowed: true };
return denyCommand(
command,
`Allowed ${bin} usage: ${bin} pub <${PUB_SUBCOMMANDS.join(
'|',
)}>, or ${bin} <${FLUTTER_DART_SUBCOMMANDS.join(
'|',
)}>. run/test execute arbitrary code and are not allowed.`,
);
}
if (bin === 'uv' && parts[1] === 'pip') {
if (parts[2] && PIP_SUBCOMMANDS.includes(parts[2]))
return { allowed: true };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const INTEGRATION_ENTRIES = [
{ id: 'integration-go' },
{ id: 'integration-swift', framework: 'swift' },
{ id: 'integration-kmp', framework: 'kmp' },
{ id: 'integration-flutter' },
{ id: 'integration-flutter', framework: 'flutter' },
{ id: 'integration-react-native', framework: 'react-native', default: true },
{ id: 'integration-expo', framework: 'react-native' },
{ id: 'integration-astro-static', framework: 'astro' },
Expand Down
1 change: 1 addition & 0 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export enum Integration {
fastapi = 'fastapi',
laravel = 'laravel',
sveltekit = 'sveltekit',
flutter = 'flutter',
kmp = 'kmp',
swift = 'swift',
android = 'android',
Expand Down
65 changes: 62 additions & 3 deletions src/lib/detection/__tests__/framework.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { detectFramework } from '@lib/detection/framework';
import { Integration } from '@lib/constants';
import { ANDROID_AGENT_CONFIG } from '../../../frameworks/android/android-wizard-agent';
import { KMP_AGENT_CONFIG } from '../../../frameworks/kmp/kmp-wizard-agent';
import { FLUTTER_AGENT_CONFIG } from '../../../frameworks/flutter/flutter-wizard-agent';

/** A throwaway project dir seeded with the given files. */
function makeProject(files: Record<string, string>): string {
Expand Down Expand Up @@ -54,6 +55,17 @@ describe('Integration enum order (drives first-match detection)', () => {
expect(order[order.length - 1]).toBe(Integration.javascriptNode);
});

test('flutter is ordered before android and swift (its subtrees look native)', () => {
// A Flutter project carries android/ and ios/ subtrees that would
// otherwise match the native detectors.
expect(order.indexOf(Integration.flutter)).toBeLessThan(
order.indexOf(Integration.android),
);
expect(order.indexOf(Integration.flutter)).toBeLessThan(
order.indexOf(Integration.swift),
);
});

test('kmp is ordered before android and swift (more specific detection wins)', () => {
// A KMP project also looks like an Android/Swift project, so KMP must be
// checked first for first-match detection to resolve it correctly.
Expand Down Expand Up @@ -137,14 +149,61 @@ describe('detectFramework (end-to-end over real project dirs)', () => {
);
});

test('a Flutter project is not claimed by anything', async () => {
test('a Flutter project resolves to flutter, not its android/ subtree', async () => {
const opts = project({
'pubspec.yaml': 'name: my_flutter_app\nenvironment:\n sdk: ^3.0.0\n',
'pubspec.yaml': FLUTTER_PUBSPEC,
'android/build.gradle': `plugins { id 'com.android.application' }`,
'android/app/src/main/AndroidManifest.xml': '<manifest/>',
'android/app/src/main/kotlin/MainActivity.kt': 'class MainActivity',
});
await expect(detectFramework(opts.installDir)).resolves.toBeUndefined();
await expect(detectFramework(opts.installDir)).resolves.toBe(
Integration.flutter,
);
});
});

const FLUTTER_PUBSPEC =
'name: my_flutter_app\n' +
'environment:\n' +
' sdk: ^3.0.0\n' +
'dependencies:\n' +
' flutter:\n' +
' sdk: flutter\n';

describe('flutter detect', () => {
const detect = FLUTTER_AGENT_CONFIG.detection.detect;

test('claims a project whose pubspec depends on the Flutter SDK', async () => {
const opts = project({ 'pubspec.yaml': FLUTTER_PUBSPEC });
await expect(detect(opts)).resolves.toBe(true);
});

test('does not claim a pure Dart project', async () => {
const opts = project({
'pubspec.yaml': 'name: my_dart_cli\nenvironment:\n sdk: ^3.0.0\n',
});
await expect(detect(opts)).resolves.toBe(false);
});

test('does not claim a project without a pubspec', async () => {
const opts = project({ 'package.json': '{}' });
await expect(detect(opts)).resolves.toBe(false);
});

test('does not claim a commented-out flutter dependency', async () => {
const opts = project({
'pubspec.yaml':
'name: my_dart_cli\ndependencies:\n# sdk: flutter removed\n',
});
await expect(detect(opts)).resolves.toBe(false);
});

test('claims the YAML-legal multi-space variant', async () => {
const opts = project({
'pubspec.yaml':
'name: app\ndependencies:\n flutter:\n sdk: flutter\n',
});
await expect(detect(opts)).resolves.toBe(true);
});
});

Expand Down
2 changes: 2 additions & 0 deletions src/lib/detection/__tests__/package-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
composerPackageManager,
swiftPackageManager,
gradlePackageManager,
pubPackageManager,
} from '@lib/detection/package-manager';

vi.mock('../../../utils/debug');
Expand Down Expand Up @@ -188,6 +189,7 @@ describe('static package manager helpers', () => {
{ fn: composerPackageManager, name: 'composer' },
{ fn: swiftPackageManager, name: 'spm' },
{ fn: gradlePackageManager, name: 'gradle' },
{ fn: pubPackageManager, name: 'pub' },
])('$name returns valid PackageManagerInfo', async ({ fn }) => {
const result = await fn();
expect(result.detected).toHaveLength(1);
Expand Down
20 changes: 20 additions & 0 deletions src/lib/detection/package-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,26 @@ export function bundlerPackageManager(): Promise<PackageManagerInfo> {
});
}

// ---------------------------------------------------------------------------
// Flutter (pub) helper
// ---------------------------------------------------------------------------

const PUB: DetectedPackageManager = {
name: 'pub',
label: 'pub',
installCommand: 'flutter pub add',
runCommand: 'flutter',
};

export function pubPackageManager(): Promise<PackageManagerInfo> {
Comment thread
turnipdabeets marked this conversation as resolved.
Resolved
return Promise.resolve({
detected: [PUB],
primary: PUB,
recommendation:
'Use flutter pub add to add dependencies; it updates pubspec.yaml automatically.',
});
}

// ---------------------------------------------------------------------------
// Android (Gradle) helper
// ---------------------------------------------------------------------------
Expand Down
2 changes: 2 additions & 0 deletions src/lib/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { FLASK_AGENT_CONFIG } from '@frameworks/flask/flask-wizard-agent';
import { FASTAPI_AGENT_CONFIG } from '@frameworks/fastapi/fastapi-wizard-agent';
import { LARAVEL_AGENT_CONFIG } from '@frameworks/laravel/laravel-wizard-agent';
import { SVELTEKIT_AGENT_CONFIG } from '@frameworks/svelte/svelte-wizard-agent';
import { FLUTTER_AGENT_CONFIG } from '@frameworks/flutter/flutter-wizard-agent';
import { SWIFT_AGENT_CONFIG } from '@frameworks/swift/swift-wizard-agent';
import { KMP_AGENT_CONFIG } from '@frameworks/kmp/kmp-wizard-agent';
import { ANDROID_AGENT_CONFIG } from '@frameworks/android/android-wizard-agent';
Expand All @@ -38,6 +39,7 @@ export const FRAMEWORK_REGISTRY: Record<Integration, FrameworkConfig> = {
[Integration.fastapi]: FASTAPI_AGENT_CONFIG,
[Integration.laravel]: LARAVEL_AGENT_CONFIG,
[Integration.sveltekit]: SVELTEKIT_AGENT_CONFIG,
[Integration.flutter]: FLUTTER_AGENT_CONFIG,
[Integration.kmp]: KMP_AGENT_CONFIG,
[Integration.swift]: SWIFT_AGENT_CONFIG,
[Integration.android]: ANDROID_AGENT_CONFIG,
Expand Down
Loading