Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
03d2eaf
feat(flutter): identify Dart snapshot builds by pure APK parsing
Oct 10, 2026
2945f50
feat(flutter): inspect Dart AOT snapshots through the ELF symbol table
Oct 10, 2026
ddf1269
fix(flutter): own snapshots, bound image reads, and preserve cancella…
Oct 10, 2026
349b212
docs(flutter): cover the Italian README with the Flutter row
Oct 10, 2026
b8cbea9
fix(flutter): make the ABI pattern portable for v-mode validators
Oct 10, 2026
e12bfbf
refactor(flutter): reuse shared harnesses and deduplicate the vertical
Oct 10, 2026
2207cc6
fix(flutter): address review findings from real-app verification
Oct 11, 2026
93db928
fix(flutter): address the Codex review findings
Oct 11, 2026
eeb56f9
fix(flutter): address the second Codex review round
Oct 11, 2026
87ac338
fix(flutter): address the third Codex review round
Oct 11, 2026
24d61ec
fix(flutter): address rounds three and four of the Codex review
Oct 11, 2026
802bb9b
fix(flutter): address the fifth Codex review round
Oct 11, 2026
9603ecb
fix(flutter): address the sixth Codex review round
Oct 11, 2026
ef79672
fix(flutter): address the seventh Codex review round
Oct 11, 2026
8d9fd5b
fix(flutter): address the eighth Codex review round
Oct 11, 2026
dbdd7fc
fix(flutter): harden streaming, sizes, and cancellation after self-re…
Oct 11, 2026
c6e7325
fix(flutter): require structurally parseable ELF headers for complete…
Oct 11, 2026
cf18c8c
fix(flutter): validate ELF and snapshot coverage
Oct 11, 2026
61394b6
fix(flutter): resolve review findings and CI effect checks
Oct 11, 2026
248ce4c
chore(flutter): resolve upstream effects-audit conflict
Oct 11, 2026
8b88190
chore: merge main into Flutter analysis branch
morluto Oct 12, 2026
34e764d
fix(flutter): unify artifact ownership and bound ELF evidence
morluto Oct 12, 2026
98707b4
chore: merge latest main into Flutter analysis branch
morluto Oct 12, 2026
9089b98
fix(flutter): preserve ELF provenance and partial coverage
morluto Oct 12, 2026
ccfaec0
chore: merge latest main after documentation updates
morluto Oct 12, 2026
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
Prev Previous commit
Next Next commit
fix(flutter): address the Codex review findings
Eight findings, all applied:

- P1: SnapshotHashScanner keeps candidates in a Set (no quadratic
  Array.includes) with a 64-distinct-hash cap, so a hostile payload of
  magic+hash records cannot stall the scan or bloat the response.
- P1: projectStringPool stops admitting new distinct entries once each
  category reaches twice its projection bound and reports
  collectionCapped; allocation and sorting now track the response, not
  the payload.
- P2: ZIP reader rejections during entry iteration or entry streaming
  map into the typed error algebra (cancellation vs input refusal)
  instead of escaping as unhandled exceptions in both operations.
- P2: magic_valid now marks coverage only for the *Data symbols; a
  complete four-symbol image with valid data magics reports complete
  coverage (the instruction symbols intentionally lack the magic).
- P2: the MCP server closes the Flutter provider during shutdown, so a
  retained snapshot root is retried and reported, not leaked.
- P2: LabeledStringScanner commits matches only when a printable run is
  delimiter-terminated; the carry grows to 600 bytes so a 500-character
  toolchain line survives any chunk boundary untruncated.
- P2: both Flutter tool effects declare writesFilesystem: true; the
  owned APK snapshot and extracted libapp.so are temporary writes.
- P2: the verify lane asserts every ABI agrees on exactly one snapshot
  hash instead of discarding the computed set.
  • Loading branch information
