nts 2.0.0
nts: ^2.0.0 copied to clipboard
Authenticated network time for Flutter apps, secured by Network Time Security (NTS).
Changelog #
2.0.0 #
Adds first-class phase attribution to the public NTS surface so callers
diagnosing a slow or refused query can distinguish DNS saturation, a
slow getaddrinfo, a stalled TCP connect, a slow TLS handshake, a
trickled NTS-KE record exchange, and a slow UDP NTP round-trip without
inspecting free-form diagnostic strings or bolting a Dart-side
Stopwatch around ntsQuery. The Rust crate nts_rust is bumped to
0.4.0 to reflect a breaking change in the public NTS API surface;
the Dart package is bumped to 2.0.0 for the matching breaking change
in the FFI signatures and the NtsError::Timeout payload (closes
nts-r2l).
Breaking changes #
NtsError::Timeoutnow carries aTimeoutPhasepayload identifying which phase of the call hit the budget. Existing pattern matches onNtsError::Timeout(Rust) orNtsError_Timeout()(Dart) need to bind the new field; pre-2.0 consumers that ignored the variant data with()will not compile against this release.nts_warm_cookiesnow returnsNtsWarmCookiesOutcome { fresh_cookies, phase_timings }instead of a bareu32(Rust) /int(Dart). The cookie count is still available viaoutcome.fresh_cookies; the newphase_timingsfield exposes the same per-phase wall-clock breakdown asNtsTimeSample.phase_timings.NtsTimeSamplegains a requiredphase_timings: PhaseTimingsfield. Constructors that named every existing field will need to supply the new field; the Dart-side equivalent applies to any test fixture or mock that builds anNtsTimeSampleby hand.
Phase attribution and timings #
- New
TimeoutPhaseenum tagsNtsError::Timeout. VariantsDnsSaturation(resolver pool full, raisedns_concurrency_cap),DnsTimeout(resolver slow, lengthentimeout_msor replace the recursive resolver),Connect,Tls,KeRecordIo, andNtpcover every blocking phase ofnts_query/nts_warm_cookies. - New
PhaseTimingsstruct exposes microsecond-resolution wall-clock costs for the four pre-NTP phases (dns_micros,connect_micros,tls_handshake_micros,ke_record_io_micros); the existingNtsTimeSample::round_trip_microsis the UDP-phase equivalent and is intentionally not duplicated.dns_microsis summed across the KE-host and NTPv4-host lookups; phases that did not run in this call are reported as0rather than absent. See the new "Phase attribution and timings" section inARCHITECTURE.mdfor the full diagnostic shape. nts_queryinstruments the KE pipeline (DNS, connect, TLS, KE record I/O) insideperform_handshakeand threads the timings out through a refactoredKeOutcome.phase_timings; the UDP-path DNS cost is captured inbind_connected_udp_usingand folded into the samedns_microsfield on the returned sample.nts_warm_cookiesexposes the same KE-phase breakdown viaNtsWarmCookiesOutcome.phase_timings. The UDP NTP exchange does not run on this path, so theNtpphase is implicitly zero.nts_querynow anchors a single call-wide wall-clock at the top of the call and subtracts the time consumed by the KE phases before arming the UDP-setup deadline. Restores the documented "single global wall-clock budget" contract ontimeout_ms; previously a cold query whose KE phases consumed most oftimeout_mswould re-anchor a freshtimeout_ms-long window for the UDP leg, letting the total wall-clock reach roughly 2x the caller's budget before surfacing asTimeout(Ntp). A budget that was already exhausted by the KE phases now short-circuits withTimeout(Ntp)immediately rather than entering the UDP-setup leg at all.
Tooling: orphan detection in the FRB drift check (no runtime impact) #
tool/check_bindings.dartnow runs_checkForOrphanedApiModulesafter codegen + lint patches + format and before the trailinggit diffdrift check. The check walkslib/src/ffi/api/*.dart(skipping*.freezed.dartand*.g.dartcompanions, which are emitted frompartdirectives in the primary file rather than referenced from the dispatcher) and flags any primary module file the regeneratedlib/src/ffi/frb_generated.dartdoes not import. Closes the FRB stale-module footgun: when the lastpubitem is removed from arust/src/api/<module>.rs, FRB drops the wire impls fromfrb_generated.{rs,dart}but leaves the previously emittedlib/src/ffi/api/<module>.darton disk. The stale module then references symbols that no longer exist in the dispatcher and surfaces as an opaque "symbol not found inRustLibApi" build break underflutter analyze/flutter testrather than at codegen time. The dispatcher'simport 'api/<basename>.dart';line set is the authoritative "still contributing" stand-in: FRB writes one such import for every Rust source underrust/src/api/that contributed at least one FRB-visible item on the most recent codegen run, so running the check after codegen guarantees the import set is current regardless of what is committed.- Detection is read-only on purpose. Auto-deleting risks papering
over a removal that wasn't intended; the diagnostic instructs
the developer to remove the orphan (and any
*.freezed.dart/*.g.dartcompanions) explicitly. The orphan list is sorted before printing so the diagnostic renders deterministically across filesystems with differentDirectory.listSynciteration orders (APFS, ext4, etc. differ). Local invocation produceserror:prefixed lines; CI invocation underGITHUB_ACTIONS=trueemits the same body with::error::so therust-bridge-syncjob surfaces it as a workflow annotation. Exit code is1on the orphan path, failing the job explicitly on the orphan diagnostic rather than implicitly via trailing drift. Header comment intool/check_bindings.dartis rewritten to document the orphan check and its rationale (closesnts-lmf).
Coverage artefact ignore at any depth #
.gitignoregains an unanchoredcoverage/entry.flutter test --coveragewritescoverage/lcov.infoat the package root, andcargo tarpaulin --output-dir coverage(configured inrust/tarpaulin.toml) writesrust/coverage/lcov.info. Both are local artefacts: each CI run regenerates them and uploads to Codecov directly from.github/workflows/ci.yml, so the in-tree copies are never consumed by anything downstream. The unanchored pattern catches both paths above;example/coverage/was already covered byexample/.gitignore:34, so no duplication.
1.4.0 #
Converts nts from a pure Dart package using the Native Assets pipeline
into a full Flutter plugin so that downstream consumers can use the
package on Android without having to replicate the Rust ↔ Kotlin JNI
bootstrap, the rustls-platform-verifier-android Maven repository
discovery, or the R8 keep-rule contract by hand. No Dart API surface
change (public exports unchanged; only dartdoc was updated to document
the two-layer initialization model) and no FRB pin movement; the Rust
crate nts_rust is bumped to 0.3.0 to reflect a breaking JNI ABI
change. Dart package version bumped to 1.4.0 (minor).
Auto-initialised Android rustls-platform-verifier bootstrap #
-
New plugin module under the package root at
android/. It ships:com.nllewellyn.nts.NtsPlugin— aFlutterPluginthat callsPlatformInit.init(applicationContext)fromonAttachedToEngine.GeneratedPluginRegistrant.registerWithruns that hook before Dartmain()in any host usingFlutterActivity,FlutterFragmentActivity, or the Flutter add-to-appFlutterEnginelifecycle, so therustls-platform-verifierpanic (Expect rustls-platform-verifier to be initialized…) is no longer reachable through the standard integration path.com.nllewellyn.nts.PlatformInit— the matched JNI Kotlin counterpart for the Rust symbol exported fromrust/src/android_init.rs. Also exposes a publicstatic init(Context)for hosts that bypassGeneratedPluginRegistrant(rare; mainly bespoke add-to-app embeddings or tests that drive the dylib directly).consumer-rules.pro— ProGuard / R8 keep rules covering both therustls-platform-verifiercompanion AAR (org.rustls.platformverifier.**) and our own JNI shim (com.nllewellyn.nts.PlatformInit). Auto-merged into the host app's shrinker config; consumers do not have to copy keep rules.build.gradle.kts— discovers the on-disk Maven repository bundled inside therustls-platform-verifier-androidcargo crate viacargo metadata, so the AAR resolves regardless of whetherntsis installed from a path dependency, the pub cache, or a monorepo, on hosts that use the default Flutter/Gradle repository setup. Replaces the brittle../../rust/Cargo.tomltraversal that previously lived inexample/android/app/build.gradle.ktsand only worked from the example tree. Hosts that enabledependencyResolutionManagement.repositoriesMode = FAIL_ON_PROJECT_REPOSinsettings.gradle.ktsare the documented exception: that mode rejects the project-level Maven injection the plugin performs throughrootProject.allprojects { ... }, so those hosts must declare the on-disk repository themselves underdependencyResolutionManagement.repositoriesinsettings.gradle.kts. The cargo-metadata path is stable and can be reused verbatim; the rationale comment inandroid/build.gradle.ktscarries the full constraint.
Native code (
libnts_rust.so) continues to be delivered by the Native Assets pipeline (hook/build.dart); the plugin module ships nojniLibs/and does no Cargo wiring of its own. Platforms other than Android are untouched: iOS / macOS / Linux / Windows remain pure Native-Assets packages with no accompanying plugin module.
Stable JNI symbol under reverse-DNS namespace (BREAKING ABI) #
- The JNI entry point exported from
rust/src/android_init.rsis renamed fromJava_com_nts_example_RustlsBootstrap_nativeInittoJava_com_nllewellyn_nts_PlatformInit_nativeInit. The previous symbol was mangled for the example app's package name, which is not a contract any downstream consumer can reasonably satisfy (renaming the symbol locally would diverge from upstream releases on every pull). The new FQDN is under the maintainer's reverse-DNS namespace and is documented as the stable public ABI.- Impact: any host application that previously hand-rolled a
matching
com.nts.example.RustlsBootstrapKotlin class plus keep rules (i.e. only the example app shipped in this repository, given the1.3.xcontract was effectively unconsumable) must drop that class. The plugin's auto-init replaces the manual wiring;flutter pub upgradeplusflutter cleanis sufficient.
- Impact: any host application that previously hand-rolled a
matching
Migrating from 1.3.x #
- Out-of-tree consumers that hand-rolled the
1.3.xAndroid contract must drop the manual scaffolding when bumping to1.4.0. The JNI symbol moved to the maintainer's reverse-DNS namespace (Java_com_nllewellyn_nts_PlatformInit_nativeInit), so the legacyexternal fun nativeInitdeclaration on a host-app shim no longer resolves against the dylib's exports.System.loadLibrary("nts_rust")still succeeds (the library itself loads), but the first invocation of the unbound declaration throwsUnsatisfiedLinkError: No implementation found for void com.<host>.RustlsBootstrap.nativeInit(android.content.Context). In the documented1.3.xintegration shape that fires fromMainActivity.onCreatebeforesuper.onCreate(...), so the host app crashes at process start, well before any TLS handshake is attempted. The plugin contributes equivalent functionality; one round offlutter pub upgrade+flutter cleanis sufficient once the items below are removed. - Host-app
RustlsBootstrap.kt(or any equivalent class whose FQDN was used to mangle theJava_*_nativeInitsymbol exported fromrust/src/android_init.rs). Delete the file. The plugin shipscom.nllewellyn.nts.PlatformInitas the new stable counterpart; nothing in the host app needs to know its name. MainActivity.onCreateshim that calledRustlsBootstrap.init(this)ahead ofsuper.onCreate(...). RevertMainActivityto a no-bodyFlutterActivity. The plugin'sonAttachedToEngineruns fromGeneratedPluginRegistrantbefore Dartmain()executes, so any code path that reached the bootstrap before reaches it now without the manual call.app/build.gradle.ktsentries that wired up therustls-platform-verifier-androidMaven repository: thefindRustlsPlatformVerifierMaven()helper (or whichever shape it took locally), therepositories { maven { url = uri(...) } metadataSources { artifact() } }block, and theimplementation("rustls:rustls-platform-verifier:0.1.1@aar")dependency. All three are contributed by the plugin's ownandroid/build.gradle.kts. Leaving them in place resolves the AAR twice; harmless at runtime but it wastes Gradle resolution time and pins the consumer to a version the plugin will move out from under them.proguard-rules.prokeep rules coveringorg.rustls.platformverifier.**and the host-app's ownRustlsBootstrapJNI class. Both are now in the plugin'sconsumer-rules.proand auto-merged into the host's R8 config. TheRustlsBootstrap-flavoured rule is doubly stale because the symbol name has changed; an unmodified rule keeps a class that no longer exists and produces no shrinker warning either way.settings.gradle.ktsdoes not change. Thedev.flutter.flutter-plugin-loaderblock is the standard Flutter wiring that picks up the new plugin module automatically; no manualinclude,pluginManagement, or Maven entry is required.- Custom embeddings. Hosts that legitimately bypass
GeneratedPluginRegistrant— bespoke add-to-app integrations, integration tests driving the dylib directly, isolates spawned ahead of plugin registration — should callcom.nllewellyn.nts.PlatformInit.init(context)from Kotlin in place of the deletedRustlsBootstrap.init(...). The signature and idempotency contract are identical; only the FQDN moves. - Hosts that did not hand-roll the
1.3.xAndroid contract have nothing to do beyondflutter pub upgrade+flutter clean. The previous JNI symbol was mangled for the example app's package name and could not be satisfied without forking the Rust crate, so the realistic pre-1.4.0integration path for any out-of-tree consumer was a vendored copy of this repository with the symbol renamed locally — that fork should be retired in favour of the published1.4.0plugin and the stablecom.nllewellyn.nts.PlatformInitsymbol.
Non-Android upgrade path #
iOS, macOS, Linux, and Windows consumers are unaffected by the
migration steps above. The android/ plugin module and the
flutter: plugin: platforms: android: key in pubspec.yaml are
scoped exclusively to Android — the Flutter tool generates no
plugin registration on other targets, no ios/ / macos/ /
linux/ / windows/ plugin module exists to compile or link,
and the Native Assets pipeline that delivers
libnts_rust.{so,dylib,dll} is unchanged. The public Dart API
exported from lib/nts.dart is unchanged, and
await RustLib.init() remains the only initialization step.
The upgrade is a single-line pubspec.yaml bump.
The on-platform TLS validators are also unchanged: every
non-Android target continues to use rustls-platform-verifier
0.5 directly, which talks to the Security framework on
iOS/macOS, the system trust store on Linux, and the Win32
Crypt* APIs on Windows without any host-side initialization
step. None of these paths require JVM-style bootstrap, which is
why the "Native platform bootstrap" layer documented in the
README is Android-only.
Example app simplified to a vanilla FlutterActivity #
example/android/app/src/main/kotlin/com/nts/example/RustlsBootstrap.ktremoved. Its responsibilities are now split between the plugin'sNtsPlugin(registration-time auto-init) andPlatformInit(manual fallback).example/android/app/src/main/kotlin/com/nts/example/MainActivity.ktreverted to a no-bodyFlutterActivity. The Android trust-store bootstrap happens beforesuper.onCreate()runs.example/android/app/build.gradle.ktsno longer carries thefindRustlsPlatformVerifierMaven()helper, therustls:rustls-platform-verifier:0.1.1@aarimplementationdep, or the local Maven repository declaration. All three now live in the plugin's ownandroid/build.gradle.kts.example/android/app/proguard-rules.proreduced to a stub comment. The keep rules previously declared here are merged in from the plugin'sconsumer-rules.pro.
Internal documentation refresh #
rust/src/lib.rs,rust/src/android_init.rs, andrust/src/nts/hybrid_verifier.rsupdated to reference the new Kotlin FQDN and the plugin'sconsumer-rules.prorather than the decommissionedRustlsBootstrap.ktin the example app. Thehybrid_verifierwarn-level fallback message that fires when R8 has strippedorg.rustls.platformverifier.*now points operators at the plugin's keep-rule file.
1.3.2 #
Repo-policy and CI-hygiene cleanup, plus a single Rust-side
runtime fix that closes a multi-hour recovery stall observed in
downstream consumers when an NTS server rotates its master key
out from under our cookie pool. No public Dart API change
(lib/nts.dart is byte-identical) and no FRB pin movement; the
Rust crate nts_rust is bumped to 0.2.3 to reflect the
behavioural change in nts_query. Dart package version bumped
to 1.3.2 (patch).
Fail-fast eviction of stale NTS sessions on rekey signals #
nts_query(rust/src/api/nts.rs) now evicts the cachedSessionfor the spec on either of the two on-wire signals that indicate the server has rotated keys out from under our cookie pool. The nextcheckoutfor that host finds no entry and performs a fresh NTS-KE handshake instead of draining the remaining cookies through identical failures plus the caller's per-source exponential backoff. Closesnts-0jl.- AEAD authentication failure — local C2S seal in
build_client_requestor remote S2C verify inparse_server_responsereturnsNtpError::Aead. The cached keys are out of step with the server's current master key. - RFC 8915 §5.7 NTSN Kiss-of-Death with matching UID — a
standards-compliant server that cannot validate the cookie
SHOULD respond with stratum 0 +
reference_id=NTSN, and that response MUST NOT carry an Authenticator (the server has no usable session keys to AEAD-sign with). The AEAD-only eviction path missed this shape entirely:parse_server_responserejected it asMissingAuthenticatorso the cached session survived and the same dead-pool draining symptom recurred. The newNtpError::StaleCookiearm classifies the matching-UID NTSN distinctly and routes it through the same generation-guarded eviction.
- AEAD authentication failure — local C2S seal in
- The eviction is gated on a generation snapshot captured at
checkouttime, symmetric to the guard already present indeposit_cookies. If a concurrentnts_warm_cookies(or anothercheckoutthat triggered its own re-handshake) installed a fresh session under the same key while this query was on the wire, the in-flight failure belongs to the old keys and the new session survives untouched. Without the guard a single transient signal would force every concurrent caller for the same host through a redundant re-handshake. - Off-path-attacker scope of the NTSN path: the matching-UID
check is the only authenticity signal available (no AEAD), so
an attacker who can observe one wire packet and forge a
UID-matching NTSN can at worst force one extra KE handshake
before the next legitimate response heals the session. A
non-matching (or absent) UID falls through to
MissingAuthenticatorand leaves the cached session intact; unauthenticated non-NTSN kiss codes (RATE,DENY, …) do the same so a server that AEAD-signs them (the standards path) still surfaces with its kiss code, while a stripped forgery cannot trigger an eviction. - AEAD-error mapping verified end-to-end:
From<AeadError>routesOpenFailed(tag mismatch — the dominant master-key-rotation signal),SealFailed,InvalidKeyLength, andInvalidNonceLengthtoNtsError::Authentication(eviction);UnsupportedAlgorithmis only reachable from the KE path and routes toKeProtocol(no eviction).From<NtpError>::Aead(_)routes the same way; wire-format, Kiss-of-Death, andUnsynchronizedarms route toNtpProtocol(no eviction — those are transient or server-attested signals, not key-state failures); the newStaleCookiearm routes toNtpProtocolfor the Dart-facing taxonomy, with eviction applied pre-conversion inside theevict_on_rekey_signalclosure so the publicNtsErrorenum stays byte-identical. - Healthy-path cost is unchanged: the trigger is a
map_errclosure that only acquires thesessions()mutex inside theAead/StaleCookiearms, so success returns are byte-identical to the pre-fix behaviour. - Coverage: seven new tests pin the behaviour. In
rust/src/api/nts.rs::tests: (i) matching-generation eviction drops the entry, jar and keys with it; (ii) stale-generation eviction is a no-op when a concurrent re-handshake has advanced the cached session; (iii) eviction is a quiet no-op when the entry is already absent; (iv) end-to-end via a loopback faux server, an AEAD tag mismatch evicts the session; (v) end-to-end, a non-AEAD protocol failure preserves it; (vi) end-to-end, a matching-UID NTSN KoD evicts; (vii) end-to-end, a wrong-UID NTSN preserves. Inrust/src/nts/ntp.rs::tests: four new parser-level tests cover matching-UID NTSN →StaleCookie, wrong-UID NTSN →MissingAuthenticator, UID-less NTSN →MissingAuthenticator, and unauthenticated non-NTSN kiss codes →MissingAuthenticator. - The FRB-generated
lib/src/ffi/api/nts.dartregainsevict_sessionin the alphabetised "ignored because notpub" comment line; no bindings code changes (the helper is intentionally crate-private).
Branch-protection enforcement (repo policy, no runtime impact) #
- Toggle
enforce_admins: trueon themainbranch protection rule so the six required status checks (the four pre-existing CI gates plus the two newHooks *checks added in this PR), linear-history requirement, and PR-only merge policy are binding for the maintainer account. The previous configuration (enforce_admins: false) made the rule advisory for repo admins, which left a directgit push origin mainunblocked for the most likely violator. - Add repo-tracked git hooks under
tool/hooks/(POSIX shell, no runtime dependency beyondgit) that refuse direct work onmain/master:pre-commitblocks plain commits,pre-merge-commitblocks merge commits (which bypasspre-commit), andpre-pushblocks any push whose destination ref isrefs/heads/main/refs/heads/masterregardless of the source branch. Activated per clone withgit config core.hooksPath tool/hooks; without that activation layer 1 contributes nothing. Two commit-time bypasses remain, both caught at push time bypre-pushand the GitHub-side rule: (a) rebases that rewrite localmain(each replayed commit runs in detached HEAD, sopre-commitfalls through), and (b) fast-forward merges (git merge feature/foowhilemainhas no diverging commits advances the ref without creating a commit, sopre-merge-commitdoes not fire). - Document the enforcement model in
AGENTS.md's new "Branch Protection" section andDEVELOPMENT.md's "Local hook setup" subsection. The model has two enforcement layers (local hooks for fast-fail, GitHub branch protection at the remote) plus CI as the upstream of the status checks the protection rule consumes. The branch protection rule itself does the merge gating: the rule refuses direct pushes from non-admin contributors, andenforce_admins: trueextends that refusal to admin/owner accounts (closing the maintainer-bypass path);required_status_checksrefuses the PR merge until the listed contexts pass. CI is not a separate enforcement layer, just the source of the signals the rule reads. Public Dart/Rust API unchanged. - CI gains two narrowly-scoped sibling jobs in
.github/workflows/ci.ymlplus atool/hooks/**path classification on the existingdorny/paths-filterstep, so a PR that touches only the enforcement scripts still gets validated rather than skipping every heavy job and merging unverified. Both jobs are added torequired_status_checksonmain, raising the required-context count from four to six:Hooks shell-syntax checkrunssh -nplus presence and exec-bit verification on each tracked hook (the explicit list fails closed if a hook is deleted, renamed, or chmod-stripped, where a glob would silently pass).Hooks behaviour checkrunstool/hooks/test_hooks.sh, a new POSIX-shell test that provisions a throwaway repo viamktemp -d, pointscore.hooksPathattool/hooks/, stages real commits and real merges, and invokespre-pushdirectly with synthetic refs/SHAs on stdin (git's documented pre-push contract: read updates from stdin, exit non-zero to abort). Asserts on exit codes plus stderr content. Catches the regression shapesh -ncannot — a script that parses but no longer enforces policy at runtime — and carries an explicit assertion sentinel for the unquoted-heredoc class of bug whereset -uaborts the hook before the recovery recipe can print. No other CI behaviour changes: thebuild,rust, andrust-bridge-syncfilters and gates are byte-identical.
Coverage exclusion alignment #
- Reconcile the four loci that determine the coverage denominator so
local artifacts, CI flags, and the Codecov dashboard agree.
.codecov.ymlnow ignoreslib/src/ffi/api/nts.dart(FRB-generated single-expression forwarders of the formntsQuery(...) => RustLib.instance.api.crateApiNtsNtsQuery(...)— reachable from the smoke tests but low-signal for authored-code coverage; the FFI dispatch they delegate into lives infrb_generated*.dartand is whatRustLib.initMock()substitutes) andrust/src/api/simple.rs(holds only the#[frb(init)]lifecycle hookinit_app, fired on dylib load and unreachable fromcargo test --lib).rust/tarpaulin.toml(new) carries the same Rust exclusion set so a localcargo tarpaulinreproduces CI numbers without per-invocation--exclude-filesflags..github/workflows/ci.ymladds the matching--exclude-files 'src/api/simple.rs'and the comment block above the step now enumerates all four filtered Rust files (previously named only two).DEVELOPMENT.md's "Coverage exclusion policy" subsection is refreshed to match.
greet smoke-test stub removal #
- Delete the
greetfunction fromrust/src/api/simple.rs(left over from the FRB scaffold; never re-exported throughlib/nts.dart, so internal-only by the package's own public-API stability statement) and refresh the file header to document its remaining role as the lifecycle-hook host.lib/src/ffi/api/simple.dartis removed; FRB does not auto-clean stale module files when a Rustapi/module loses its lastpubitem (followup tracked asnts-lmfto extendtool/check_bindings.dartto flag this footgun). ThecrateApiSimpleGreetoverrides inexample/lib/src/mock_api.dart,test/api_smoke_test.dart, andtest/ffi_smoke_test.dartare removed in the same commit; the FRB-generated layer (lib/src/ffi/frb_generated.{dart,io.dart,web.dart},rust/src/frb_generated.rs) is regenerated viaflutter_rust_bridge_codegen 2.12.0and committed clean against the drift gate.
CI: Flutter stable channel migration #
- Switch the Flutter SDK reference from the pinned
3.41.7release to thestablechannel across the five loci that named it:.fvmrc("flutter": "stable"),.github/workflows/ci.yml(matrix entry renamed3.41.7→stable),pubspec.yaml,DEVELOPMENT.md, and.github/pull_request_template.md. The pinned-semver references are rewritten to describe the channel rather than a specific version. The compatibility-floor matrix leg (3.38.10, the lowest Flutter satisfyingflutter: ^3.38.0inpubspec.yaml) is unchanged so the floor remains pinned. subosito/flutter-actionreceivesflutter-version: anyfor thestableleg (the action's documented channel-latest sentinel, since the action does not accept channel names asflutter-versionvalues); the format / coverage / Codecov upload gates are retargeted frommatrix.flutter == '3.41.7'tomatrix.flutter == 'stable'.rust-bridge-syncdrops itsflutter-versionpin and points the FVM symlink at$HOME/fvm/versions/stableto match.fvmrc.- Branch-protection continuity is preserved: the matrix-leg job
names (
Format / analyze / Dart tests (Flutter ${{ matrix.flutter }})) are not required status checks. TheDart tests gateaggregator job (needs: [changes, build],if: always()) is the entry onmain'srequired_status_checkslist and rolls up the matrix outcome under a name that does not move with the channel rename, so the rule continues to gate merges without any branch-protection edit. The five other required contexts (Detect changed paths,Verify FRB bindings are in sync,Rust build + tests + coverage,Hooks shell-syntax check,Hooks behaviour check) are also untouched by this rename. - The historical
3.41.7mention inside the## 1.0.0release entry below is intentionally left in place — it is a published-release entry and pub.dev archives the changelog at publish time.
1.3.1 #
Documentation-only patch on the 1.3.0 observability surface. No code,
FFI, or runtime behaviour changes; the Rust crate nts_rust is
unchanged at 0.2.2.
NtsDnsPoolStats — acknowledge inFlight > highWaterMark transient #
- Tighten the dartdoc on
ntsDnsPoolStats(lib/src/api/nts.dart) and the mirrored Rust docstring onNtsDnsPoolStatsplus itshigh_water_markfield (rust/src/api/nts.rs). The 1.3.0 wording ("Monotonically non-decreasing for the lifetime of the process", "racy by construction… never logically impossible") invited the strict reading thathighWaterMark >= inFlightholds at every observation point. It does not:try_acquire_slotperforms thefetch_addonin_flightand thefetch_maxonhigh_water_markas two independent atomic operations, so a concurrentpool_snapshot()can observeinFlight = prev + 1andhighWaterMark = prevfor the few-nanosecond window between them. The replacement wording calls this transient out by name and restates the actual guarantee — per-counter monotonicity across consecutive snapshots, not a cross-counter invariant within a single snapshot. - Rationale for documenting rather than patching
snapshot_ofto returnmax(in_flight, high_water_mark): the twoRelaxedloads in the snapshot path are not atomic together, so a derivedmax()suppresses one common observation but does not produce a coherent point-in-time view; closing the race in the increment path requires a CAS loop on a packed(in_flight, hwm)tuple, which is not justified by an observable-only-via-snapshot diagnostic counter; and the three operator-facing failure-mode signatures (healthy / cap-bound / libc wedge — see the rest of the dartdoc) reason about per-counter trajectories across consecutive snapshots, not single-snapshot cross-counter invariants. The transient does not degrade their diagnostic value. - The generated FFI dartdoc in
lib/src/ffi/api/nts.dartis regenerated from the Rust source and tracks the new wording. No other diff in the FRB-generated layer.
Documentation #
- Clarify shared-pool semantics for mixed-cap callers in the
rust/src/nts/dns.rsmodule header and the "Timeout budget and bounded DNS" section ofARCHITECTURE.md. The 1.2.0 wording — "the effective ceiling at any moment is set by whichever caller is currently being admitted" — invited a stateful reading in which the most recently admitted caller's cap somehow governs subsequent admissions. The actual mechanic is purely local: every admitted worker counts toward every caller's threshold, and each admission decision compares the live pool size against that call's own cap. The replacement wording names the asymmetric starvation behaviour explicitly (a small-cap caller can be refused when the pool is filled by a large-cap caller; the reverse cannot happen) so it is discoverable by a future ctrl-F search for "starvation" or "fairness". The published 1.2.0 changelog entry is intentionally not retroactively edited (pub.dev archives the changelog at publish time).
1.3.0 #
Public-API stability layer, bounded DNS resolver pool observability,
and a documentation correction in the Rust core. Strictly additive on
the Dart surface: existing call sites (including
test/ffi_smoke_test.dart and the example app, GUI, and CLI) keep
their current arguments and continue to compile. The Rust crate
nts_rust is unchanged at 0.2.2.
Public API stability layer (lib/src/api/nts.dart, new) #
- Introduce a hand-written wrapper in
lib/src/api/nts.dartthat becomes the package's stable public surface. The wrapper exposesntsQueryandntsWarmCookieswith idiomatic Dart optional named parameters (timeoutMs,dnsConcurrencyCap) and package defaults (kDefaultTimeoutMs = 5000,kDefaultDnsConcurrencyCap = 0), forwarding to the FRB-generated bindings for the actual FFI call.await ntsQuery(spec: spec)(no other arguments) now compiles and produces the same behaviour as 1.2.0'sntsQuery(spec: spec, timeoutMs: 5000, dnsConcurrencyCap: 0). - Rewrite
lib/nts.dartas an explicit re-export of the wrapper plus the bridge bootstrap (RustLib). The blanket re-export oflib/src/ffi/api/nts.dart(and thegreettoolchain helper fromlib/src/ffi/api/simple.dart) is removed; the FFI surface is now an internal implementation detail. Consumers' call sites are unchanged because the wrapper exposes the same names with compatible signatures. - Motivation:
flutter_rust_bridgev2 codegen emits every Rustpub fnargument as arequirednamed parameter on the Dart side, with no FRB attribute today that maps it to an optional Dart parameter with a default. Absorbing that asymmetry in a hand-written layer decouples the public contract from the FFI contract — internal Rust signature evolution (extra knobs, struct field churn, lint-pin regen) no longer propagates as breaking call-site edits for every downstream consumer. The 1.2.0 release was the concrete episode that motivated this: addingdnsConcurrencyCapwas a strict superset of the previous behaviour but broke source compatibility for every caller because the new parameter landed asrequired. - The deprecation policy for future Rust-side removals is symmetric:
parameters dropped from the Rust core survive in the wrapper as
deprecated no-ops for at least one minor release before being
removed at the next major. Documented in
ARCHITECTURE.md's new "Public API stability layer" section.
Bounded DNS resolver pool observability #
- Add
ntsDnsPoolStats()(synchronous; no future / isolate hop) returning a process-wide snapshot of the bounded resolver pool with four counters:inFlight(live workers currently pinned in the system resolver),highWaterMark(peakinFlightsince process start, monotonic),recovered(cumulative completed workers that released their slot), andrefused(cumulative admission attempts rejected because the cap was reached). The function is marked#[frb(sync)]on the Rust side so reading four atomics does not pay the FRB future-marshalling overhead. - The new struct
NtsDnsPoolStatslands as part of the wrapper layer's public surface alongsideNtsServerSpec/NtsTimeSample. - Saturation surfaces unchanged on the hot path as
NtsError.timeout(the error contract stays collapsed); the new counters are the side-channel that lets operators distinguish a healthy oscillating-below-the-cap resolver from a true libc-level wedge. The diagnostic shape is documented in dartdoc onntsDnsPoolStats()and inARCHITECTURE.md's "Timeout budget and bounded DNS" section. - Internal refactor in
rust/src/nts/dns.rs: the previous loneIN_FLIGHT_DNS_LOOKUPS: AtomicUsizeis replaced by aPoolStatsbundle (in-flight + high-water + recovered + refused atomics), sotry_acquire_slot/SlotGuard::dropkeep the four counters in lockstep and the test seam parameterises a per-test bundle the same way the previous lone counter was parameterised. The existingresolve_with_global/resolve_with_timeoutsignatures are unchanged; only the internalresolve_withseam picks up the new type. Memory-ordering rationale for each counter (Relaxedfor cumulative tallies,AcqRelfor in-flight,AcqRelfor the HWMfetch_max) is documented inline. - Three new Rust unit tests in
nts::dns::tests:recovered_increments_on_worker_completion— the cumulative counter bumps exactly once per slot release, after the worker returns from the resolver, alongside the in-flight drain.refused_increments_on_cap_exhaustion— companion tocap_reached_returns_would_block; pins the counter delta on rejected admissions.high_water_mark_tracks_concurrent_admissions— admits N workers behind aBarrier, asserts the mark catches up to N while the slots overlap, then releases and asserts the mark stays at N (monotonic, not pinned to the live in-flight count).
- New wrapper-level smoke test (
test/api_smoke_test.dart) verifiesntsDnsPoolStats()is a synchronous getter returning anNtsDnsPoolStatsand that the FFI struct's fields are forwarded through the wrapper verbatim.
Documentation #
rust/src/nts/cookies.rs: rewrite theDEFAULT_CAPACITYdoc comment. The previous wording claimed the "initial NTS-KE response always delivers exactly 8" cookies, which is not mandated by the protocol — RFC 8915 §4 leaves the count returned by any given server to server policy. The replacement cites RFC 8915 §6 (the client-side cap of 8 unused cookies) and notes that the value matches what several public deployments (Cloudflare) are observed to deliver, with a §4 reference for the server-policy framing. No code change; this aligns the internal docs with theexample/-side framing already shipped in 1.1.2 / 1.2.0.README.md: rewrite the "API summary" table to show the wrapper signatures with=defaults (timeoutMs = kDefaultTimeoutMs,dnsConcurrencyCap = kDefaultDnsConcurrencyCap), add rows for the twokDefault*constants, and add a paragraph linking to the new ARCHITECTURE.md section. ThednsConcurrencyCapprose is updated to mention that omitting the parameter (or passing0) inherits the built-in default.ARCHITECTURE.md: add a new "Public API stability layer" section describing the wrapper, the FRB asymmetry it absorbs, the deprecation policy, and the contract split betweenlib/src/api/(hand-written, stable) andlib/src/ffi/(generated, regenerable). Update the repository layout table to list the new wrapper directory.
Examples #
example/main.dart: simplify the warm-then-burst flow to use the new wrapper defaults (await ntsWarmCookies(spec: spec)andawait ntsQuery(spec: spec)instead of threading explicittimeoutMs: 5000, dnsConcurrencyCap: 0through every call). Comment in Phase 1 documents that the defaults are sourced fromkDefaultTimeoutMs/kDefaultDnsConcurrencyCap.example/example.md's fenced block stays byte-for-byte identical toexample/main.dart(5310 bytes).- The Flutter GUI controller (
example/lib/src/state/nts_controller.dart) and the CLI (example/bin/nts_cli.dart) continue to thread their own configured values explicitly. They are not migrated to the defaults pattern in this release; the wrapper accepts both call styles.
Tests #
test/api_smoke_test.dart(new): wrapper-level smoke test that pins the package defaults (kDefaultTimeoutMs == 5000,kDefaultDnsConcurrencyCap == 0), asserts the wrapper applies them when the optional parameters are omitted, verifies that explicit overrides (including the0sentinel) are forwarded verbatim to the FRB layer, and exercises the synchronousntsDnsPoolStats()plumbing. Seven test cases.test/ffi_smoke_test.dart: rewrite the import block.greetand the FRB-layerntsQuery/ntsWarmCookiesare now imported directly frompackage:nts/src/ffi/...rather than the public barrel, so the test continues to exercise the FFI contract unchanged while the public barrel stops re-exporting them. The five existing test cases are unmodified and still pass.
Generated bindings #
lib/src/ffi/api/nts.dart,lib/src/ffi/frb_generated.dart,lib/src/ffi/frb_generated.io.dart,lib/src/ffi/frb_generated.web.dart, andrust/src/frb_generated.rsregenerated viaflutter_rust_bridge_codegen generate(pinned at 2.12.0) to pick up the newNtsDnsPoolStatsstruct and thents_dns_pool_statsentry point. No drift detected bytool/check_bindings.dartafter the regen + lint-suppression patches.
Verification #
fvm flutter analyze: clean (no issues).fvm flutter test test/api_smoke_test.dart test/ffi_smoke_test.dart: 12 / 12 pass.fvm flutter test(example/): 31 / 31 pass.cargo fmt --check(inrust/): clean.cargo clippy --tests --all-targets -- -D warnings(inrust/): clean.cargo test(inrust/): 112 / 112 pass, 3 ignored (live-network).example/main.dart↔example/example.mdfenced-block byte-for-byte parity: 5310 bytes.
1.2.0 #
Reliability and timeout-budget hardening across the Rust core. The public
Dart surface (ntsQuery, ntsWarmCookies, NtsServerSpec,
NtsTimeSample, NtsError) gains one new optional knob —
dnsConcurrencyCap — for tuning the bounded DNS resolver per call;
existing call sites that omit it continue to compile because the
codegen marks the parameter required (pass 0 to inherit the default).
Consumer-visible behaviour also improves on the timeout-fidelity and
DNS-stall paths. Rust crate nts_rust is bumped from 0.2.1 to
0.2.2; the bindings (lib/src/ffi/) are regenerated to reflect the
new parameter.
Bounded DNS resolution (rust/src/nts/dns.rs, new module) #
- Replace the unbounded
ToSocketAddrslookup that previously fronted both NTS-KE TCP connect and the NTPv4 UDP bind with a thread-pool resolver that offloadsgetaddrinfoto a detached worker and bounds the wait via ampsc::Receiver::recv_timeout. A stalled name server no longer holds the calling thread past the caller'stimeoutMsbudget; the resolver returnsio::ErrorKind::TimedOutonce the remaining budget is exhausted, which theapi::ntsandnts::kecall sites collapse toNtsError::Timeout. - Add a global atomic concurrency cap on in-flight resolver workers to
protect the host environment from a runaway burst of
ntsQuerycalls against a blackholed DNS server. The cap is configurable per call via thednsConcurrencyCapparameter onntsQuery/ntsWarmCookies; passing0selects the built-in default of 4, sized for mobile (worst-case ~512 KB-1 MB of pthread stack per leaked worker on iOS/Android, capping the steady-state leak from a blackholed resolver to ~4 MB instead of unbounded growth). Server-side callers that legitimately need higher fan-out can pass a larger cap per invocation. Cap exhaustion surfaces asio::ErrorKind::WouldBlockfrom the resolver entry point and is mapped toNtsError::Timeoutat both KE and UDP call sites so the Dart-side switch arm is reached without introducing a new variant. - Because the threshold compares against a single process-wide counter, two concurrent callers passing different caps share the same in-flight pool: the effective ceiling at any moment is set by whichever caller is currently being admitted, not a private quota.
- The detached-worker pattern intentionally leaks the OS thread on
timeout rather than aborting it:
getaddrinfois not cancellable on any major libc, so attempting to interrupt the worker would corrupt the resolver state. The slot cap bounds the steady-state cost of this leak under pathological conditions.
NTS-KE handshake (rust/src/nts/ke.rs) #
- Introduce a private
Deadlinenewtype that anchors a singleInstantat the top ofperform_handshakeand exposesremaining()(saturating) plusapply_to(&TcpStream)(refreshes socket read/write timeouts; returnsio::ErrorKind::TimedOutif the budget is exhausted). Replaces the previous pattern where every blocking phase — DNS lookup, TCP connect, TLS handshake, NTS-KE record I/O — was independently armed with the caller's fulltimeoutMs, allowing the total wall-clock cost to overshoot the budget by up to ~3x. connect_with_deadline_using<F>becomes the new core path;connect_with_timeout_usingis retained as a thinOption<Duration> → Option<Deadline>wrapper that preserves the slow-DNS test seam.perform_handshakethreads oneDeadlinethrough DNS resolution, TCP connect, post-connect socket-timeout setup, pre-write/pre-flush refreshes, and the read loop.read_to_end_cappednow takesStream<'_, ClientConnection, TcpStream>plusOption<&Deadline>and refreshes the underlying socket's read/write timeouts on every loop iteration, so a server that drip-feeds the NTS-KE response cannot stretch the read phase past the global deadline.- New regression tests:
deadline_remaining_saturates_at_zero_after_expiry,deadline_apply_to_returns_timed_out_when_expired,deadline_apply_to_sets_socket_timeouts_within_remaining_budget,connect_with_deadline_respects_external_deadline_for_unroutable_ip,connect_with_timeout_surfaces_slow_dns_as_timed_out.
UDP query path (rust/src/api/nts.rs) #
- Mirror the KE-side helper with a private
UdpDeadlinenewtype forUdpSocket. Surface:new(Duration),remaining()(saturating), andremaining_or_timeout() -> Result<Duration, NtsError>which short-circuits toNtsError::Timeoutonce the budget is exhausted rather than feedingDuration::ZEROintoset_read_timeout(which isEINVALon some platforms). bind_connected_udp_usingrewritten to anchor oneUdpDeadline, invokeremaining_or_timeout()?beforeresolve_with_globalso the resolver receives the live remaining budget rather than the originaltimeoutMs, and again beforeset_read_timeout/set_write_timeoutso the UDP socket inherits the remaining budget. The downstreamsocket.send/socket.recvinnts_querytherefore trip no later than the global deadline, even when the KE phase has consumed most of it.UdpDeadlineis intentionally a separate type from the KE-sideDeadlinebecauseapply_towould otherwise need to be socket-type-generic; the duplicated surface is ~20 lines.- New regression tests:
udp_deadline_remaining_or_timeout_after_expiry,bind_connected_udp_socket_timeouts_reflect_remaining_budget,bind_connected_udp_surfaces_slow_dns_as_timeout.
Documentation #
- The dartdoc on
ntsQuery(regenerated intolib/src/ffi/api/nts.dartfrom the Rust docstring oncrate::api::nts::nts_query) now states thattimeout_ms"bounds the DNS lookup that precedes each phase so a stalledgetaddrinfocannot stretch the wall-clock cost past the caller's budget" rather than the previous wording which described the timeout as per-phase.
Housekeeping #
- Apply
cargo fmt(pinned toolchain1.92.0) acrossapi/mod.rs,ios_init.rs,lib.rs,nts/aead.rs,nts/cookies.rs,nts/ntp.rs, andnts/records.rsto reconcile drift accumulated since the 1.1.0 cycle. Behaviour is unchanged. .gitignore: add.DS_Storeso macOS Finder metadata stops appearing ingit status.rust/src/nts/mod.rs: declare the newdnsmodule.
Verification #
cargo test --manifest-path rust/Cargo.toml: 108 passed, 0 failed, 3 ignored (live-network).cargo clippy --manifest-path rust/Cargo.toml --tests --all-targets -- -D warnings: clean.cargo fmt --manifest-path rust/Cargo.toml --check: clean.dart analyze: clean.flutter test test/ffi_smoke_test.dart: 5 / 5 pass.
1.1.2 #
Example-app polish and RFC 8915 §4 compliance in the consumer demo. No
changes to the published Dart surface (ntsQuery, ntsWarmCookies,
NtsServerSpec, NtsTimeSample, NtsError), the Rust crate
(nts_rust stays at 0.2.1), the FFI bindings, or the Native Assets
build hook. The diff is confined to example/, README.md, and
example/GUI_GUIDE.md.
Example app (example/) #
example/lib/src/widgets/log_view.dart: fix an auto-scroll "stickiness" race condition. The scroll-to-bottom side-effect ran in aWidgetsBinding.instance.addPostFrameCallback, so by the time the callback evaluated whether the user had been near the bottom the layout had already been extended by the freshly-appended entry and the threshold check fired againstmaxScrollExtentmeasured after the append. The decision is now taken synchronously in the signal effect against the pre-append layout, while the animated jump still runs post-frame against the resolved target. The 32 px stickiness threshold and 120 ms animation duration are unchanged.example/main.dart,example/example.md,README.md,example/GUI_GUIDE.md: drop the hardcodedconst _burstSize = 8assumption from the warm-then-burst sample. RFC 8915 §4 leaves the cookie-pool size to server policy — the NTS-KE handshake does not let a client request a specific count — so the burst loop now runsfor (var i = 0; i < warmed; i++)against the actual count returned byntsWarmCookies. Prose inREADME.mdandexample/GUI_GUIDE.mdis rewritten to cite the RFC and the live-logrecovered N fresh cookie(s)report rather than the previous "(typically 8)" / "Eight matches" framing.example/main.dartand the fenced block inexample/example.mdremain byte-for-byte identical at 5172 bytes.example/lib/src/widgets/log_view.dart: trim ~20 px of trailing whitespace below the newest log entry. After the stickiness fix made the layout settle visibly, two compounding sources of dead space at the bottom of the log card became apparent:_spansForappended\nto every entry (including the last), leaving a phantom blank line; andSingleChildScrollViewused symmetricEdgeInsets.all(12), stacking 12 px of bottom inset on top of that phantom line. The fix drops the trailing newline from the message span, inserts aTextSpan(text: '\n')separator between entries at the build site (so adjacent entries still render on their own lines, and selection-copy still yields one entry per line), and tightens the bottom padding toEdgeInsets.fromLTRB(12, 12, 12, 8). Total trailing gutter below the newest entry: ~28 px → ~8 px.
Packaging #
screenshots/gui_showcase.png(820,984 bytes) →gui_showcase.webp(183,230 bytes, −78%) viacwebp -lossless -z 9 -m 6. Output is pixel-identical to the source PNG (lossless ARGB, dimensions preserved at 1766×2062, alpha intact).pubspec.yaml'sscreenshots:entry now points at the.webppath. pub.dev's screenshot pipeline is WebP-native via pana'swebpinfovalidator, so this also skips the server-sidecwebpround-trip. Tarball footprint drops from 835 KB to ~213 KB.
Verification #
fvm flutter analyze(root +example/): no issues.fvm dart analyze(root): no issues.fvm flutter test(example/): 31 / 31 pass.example/main.dart↔example/example.mdfenced-block byte-for-byte parity holds at 5172 bytes.webpinfo screenshots/gui_showcase.webp: VP8L, 1766×2062, alpha=1.
1.1.1 #
Maintenance release. The public Dart surface (ntsQuery, ntsWarmCookies,
NtsServerSpec, NtsTimeSample, NtsError) is unchanged.
- Bump the
native_toolchain_rustbuild-hook dependency floor from^1.0.3to^1.0.4to pick up upstream fixes shipped in thenative_toolchain_rust1.0.4 release (pub.dev, 2026-04-27). The package has no runtime impact; it runs only insidehook/build.dartduring the Native Assets compile of the bundled Rust crate. - Refresh
pubspec.lockandrust/Cargo.lockto keep the resolved dependency graph aligned with the new floor. - Patch-bump the internal Rust crate
nts_rustfrom0.2.0to0.2.1so the crate version moves in lockstep with the Dart package release. The bindings (lib/src/ffi/) and Native Assets bridge are unaffected; no behavioural changes ship in the Rust core. - README, example, and dartdoc updates from the previous release stay in place; this release adds no new user-facing documentation.
1.1.0 #
Protocol-compliance and reliability hardening across the Rust core. The
public Dart surface (ntsQuery, ntsWarmCookies, NtsServerSpec,
NtsTimeSample, NtsError) is unchanged; consumer-visible behaviour
improves on the timeout, cookie-cache, and error-classification paths.
Rust crate nts_rust is bumped from 0.1.0 to 0.2.0 to mark the
internal protocol-validation tightening; the bindings (lib/src/ffi/)
and Native Assets bridge are unaffected.
NTS-KE handshake (rust/src/nts/ke.rs) #
- Replace the OS-default TCP connect with a deadline-aware connection
loop that honours the caller's
timeoutMs. Earlier releases passed the budget only to the read/write side of the socket and letTcpStream::connectblock on the platform default (typically 75 s on macOS / 21 s on Linux), which madentsQuery(..., timeoutMs: 5000)hang for the full kernel default when the KE endpoint blackholed SYNs. The new loop iterates the resolved address list, computes the per-attempt deadline from the remaining budget, and surfaces aKeError::Io(ErrorKind::TimedOut)on the first exhausted attempt rather than the last. Mapped throughFrom<KeError> for NtsErrortoNtsError.timeoutso the Dart-side switch arm is reached. - Regression test
connect_with_timeout_respects_budget_for_unroutable_ipexercises the deadline against192.0.2.1(RFC 5737 TEST-NET-1) and asserts the call returns within 1.5× the configured budget.
Cookie management (rust/src/api/nts.rs) #
- Introduce a monotonically-increasing
generation: u64onSessionand propagate it intoQueryContext::session_generationso each in-flight NTPv4 query carries the identity of the handshake that produced its cookies.Session::deposit_cookiesnow gates the cookie-jar update on a matching generation: cookies extracted from a response signed under generation N are silently dropped if the session has been re-handshaked to generation N+1 between dispatch and receipt. This closes a cross-session poisoning window where a late response from a stale session could install cookies bound to retired keys, causing the nextntsQueryto dispatch unauthenticatable cookies and fail the AEAD seal. - The generation counter is also incremented on every successful
Session::rehandshake, so the stale-cookie filter applies symmetrically to both concurrent-query races and explicitntsWarmCookiesinvocations during an in-flight query.
NTPv4 header validation (rust/src/nts/ntp.rs) #
- Add
STRATUM_UNSYNCHRONIZED_FLOOR = 16and reject any post-AEAD reply withstratum >= 16asNtpError::Unsynchronized. RFC 5905 reserves stratum 16 as the "unsynchronized" sentinel and 17–255 as reserved; previous versions only filtered LI=3, so a server in the alarm condition could surface a wall-clock offset to the discipline loop if it left LI=0. - Reorder the validation so the Stratum-0 short-circuit (Kiss-o'-Death)
runs before the LI=3 / stratum-ceiling check. Real-world KoD
packets routinely arrive with LI=3 because the server has no
synchronised time to advertise; the previous ordering swallowed the
4-octet kiss code (
RATE,DENY,RSTR,NTSN, …) into a genericUnsynchronizederror and stripped the diagnostic the caller needs to choose a back-off strategy. - Validation remains positioned after AEAD
open()and the origin-timestamp check.stratumand the leap indicator are part of the NTP AAD, so by this point the server has signed the value; off-path attackers cannot forge KoD or stratum-16 to disrupt the client. The post-AEAD ordering is pinned by the*_after_seal_*_tamper_as_aead_failuretest family. - New regression tests:
parse_response_prefers_kod_over_unsynchronized_when_both_setpins the new precedence (Stratum 0 + LI=3 ⇒KissOfDeath).parse_response_rejects_invalid_high_stratumpins the new stratum-ceiling check (stratum 16 + LI=0 ⇒Unsynchronized).
- Broaden the
Displayarm and rustdoc onNtpError::Unsynchronizedto"server reports unsynchronized clock (LI=3 or stratum >= 16)"so the diagnostic accurately reflects both triggers; the message passes throughNtsError::NtpProtocol(..)to the Dart side unchanged.
Housekeeping #
rust/src/nts/records.rs: replacebody.len() % 2 != 0with!body.len().is_multiple_of(2)indecode_u16_arrayto satisfy theclippy::manual_is_multiple_oflint (warn-by-default in clippy 1.92, surfaced oncecargo clippy --all-targets -- -D warningswas added to the release gate). Behaviour is unchanged.
Verification #
cargo test --lib: 95 passed, 0 failed, 3 ignored (live-network).cargo clippy --tests --all-targets -- -D warnings: clean across the workspace.
1.0.7 #
Documentation and published-tarball hygiene. No changes to the published Dart surface, the Rust crate, or the Native Assets bridge.
-
example/lib/src/state/nts_controller.dart: prepend a 46-line dartdoc block torunQuerythat documents the NTS-KE cold-start cost (TCP + TLS 1.3 + KE handshake + first NTPv4 exchange ≈ 4 RTTs end to end, no session-ticket resumption), the steady-state path (cached session keys, in-band cookie pool replenishment, ~1 RTT), and the attribution boundary (the latency is RFC 8915 protocol overhead, notRustLib.init(), the Native Assets pipeline, or per-call FFI cost). Includes a production note pointing atexample/main.dart'sntsWarmCookies()warm-then-query pattern as the canonical way to amortize the cold-start cost; the GUI deliberately does not follow it so that the protocol observation tool surfaces the unmasked latency. -
Repository-wide documentation refactor (7 files:
pubspec.yaml,analysis_options.yaml,DEVELOPMENT.md,README.md,example/.pubignore,example/README.md,tool/check_bindings.dart) to replace meta-commentary about pub.dev scorecards,panarubrics, and tag-drop heuristics with objective technical justifications. The platform allow-list now reads as RFC 8915's raw TCP/UDP requirement plus rustls+ring's lack of a wasm32 target; the FRB pin is justified by the silent-memory-corruption risk of a wire-format mismatch; the analyzer-exclude removal is justified by lockstep with the consumer's analyzer view; the// ignore_for_file:directives inlib/src/ffi/**are justified bypublic_member_api_docsbeing enabled and the FFI surface not being excluded. The IANA AEAD-registry reference inexample/GUI_GUIDE.mdis preserved as a legitimate protocol citation. -
.pubignore(new, root): introduce a root.pubignorethat mirrors the root.gitignorepatterns (per dart.dev/go/pubignore, a directory's.pubignorereplaces its.gitignorefor publish purposes) and additionally excludes consumer-irrelevant files:AGENTS.md,CLAUDE.md(AI-agent guidance),ARCHITECTURE.md,DEVELOPMENT.md(self-identified contributor-only documentation),analysis_options.yaml(consumer analyzers read the consumer's own config),flutter_rust_bridge.yaml(FRB codegen config; bindings ship pre-generated),tool/(CI drift check for FRB regeneration), andtest/(internal FFI smoke test, not a public-API verifier). -
example/.pubignore: addanalysis_options.yamlandtest/to the example's exclusion list for the same reasons as the root. The canonical consumer entry point remainsexample/main.dart. -
Net effect verified via
dart pub publish --dry-run: the published tarball drops from 840 KB (1.0.6) to 824 KB, twelve maintainer-only files are stripped, and the warning/hint output is unchanged. No source files inlib/,rust/, orhook/are touched, so the binding drift gate and Native Assets build hook are unaffected.
1.0.6 #
Binding regen consequent on the 1.0.5 analyzer-exclude removal. No changes to the published Dart surface, the Rust crate, or the Native Assets bridge.
lib/src/ffi/frb_generated.dart: regenerate against the currentanalysis_options.yaml. Removing theanalyzer.exclude: [lib/src/ffi/**]block in 1.0.5 (nts-2cq) had a side effect that the bindings CI job did not surface until the next commit that re-triggered the job:flutter_rust_bridge_codegenruns an analyzer-aware fix-up over the Dart it emits before exiting, that pass was a no-op while the FFI files were excluded, and with the exclude gone the pass appliesprefer_final_localsandprefer_const_constructorsto the synthesized dispatcher boilerplate. The committed file (last regenerated in 1.0.2,0349077) was therefore stale relative to the codegen's deterministic output. The regen is purely cosmetic —varlocals insidedco_decode_nts_error/sse_decode_*becomefinal, and the two nullaryNtsErrorvariants gainconstprefixes — and produces no wire-format or public-API change. The file-level// ignore_for_file:directives managed bytool/check_bindings.dartstill suppress both rules so future codegen output that emits a non-final local or non-const constructor remains acceptable to pana without re-failing the drift gate.
1.0.5 #
Example clarity and pub.dev metadata fidelity. No changes to the published Dart surface, the Rust crate, or the Native Assets bridge.
-
example/main.dart: switch the minimal sample from a singlentsQuery()call to a warm-then-query flow that callsntsWarmCookies()first and thenntsQuery(). The original one-call form lumped the NTS-KE handshake into the same latency budget as the NTPv4 exchange and never made the cookie pool visible; the new form mirrors the production access pattern, surfaces thecookies_remainingcounter onNtsTimeSample, and gives readers a self-contained reference for both stages of the protocol.example/example.mdis regenerated as a byte-for-byte fenced mirror so the pub.dev Example tab tracks the runnable sample. The exhaustiveNtsErrorswitch and theRustLib.init()bootstrap order are unchanged. -
example/example.md: drop the developer-facing meta-commentary about the rendering quirk that motivated the file's existence (panapriority list, theexample/main.dartshadowing dance from 1.0.3 / 1.0.4). The fenced sample is the consumer-visible artefact; the rendering history is recorded in this changelog and in thents-9tdcommit message, not in the file pub.dev publishes. -
analysis_options.yaml: remove theanalyzer.exclude: [lib/src/ffi/**]block so localdart analyze/flutter analyzeruns see the same surface pana sees on pub.dev. The FRB-generated files inlib/src/ffi/carry file-level// ignore_for_file:directives (managed bytool/check_bindings.dartand landed in 1.0.2) for the rules they cannot satisfy, which pana respects butanalyzer.excludedoes not — keeping both meant local CI was strictly more permissive than the pub.dev scorecard. With the exclude removed, lint drift between the two environments is impossible. -
pubspec.yaml: add a top-levelplatforms:allow-list withandroid,ios,macos,linux,windows. Earlier releases shipped without this block, which let pana award thewebandwasmplatform tags on the strength of the Dart surface compiling cleanly underdart2js/dart2wasm— but actual runtime use of any nts API on Web cannot work, because RFC 8915 needs raw TCP for NTS-KE on:4460and raw UDP for NTPv4 on:123(neither of which browsers expose to web pages), and therustls+ring+rustls-platform-verifierstack does not targetwasm32-unknown-unknown. Declaring the supported platforms explicitly drops both incorrect tags from the next pana rescore so the pub.dev scorecard reflects the package's true platform surface.
1.0.4 #
pub.dev Example tab fix (take two). No runtime changes.
-
Add
example/example.mdcontaining the minimal NTS-KE sample as a fenced ```dart block plus a pointer to the Flutter GUI showcase atexample/lib/main.dart. The 1.0.3 rename of the minimal sample toexample/main.dartdid not unblock the Example tab: empirical check on the published version-pinned URL still renderedexample/lib/main.dart. The bracket notationexample[/lib]/main.dartin dart.dev's package-layout doc is shorthand for two separate slots in pana's selection list, with thelib/form ranked higher than the bare form. The actual list lives inpana/lib/src/maintenance.dart:example/README.mdexample/example.md← new in 1.0.4, secures the slotexample/lib/main.dart(GUI showcase, no longer rendered)example/bin/main.dartexample/main.dart(1.0.3 rename target, also no longer rendered)
Slot 2 beats slot 3, so the new
example/example.mdfinally wins overexample/lib/main.dart. The minimal sample atexample/main.dartstays in the archive as the runnable Flutter target; the.mdis just a syntactic mirror so pub.dev picks it. -
No changes to the published Dart surface, the Rust crate, or the Native Assets bridge. The two new lines in
pubspec.yamlandCHANGELOG.mdare the only metadata edits.
1.0.3 #
pub.dev Example tab fix. No runtime changes.
- Rename
example/example.darttoexample/main.dartso pub.dev's Example tab renders the intended minimal single-call sample. pub.dev picks the rendered file from a hardcoded priority list documented at https://dart.dev/tools/pub/package-layout#examples; the previous layout placed the minimal sample at priority 5 (example[/lib]/example.dart) where it was shadowed by the Flutter GUI showcase at priority 2 (example/lib/main.dart). The bareexample/main.dartslot also sits at priority 2 but wins over thelib/variant, so the rename promotes the minimal sample without removing the GUI showcase from the published tarball. - Update
example/README.mdto spell the GUI entry point explicitly asflutter run -t lib/main.dart(or-t example/lib/main.dartfrom the repo root) so contributors don't accidentally launch the new top-levelexample/main.dartas the Flutter target. - Update root
README.mdandARCHITECTURE.mdto reference the new path. The 1.0.1 changelog entry that introducedexample/example.dartis left unchanged for historical accuracy.
1.0.2 #
Static-analysis score recovery. No runtime changes.
- Suppress pana-only lints across the FRB-generated bindings via the
// ignore_for_file:directive of each file, applied as a post-codegen patch step intool/check_bindings.dart. pana's static-analysis run uses a stricter ruleset thanflutter_lintsand surfaced 117+ INFO lints against the synthesized freezed wrappers (NtsError), auto-generated default constructors (NtsServerSpec,NtsTimeSample), and dispatcher boilerplate that FRB cannot back with Rust docstrings, costing 10 pub points. Patched files and rules:lib/src/ffi/api/nts.dart:public_member_api_docs.lib/src/ffi/frb_generated.dart:public_member_api_docs,prefer_final_locals,prefer_const_constructors.lib/src/ffi/frb_generated.io.dart:public_member_api_docs.lib/src/ffi/frb_generated.web.dart:public_member_api_docs. Localpana 0.23.12now reports 160 / 160 against the working tree.
1.0.1 #
Documentation and pub.dev metadata polish. No runtime changes.
- Restructure README around a What → Why → How flow and offload the
Rust toolchain, build hooks, and crate breakdown into new
ARCHITECTURE.mdandDEVELOPMENT.mdreference documents. - Add a self-contained
example/example.dartfor pub.dev's Example tab. - Resolve two
dartdocunresolved-reference warnings inlib/src/ffi/api/nts.dartby replacing Rust intra-doc link syntax with literal values in the upstream Rust docstrings and regenerating the bindings. - Trim the package description to fit pana's 180-char ceiling, add
five pub.dev topics (
ntp,time,networking,security,cryptography), and registerscreenshots/gui_showcase.pngas the package listing screenshot. - Expand the inline comment on the
flutter_rust_bridge: 2.12.0pin to document the wire-format rationale and the accepted pana warning.
1.0.0 #
Initial stable release.
Protocol #
- Network Time Security (RFC 8915) client implementing the full NTS-KE
handshake (TLS 1.3, ALPN
ntske/1, port 4460) followed by AEAD-protected NTPv4 (RFC 5905) over UDP/123. - AEAD algorithms: AES-SIV-CMAC-256 (IANA ID 15, default) and AES-128-GCM-SIV (IANA ID 16), negotiated during NTS-KE.
- Cookie management: in-memory cookie jar with automatic refresh via
ntsWarmCookies()when the pool is exhausted.
API #
ntsQuery({required NtsServerSpec spec, required int timeoutMs})returnsFuture<NtsTimeSample>with server transmit time, round-trip duration, stratum, negotiated AEAD ID, and fresh cookie count.ntsWarmCookies({required NtsServerSpec spec, required int timeoutMs})forces a fresh handshake and reports the number of cookies received.NtsErrorsealed class with eight typed variants (invalidSpec,network,keProtocol,ntpProtocol,authentication,timeout,noCookies,internal) for exhaustive pattern matching.
Implementation #
- Cryptographic core implemented in Rust (
rustlsfor TLS 1.3,aes-siv/aes-gcmfor AEAD,ringfor primitives). - Bridged to Dart via
flutter_rust_bridge2.12.0 (pinned exactly to match the Rust crate's wire format). - Bundled through the stable Native Assets API (
hook/build.dart+native_toolchain_rust); no manualcargoinvocation required from consumers.
Platform support #
Android, iOS, macOS, Linux, Windows. Web is not supported (no UDP socket primitive in the browser).
Build #
- Default release builds use the
log-stripCargo feature, elidinginfo!/debug!/trace!format strings at compile time;warn!anderror!survive for diagnostics. - The
verbose_logsuser-define inpubspec.yamlopts into a debug build with full logging (includingrustlsprotocol traces) for development.
Tooling #
tool/check_bindings.dartregenerates FRB bindings and fails CI if the committed Dart bindings orrust/src/frb_generated.rsdrift from the generator output.- CI matrix exercises both the declared SDK floor (Flutter 3.38.10 / Dart 3.10.9) and the pinned development version (Flutter 3.41.7 / Dart 3.11.5).
Requirements #
- Dart
^3.10.0, Flutter>=3.38.0. The lower bound matches thehookspackage (>=1.0.3) requirement. - Native Assets API (stable since Flutter 3.24).