REA Contributor me
REA Contributor authored and me committed Oct 11, 2026
commit 93db9281bcbe34f6e9d2e1785dc4091f136cab8b
6 changes: 5 additions & 1 deletion scripts/verify-flutter.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,11 @@ if (options.apk !== null) {
),
`hash=${identified.abis.find((abi) => abi.libapp.present)?.libapp.snapshot_hash}`,
);
void hashes;
check(
"every ABI agrees on one snapshot hash",
hashes.size === 1,
[...hashes].join(", "),
);
check(
"engine build-ids present and hex per ABI",
identified.abis
Expand Down
2 changes: 2 additions & 0 deletions src/contracts/toolEffects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
}),
identify_flutter_build: effects({
mutatesSession: true,
writesFilesystem: true,
}),
inspect_dart_aot: effects({
mutatesSession: true,
Comment thread
3QL marked this conversation as resolved.
Resolved
writesFilesystem: true,
}),
inspect_apktool_client: effects({
mutatesSession: true,
Expand Down
4 changes: 3 additions & 1 deletion src/flutter/FlutterBuildProvider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,9 @@ test.skipIf(process.platform === "win32")(
).toBe(true);
expect(value.string_pool.package_uri_count).toBe(2);
expect(value.string_pool.dart_uri_count).toBe(2);
expect(value.coverage).toBe("partial");
// All four symbols present, both data magics valid, pool under budget:
// the honest answer for a complete payload is complete coverage.
expect(value.coverage).toBe("complete");
},
);

Expand Down
118 changes: 109 additions & 9 deletions src/flutter/FlutterBuildProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ import {
AnalysisResourceConstraintError,
AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
import { ZipArtifactReader } from "../artifacts/ZipArtifactReader.js";
Expand Down Expand Up @@ -114,6 +115,65 @@ const emptyFacts = (): LibraryFacts => ({
},
});

/** Translate a ZIP reader rejection into the typed analysis error algebra. */
const mapReaderFailure = (
operation: string,
path: string,
cause: unknown,
): AnalysisError => {
if (
(cause instanceof Error && cause.name === "AbortError") ||
(cause as NodeJS.ErrnoException)?.code === "ABORT_ERR"
)
Comment thread
3QL marked this conversation as resolved.
Resolved
return new AnalysisCancelledError(operation, { cause });
Comment thread
3QL marked this conversation as resolved.
Resolved
const message = cause instanceof Error ? cause.message : String(cause);
return new AnalysisInputError(operation, {
cause: new Error(
`The APK could not be read as a package: ${path}: ${message}`,
),
});
};

/** Iterate ZIP entries, mapping reader failures to typed errors. */
const collectEntriesSafely = async (
reader: ZipArtifactReader,
operation: string,
path: string,
signal: AbortSignal | undefined,
): Promise<ArtifactEntry[]> => {
try {
const entries: ArtifactEntry[] = [];
for await (const entry of reader.entries(signal)) entries.push(entry);
return entries;
} catch (cause) {
throw mapReaderFailure(operation, path, cause);
}
};

/** Open one entry stream, mapping reader failures to typed errors. */
const openEntrySafely = async (
reader: ZipArtifactReader,
entry: ArtifactEntry,
operation: string,
path: string,
signal: AbortSignal | undefined,
): Promise<AsyncIterable<Buffer>> => {
const stream = await reader.open(entry, signal).catch((cause: unknown) => {
throw mapReaderFailure(operation, path, cause);
});
return {
[Symbol.asyncIterator](): AsyncIterator<Buffer> {
const iterator = stream[Symbol.asyncIterator]();
return {
next: () =>
iterator.next().catch((cause: unknown) => {
throw mapReaderFailure(operation, path, cause);
}),
Comment thread
3QL marked this conversation as resolved.
Resolved
};
},
};
};

export interface FlutterProviderOptions {
readonly environment?: Readonly<Record<string, string | undefined>>;
/** Deterministic root removal for tests; production removes recursively. */
Expand Down Expand Up @@ -421,6 +481,9 @@ export class FlutterBuildProvider {
},
),
);
} catch (cause) {
if (cause instanceof AnalysisError) return err(cause);
return err(new AnalysisProtocolError(request.operation, { cause }));
} finally {
await reader.close().catch(() => undefined);
Comment thread
3QL marked this conversation as resolved.
Resolved
await this.discardRoot(snapshot.root);
Expand Down Expand Up @@ -457,7 +520,12 @@ export class FlutterBuildProvider {
);
try {
const candidates: { entry: ArtifactEntry; abi: string }[] = [];
for await (const entry of reader.entries(signal)) {
for await (const entry of await collectEntriesSafely(
reader,
"inspect_dart_aot",
snapshot.path,
signal,
)) {
if (entry.kind !== "file") continue;
const match = /^lib\/([^/]+)\/libapp\.so$/u.exec(entry.path);
if (match === null) continue;
Expand Down Expand Up @@ -517,7 +585,13 @@ export class FlutterBuildProvider {
const imageHash = createHash("sha256");
await writeFile(imagePath, Buffer.alloc(0), { flag: "w" });
{
const stream = await reader.open(selected.entry, signal);
const stream = await openEntrySafely(
reader,
selected.entry,
"inspect_dart_aot",
snapshot.path,
signal,
);
let total = 0;
for await (const chunk of stream) {
if (signal?.aborted === true)
Expand Down Expand Up @@ -607,7 +681,10 @@ export class FlutterBuildProvider {
const pool = projectStringPool(isolateData);
const partial =
sections.length < symbolNames.length ||
sections.some((section) => !section.magic_valid) ||
sections.some(
(section) => section.name.endsWith("Data") && !section.magic_valid,
) ||
pool.collectionCapped ||
pool.packageUriCount > MAX_POOL_URIS ||
pool.dartUriCount > MAX_POOL_URIS ||
pool.classLikeTokenCount > MAX_POOL_TOKENS;
Expand Down Expand Up @@ -662,6 +739,9 @@ export class FlutterBuildProvider {
},
),
);
} catch (cause) {
if (cause instanceof AnalysisError) return err(cause);
return err(new AnalysisProtocolError("inspect_dart_aot", { cause }));
} finally {
await reader.close().catch(() => undefined);
await this.discardRoot(snapshot.root);
Expand All @@ -670,6 +750,13 @@ export class FlutterBuildProvider {
}

/** Categorize printable runs from one snapshot data section. */
/**
* Categorize printable runs from one snapshot data section. Collection stops
* admitting new distinct entries once each category reaches its projection
* bound times a slack factor, so allocation and sorting stay proportional to
* the response rather than to an adversarial payload; counts still reflect
* how far scanning proceeded before the collection cap tripped.
*/
const projectStringPool = (
section: Buffer | null,
): {
Expand All @@ -680,24 +767,36 @@ const projectStringPool = (
classLikeTokens: string[];
classLikeTokenCount: number;
printableRunCount: number;
collectionCapped: boolean;
} => {
const packages = new Set<string>();
const darts = new Set<string>();
const tokens = new Set<string>();
let runCount = 0;
let collectionCapped = false;
const COLLECTION_SLACK = 2;
const packageBudget = MAX_POOL_URIS * COLLECTION_SLACK;
const dartBudget = MAX_POOL_URIS * COLLECTION_SLACK;
const tokenBudget = MAX_POOL_TOKENS * COLLECTION_SLACK;
if (section !== null) {
let run = "";
const consider = (text: string): void => {
if (text.length < 6) return;
Comment thread
morluto marked this conversation as resolved.
Resolved
runCount += 1;
if (text.startsWith("package:")) packages.add(text);
else if (text.startsWith("dart:")) darts.add(text);
else if (
if (text.startsWith("package:")) {
if (packages.size >= packageBudget) collectionCapped = true;
else packages.add(text);
Comment thread
3QL marked this conversation as resolved.
Resolved
} else if (text.startsWith("dart:")) {
if (darts.size >= dartBudget) collectionCapped = true;
else darts.add(text);
} else if (
text.length <= 128 &&
text.length >= 5 &&
IDENTIFIER_PATTERN.test(text)
)
tokens.add(text);
) {
if (tokens.size >= tokenBudget) collectionCapped = true;
else tokens.add(text);
}
};
for (const byte of section) {
if (byte >= 0x20 && byte < 0x7f) run += String.fromCharCode(byte);
Expand All @@ -716,5 +815,6 @@ const projectStringPool = (
classLikeTokens: [...tokens].sort(),
classLikeTokenCount: tokens.size,
printableRunCount: runCount,
collectionCapped,
};
};
40 changes: 31 additions & 9 deletions src/flutter/FlutterPayloadScan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,13 @@ export interface SnapshotHashScan {
* Feed chunks in order; a trailing carry keeps a magic-to-hash span that a
* chunk boundary would otherwise split.
*/
/** Hard cap on distinct hashes retained before partial coverage reports. */
export const MAX_SNAPSHOT_HASH_CANDIDATES = 64;

export class SnapshotHashScanner {
#sources = 0;
private readonly candidates: string[] = [];
private readonly candidateSet = new Set<string>();
#buffer = new Uint8Array(0);
/** Absolute stream offset from which unprocessed bytes begin. */
#base = 0;
Expand All @@ -77,8 +81,14 @@ export class SnapshotHashScanner {
magic + SNAPSHOT_HASH_OFFSET + SNAPSHOT_HASH_LENGTH,
),
).toString("latin1");
if (HASH_PATTERN.test(candidate) && !this.candidates.includes(candidate))
if (
HASH_PATTERN.test(candidate) &&
this.candidates.length < MAX_SNAPSHOT_HASH_CANDIDATES &&
Comment thread
morluto marked this conversation as resolved.
Resolved
!this.candidateSet.has(candidate)
) {
this.candidateSet.add(candidate);
this.candidates.push(candidate);
}
this.#sources += 1;
Comment thread
3QL marked this conversation as resolved.
Resolved
offset = magic + DART_SNAPSHOT_MAGIC.length;
this.#absoluteScanFrom =
Expand Down Expand Up @@ -176,32 +186,44 @@ const DART_VERSION_PATTERN = /Dart VM version:[^\x00\n]{0,200}/u;
const TOOLCHAIN_PATTERN =
/Android \([^)\x00\n]{0,80}\) clang version [^\x00\n]{0,500}|based on LLVM \d[^\x00\n]{0,80}/u;
const MAX_TOOLCHAIN_LINES = 4;
/** Carry spans chunk boundaries for either accepted pattern. */
const CARRY_BYTES = 600;
Comment thread
3QL marked this conversation as resolved.
Resolved

/**
* Incremental ASCII string collector that keeps only labeled version and
* toolchain facts. Printable runs feed the patterns; a 256-byte carry
* survives chunk boundaries.
* toolchain facts. A match is committed only when a printable run is
* terminated by a delimiter, so a value split across chunk boundaries is
* never committed truncated; the carry holds the longest accepted match
* so boundaries in either pattern survive.
*/
export class LabeledStringScanner {
#dartVersion: string | null = null;
private readonly toolchainLines: string[] = [];
private carry = "";
private printable: string = "";
#ended = false;

push(chunk: Uint8Array): void {
let run = "";
for (const byte of chunk) {
if (byte >= 0x20 && byte < 0x7f) run += String.fromCharCode(byte);
else {
this.#consider(run);
this.#consider(this.carry + run);
run = "";
}
}
this.#consider(run, true);
// Retain the unfinished tail; it may still grow past a chunk boundary.
this.carry = (this.carry + run).slice(-CARRY_BYTES);
}

/** Commit any retained tail, e.g. when the stream ends mid-string. */
end(): void {
if (this.#ended) return;
this.#ended = true;
this.#consider(this.carry);
this.carry = "";
}

#consider(run: string, partial = false): void {
const text = this.carry + run;
#consider(text: string): void {
if (this.#dartVersion === null) {
const match = DART_VERSION_PATTERN.exec(text);
if (match !== null) this.#dartVersion = match[0].trim();
Expand All @@ -214,10 +236,10 @@ export class LabeledStringScanner {
this.toolchainLines.push(line);
}
}
this.carry = partial ? text.slice(-256) : "";
}

result(): LabeledStringScan {
if (!this.#ended) this.end();
return {
dartVersion: this.#dartVersion,
toolchainLines: [...this.toolchainLines],
Expand Down
Loading