V- Modal AI: Visual Video / Image Search - Flutter Video SDK
Dart android-sdkflutterflutter-appflutter-packageflutter-sdkflutter-videoflutter-video-editingflutter-video-playerflutter-video-sdkflutter-videosflutter-videosdkmobile-videomobile-video-editor-sdkmobile-video-sdkvideo-editingvideo-sdkvideo-searchvideo-search-enginevideo-streaming
Release Flutter SDK from 5dd1131917e019762bd2590145e1794b5095c1db
vmodal-release-appb23fba45f5d1
diff --git a/README.md b/README.mdindex c977229..a44bc3c 100644--- a/README.md+++ b/README.md@@ -79,8 +79,9 @@ next command I should run.## Integrate into an existing app-Start with [the documentation index](docs/README.md) and-[ready-to-use app recipes](docs/component_patterns.md) for session ownership,+Start with [the documentation index](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/README.md) and+[Choose authentication](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/authentication.md), then+[ready-to-use app recipes](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/component_patterns.md) for session ownership,controller/widget wiring, upload/index/search, recovery, and mobile lifecycle.## Start in minutes@@ -149,6 +150,38 @@ internally.> The SDK never owns your login screen or persists your API key. Authentication identity is separate from project, collection, and stream organization. `VModalProject` and `VmodalClient` provide tenant-scoped access; use `UserSessionManager` below for app-user isolation.+### Choose authentication: developer-backend scoped tokens++The direct runtime-key setup above remains supported. For server-enforced user+grants, your backend verifies the current app session and obtains a short-lived+VModal token using its registered server credential:++```dart+final backend = await VModal.connectWithBackend(+ expectedAppUserId: signedInUser.id,+ expectedProjectId: 'framebase',+ loadToken: () async => ScopedTokenEnvelope.fromJson(+ await developerApi.createVmodalSession(),+ ),+);+final collections = await backend.session.listCollections();+final library = backend.scope('my_library');+final results = await library.search('a person entering the room');+await backend.close();+```++Both mechanisms use the public gateway; data requests go directly to VModal.+Flutter receives no master key, constructs no backend collection selector, and+adds no identity headers. The SDK confirms auth/me binding/grants before return+and coalesces renewal. Close at the start of logout or account switch.++This source API requires corresponding registered origin, Worker and upstream+capabilities; it is not a claim of live deployment. See+[Choose authentication](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/authentication.md),+[the backend guide](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/docs/backend_authentication.md), and the independent+[backend-auth reference](https://github.com/v-modal/vmodal_sdk_flutter/blob/main/example/06_backend_auth/README.md). The preserved+Framebase user-login app remains a shared-key/local-isolation example.+## Isolate signed-in app users sharing one tenant keyYour authenticated host app resolves a stable user ID and its allowed contentdiff --git a/RELEASE_METADATA b/RELEASE_METADATAindex c3dc451..bbeb430 100644--- a/RELEASE_METADATA+++ b/RELEASE_METADATA@@ -1 +1 @@-Source-vmx-api: e969dfe073e422ff65e618238a86398a51e94036+Source-vmx-api: 5dd1131917e019762bd2590145e1794b5095c1dbdiff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256index 6f8ef14..8937570 100644--- a/SOURCE_MANIFEST.sha256+++ b/SOURCE_MANIFEST.sha256@@ -4,19 +4,21 @@ a3e3ce18f80b46587bcd529d13e456d10d97dd5e4a3f15e8e1a18894961120b1 ./.github/workefaab625b09d5b5bb80352b0586e4f81764914a1aff24164e338b6a95fee5973 ./.pubignoreabdc15ffd2312caa935bd8eeb30485b42654c146ded001997cfa240e9a77c7b2 ./CHANGELOG.md37b7148216ac6090e36adfb699d642b8dd1e1b8ba99870e65e88733947a59fa6 ./LICENSE-d8707e1a8e1ad5e89183d06dde554d7daccd2b9ef0693d6090c67dea6625f163 ./README.md-a001f5aef42d295b573e8857038bf10443219759875e0c7767aae03912438188 ./RELEASE_METADATA+4a3171e141f97f254ff26643867c0ccb4a9bb4c0c53057bc439b7bae1b7190bf ./README.md+db5da40576684f0f4aa4d199a81158101f7772de2950306f557dbce7bd595918 ./RELEASE_METADATAdef7e4f643adff5b01b877b6a7fa5b2381612b693c0bf06bd232ee0f7197d342 ./analysis_options.yaml-5aeee476843e07c110c4525685fb6b875fa28824e26eae514f345d593126df48 ./build.sh+4cbda05ee121f7d7c40278a2cdad0322299f7258ddf94c8d7035b26b23d581ca ./build.sh4f18642680fb433554a5523d00bd99e0d650af340bcaebe628f59f63ac84e458 ./dartdoc_options.yaml-aa2787c65ea636f679723f9d6b575ce5c0d70f24e2ab3ac5823a821670b03151 ./doc/README.md-9399282ad46b1c181f92fb378ec51dc8013cd422bd90f2942dc19029fa17fcc0 ./doc/component_patterns.md-c5a4e9f35c43b80bed051903fc923a9629ee876fa1ad8d38fb3a3782338a6229 ./doc/diagrams.md-e5120a94a88f2260b1d0264af7820d95a87cca8727c698f9047e1feae4d1d288 ./doc/manage_api_key.md+1e7cc6b15bfd5b785478ef86b7d1dd0ecaca40385b540797662403631630dc04 ./doc/README.md+397201d1696692d0ad05c2ecf621d0e7b1c3f82b13580fd6d4858b68973d3821 ./doc/authentication.md+b93d87d3e11b0d536fdc119a21b25be0943eb22457465ba31768262611209d38 ./doc/backend_authentication.md+4d40f0045230678833e3896c810a3de2c9f9a802b4ad3aab6d278c6a46d10ff0 ./doc/component_patterns.md+c3beb6981cbaac6fd49d93abbd0dc9fd9e2b3c002ba937e5f66bbe81cf6f94cf ./doc/diagrams.md+c0bd274c1c63db332856740288b1b919106473b70bec549ded5a817adaede71b ./doc/manage_api_key.mda66d39da0983a994474fa516f81fd41bbb131efbd69c955891a41781a76daf24 ./doc/performance.md-c59892e1edadebe19a9bc5211f6d6a2f38ad0aece15d6505f8237405f152896e ./doc/release.md-95637461214d0de45263b904eb38d702253805d989c3f07e9f896af023d915fb ./doc/sdk_contract.md-3531909fc0b44a8640155cb6fb014795950c1af393dbecd9558953b6360b384c ./doc/sdk_doc.md+440332e1f43fc7e1deb8456f237a380751f6b907b2cac96951b5bcbfe2e38a02 ./doc/release.md+2ab6724728c322950ac9eed3ac280a91f7f7dde2272b8037bf74cb3d31ef679f ./doc/sdk_contract.md+db828d1510fb5490a5c88202164a3f2fddd77cce703c2de1e9c774dc553ef7f6 ./doc/sdk_doc.md6210ee89bebfcbf66e2dbfb035238420de4e10e80a3380a689653b1e45b26608 ./doc/search_app.md3271e5e49451d705345e3921393766b8b5d8b11a9cffaac0f0ecc325f5514a72 ./doc/transcode_360.mde246ed229511a24a1ee7e98529c203ef90d1d352290ce8486caebe05683db3a0 ./env.sh@@ -361,17 +363,25 @@ a51475dbc546a45bb5cbc6d85bbd39a5e84a4ca1c8c27402f4d1d7ab8c4e8e29 ./example/05_fb3f31425c264023e88a1f9ce82efdf619bb1ed80c69bcd454b11125a29f97977 ./example/05_framebase_userlogin/test/user_session_controller_test.dart8a1cd1f781e0c217df5c6676557e87ff1ebdb480b6b73e5db64a407164d661b8 ./example/05_framebase_userlogin/test/user_session_failures_test.dart5e3939495af84efeb41a736e11e3d8a9e55954da304dc16d6f646b04baa0399f ./example/05_framebase_userlogin/test/widget_test.dart+bf7d982b4aa28e125b02dbe25a861e148252b189fe03cd98519ce1d4f38fbbd4 ./example/06_backend_auth/README.md+f1aa6fde6d2fca4295953b6482ee71a530316461c24686051d63869fa5ad2522 ./example/06_backend_auth/developer_backend/session.mjs+dae89a3f907d3c79039d626a26b05e31d4dbd2aaa9bac7a9ca4d9173c3c042fd ./example/06_backend_auth/developer_backend/session_test.mjs+8e32e04701b53547c04b2b18a109a72f7fa11b448422707bc7ac9e60fd2a92a7 ./example/06_backend_auth/lib/backend_auth_example.dart+dd01a6e18a7f295b3eb5ad350366dae2ab76c9fa5fb03a79b872973b3c76eea9 ./example/06_backend_auth/pubspec.lock+1a40cfcce0bd4521ab96cefe6c5e12603989e739725fbe5ad00206942d799c7d ./example/06_backend_auth/pubspec.yaml+5e55c3d7c3a221ca7375ccdc05719a8f57b63efd051a55d375cf1861fd3efe6d ./example/06_backend_auth/test/backend_auth_example_test.dartbb2e66ce21a066b5331a8c6ee665f1a4d2fcb3451cde5ce2ba0e6fe492344ac0 ./example/readme.md23756b83470b1f25f6a7e6b5a6270f123a5224e49fd8e2eda36001358951b688 ./install.sh7becacd31a8d134fa435b39cd819798d5fbf58f89b9f30c50362e2dcf757aaed ./lib/src/adaptive_upload.dart-3266fb275cbf5634bc9122b27e30cc86f36a8c606eca2d1efd0ad34effe37ce6 ./lib/src/api_key_provider.dart+8971b2f8db06edecfcc9060f8629a6c9716fc01d29525e0f9047604308e59804 ./lib/src/api_key_provider.dart+4e7f9b6015ddc15fa68b84f08cf7507fe9e28a09e4357a0189251b8fccaf78ba ./lib/src/backend_auth.dart23bfe683fe220a98ef960e89bf4a024b57d472d3da652c46a5e39697dba6251f ./lib/src/client.dart56854450130793060945446c9d4f812dab1ef80de83c51db5f9f4fdc13851c9d ./lib/src/collection_uploads.dart3591a3bfd33164aadcd65b5d5b02bafc5f36b577a304a0e87bec8fb7ac34bb8b ./lib/src/config.dartd3e03d9a72a499659c70f2296115d1d3138b9370a017e027d8255f85f7fb1c5c ./lib/src/content_scope.dart-f5f0f63de2c13aca3813acf91fe8031ae388494db345450a14e4515086ddb176 ./lib/src/errors.dart-0801d536afa98f714a4df66a661c5c5de87a750b2db7e49a0238678d39cc1f83 ./lib/src/http.dart-edd4993e3f56b492b19430a6eb52646d52052a8b8b9a98d7bce784da41195ef9 ./lib/src/models.dart+36739c7c84a2ca469249960aa47b1b585afc704afa6b58b3042f486341b584ab ./lib/src/errors.dart+09dc0dd7869fee12549c21fc06bd0c5c88e0520d3a3a5519f024927dd7dbffbc ./lib/src/http.dart+1d059aa27cf71678d676b62d57341a952506806e6dfe22ab78ea6d364ca35674 ./lib/src/models.dart1612baa4be9d9f1489673ea1368698209fbca9199e9f927a114d696a413deb09 ./lib/src/resources.dart43770c621bffccf69eacebd1e3b297503ca288093c848f0e8ccbd118d7f0d88a ./lib/src/routes.dart27056230065682f3ea3aa747c39c08950dcdca87387f4733adfad18f4b345b06 ./lib/src/routes.g.dart@@ -379,10 +389,10 @@ d8bb946941c49cd18cc11190b909a3a70411a956ec143ccf2a1caf2e1194e7a6 ./lib/src/sess42331852249c8f99874a5e3889c752fd344ad8a5301ede246d5a4fbccb4191f2 ./lib/src/transcode.dartb7f65edb62ce973e55e692a1e20a9f34acb8bf5b82573e4a47551c6d4c32ad45 ./lib/src/transport.dart40c6fde33466faad146ca0ffe24c92ab40b0ed356fd41b0e04f864b6d7747fca ./lib/src/upload.dart-381b448154db5bc7b7969465b7589e0dce1c2018db27281eb96c097f8bec1645 ./lib/src/user_session.dart+10d177fc4112ec064bf42cdf76221c6ee37f89758f66e157f84805cc19e2ebb9 ./lib/src/user_session.dart655a7627df6b9db8059dadd5a7f61c796e8e8da39b7210ce291ac9189027a7fd ./lib/src/utils.dart-fded09f674653828d4cc95bceacac01018d4783cc584ef8eb816edb25e1f8831 ./lib/src/vmodal.dart-7207c5bfb20c0810c9b45b2bc835afeda9ed5ee6bf32b7f9da3a9547eaaaa48d ./lib/vmodal_sdk_flutter.dart+f8ed22691338cc0e42025ad88dbcc818f24854be02504fa6463c0cf3b091e0ab ./lib/src/vmodal.dart+925f12325c39f8c7f4d92eff42592f2874f2514b4334b974c901d5932162a26e ./lib/vmodal_sdk_flutter.dart72fff91181fd3e25fd9afd766930a67025205b61096fd35c55cbdd9a3178ecf0 ./pubspec.lockc2054b07765ac3d058dc8d1e313516b2e6b9ec8b04db7862b9e2d073346325ce ./pubspec.yaml387ec75b8a58410c403abd622bc6627d194a2fa4b839c549600cc0ea28b50f67 ./readme_assets/app1.png@@ -397,10 +407,11 @@ bb5948fd73afd0adfbc1fa34addb946ae688fc8e03f4c54a17c4b067f0679b3d ./security_che75d9810c9d50fd1224462aba8d2d1669cbfa094bd9cc0e5275f3a6a9f1364cb5 ./test.shbe59599b9ba77d031e9b4bad7f8d5c59efd2687888c5b73be4fbea115902106b ./test/adaptive_upload_test.dart8d138ac9ba874307aa11cbd873eded2c913167475db550f79a697f696df1287c ./test/auth_http_test.dart+0336e0c2a7e5b68ba0e897b4ed201047a7efc8c8f55d3f2c8211ffa1d0946f94 ./test/backend_auth_test.dart51001c445940a527271418f3eded8af669dd1eb6c450504e9dd1f12ec16d66a0 ./test/cctv_contract_test.dart3cb772c473b1657f2aaeebd8281e4d9cfee1aaa10b70badb70a1df8d5d7bc389 ./test/client_test.dart56eb465d0c149368f68dce9d54e48ad8f61476b912525d5783fac7de7b7c2943 ./test/config_routes_test.dart-e1f8d5e754fc698b827cb6974c9830c9620e0f905216f3d81d26c29bb3462780 ./test/docs_reference_test.dart+5929ef8b075bfd4a67a866e7279be1c8f1b8f735e9b50ca9c611c37d13e38d4e ./test/docs_reference_test.dartb45470d8e7674bcb87828a8dcf231ac29afb4418774972c66e60cea9788270db ./test/errors_leak_test.dartd132b6dceb89804a47418245845547a25fcf8f89f56b292ee70a404d63364865 ./test/fakes.dart0a1394c90829b91541aa01e9786e3195aae04fc49a7b92775dbf404bf2802107 ./test/fakes_test.dart@@ -408,12 +419,12 @@ d132b6dceb89804a47418245845547a25fcf8f89f56b292ee70a404d63364865 ./test/fakes.d593b356ac3431de80e03e7a0e2f1df0d29589140f44746468213c1cac1c35bbe ./test/multipart_upload_test.dart1247019fcd0549fab4bb48fa9aeee438ea288cc1e73561c46ca7dd6598170d14 ./test/new_api_surface_test.dart97593b7d76911b80a27a7f2ea2bcf283986e881d2bbb1347478ef5241c6a67f9 ./test/readme_pin_test.dart-60b04b0e565aa3a2928b76c36ef1f33e277f619cf1704da339f4e21ced6148b5 ./test/regression_manifest_test.dart+4642fb897dd0b8892e20fa1f2a85d3d6b64ccb207679cde1e8a87c287af10eea ./test/regression_manifest_test.dart5f049dd64b419a6afa46b548cdaba8d1101dd66501cede4425f02ed956b9a669 ./test/resources_models_test.dart701017ce3056f071f324d8fc94ccf2b6a147a3f0abd540eda634fac450fe53e3 ./test/session_guard_test.dart113ee0888fb78edf96476ee9d2c15fba2eecedfa6ff8529a9b86d0feb44a1563 ./test/session_lifecycle_test.dart9b0eb2ce870652644e7b0e73781a1c15ccbdb60b9cb7e25bc08e9004332f587d ./test/session_storage_test.dart-8619ce113bb8669612f9a2a16b1b334ac68435c5972e84828a789511467fcb77 ./test/shell_scripts_test.dart+6b4798bb2f7d31eac0a08141344661624141c6273efa869f509d6f0b28589456 ./test/shell_scripts_test.dartfd3d42374ae441045c4947152dc312020c331fbe07f197030e834e1aa7d06eb5 ./test/tenant_credentials_test.dartefe4f1158e7d4b9ca8e57f3538ce296279817292a4356c1399cf5f2cbae4c52d ./test/transcode_upload_test.dartb94c0fef25560e387c4de5de0e4032fce73aa22b23a4bf38594ea6ff241d914c ./test/transport_test.dartdiff --git a/build.sh b/build.shindex 6b2d900..db77287 100755--- a/build.sh+++ b/build.sh@@ -44,6 +44,7 @@ sdk_pub_get() {(cd example/03_cctv && sdk_flutter pub get)(cd example/04_example && sdk_flutter pub get)(cd example/05_framebase_userlogin && sdk_flutter pub get)+ (cd example/06_backend_auth && sdk_flutter pub get)}sdk_format() {@@ -51,7 +52,7 @@ sdk_format() {## Usage:bash build.sh format'- sdk_dart format --output=none --set-exit-if-changed lib test tool example/01_full_app/lib example/01_full_app/test example/02_users/lib example/02_users/test example/03_cctv/bin example/03_cctv/lib example/03_cctv/test example/04_example/lib example/04_example/test example/04_example/integration_test example/05_framebase_userlogin/lib example/05_framebase_userlogin/test+ sdk_dart format --output=none --set-exit-if-changed lib test tool example/01_full_app/lib example/01_full_app/test example/02_users/lib example/02_users/test example/03_cctv/bin example/03_cctv/lib example/03_cctv/test example/04_example/lib example/04_example/test example/04_example/integration_test example/05_framebase_userlogin/lib example/05_framebase_userlogin/test example/06_backend_auth/lib example/06_backend_auth/test}sdk_analyze() {@@ -65,6 +66,7 @@ sdk_analyze() {(cd example/03_cctv && sdk_flutter analyze)(cd example/04_example && sdk_flutter analyze)(cd example/05_framebase_userlogin && sdk_flutter analyze)+ (cd example/06_backend_auth && sdk_flutter analyze)}sdk_test() {@@ -78,6 +80,7 @@ sdk_test() {(cd example/03_cctv && sdk_flutter test)(cd example/04_example && sdk_flutter test)(cd example/05_framebase_userlogin && sdk_flutter test)+ (cd example/06_backend_auth && sdk_flutter test)}sdk_example_android() {diff --git a/doc/README.md b/doc/README.mdindex 6b38c1b..6ed3dce 100644--- a/doc/README.md+++ b/doc/README.md@@ -1,12 +1,15 @@# Flutter SDK documentationFor an existing Android/iOS app, start with-[Flutter app integration recipes](component_patterns.md). It covers API choice,+[Choose authentication](authentication.md), then+[Flutter app integration recipes](component_patterns.md). They cover API choice,host activation, a complete search controller/widget, upload progress, indexpolling, recovery, storage, mobile lifecycle, and host acceptance tests.| Reading path | Guide || --- | --- |+| Direct keys, local user isolation, or server-enforced scoped tokens | [Choose authentication](authentication.md) |+| Backend endpoint, exact grants, renewal, errors and rollout | [Backend authentication](backend_authentication.md) || Ready-to-use production integration patterns | [Component patterns](component_patterns.md) || Concise tenant-scoped API orientation | [SDK guide](sdk_doc.md) || Exact sessions, permissions, provenance, storage, and response semantics | [SDK contract](sdk_contract.md) |@@ -16,6 +19,7 @@ polling, recovery, storage, mobile lifecycle, and host acceptance tests.| Streaming, concurrency, timeouts, and device measurement | [Performance](performance.md) || Tenant-scoped custom video reducer | [Transcode](transcode_360.md) || Complete session app and host adapter injection | [Framebase example](../example/05_framebase_userlogin/README.md) |+| Separate scoped callback and verified-identity backend reference | [Backend-auth reference](../example/06_backend_auth/README.md) || SDK maintainer publication and export | [Release](release.md) |Session recipes require the 1.3.0 APIs present in this source tree. Use the localdiff --git a/doc/authentication.md b/doc/authentication.mdnew file mode 100644index 0000000..593da93--- /dev/null+++ b/doc/authentication.md@@ -0,0 +1,159 @@+# Choose authentication++The SDK supports two ways to obtain the Bearer credential used by the public+VModal gateway. Your app owns login, signup, guest identity, user permissions and+the identity provider. The SDK owns VModal request credentials and connection+cleanup. Both patterns send search and media requests directly to VModal.++| Pattern | Credential supplied to Flutter | Server authority | Best fit |+| --- | --- | --- | --- |+| Direct runtime credential | Existing VModal API key, static or synchronous provider | Existing VModal principal authority | Tenant applications, evaluation, existing integrations |+| Direct credential with app-user sessions | Same API key plus host-resolved local user policy | Same principal authority; SDK narrows local operations | Cooperative clients requiring local account isolation |+| Developer-backend scoped connection | Short-lived VModal-issued scoped token returned by your backend | Signed exact grants checked by VModal and upstream handlers | Apps whose users must have distinct server-enforced access |++The second row adds local ownership and cancellation to the first. A shared+tenant key can still authorize a modified client to perform tenant-wide+operations. Use the scoped connection when the server must enforce the+app-user boundary.++This guide describes source APIs. A successful local test is not evidence that+your public VModal deployment supports delegated access. Configure the origin,+edge, registrations and upstream enforcement and complete the+[rollout checks](backend_authentication.md#deployment-and-acceptance) before+enabling the scoped pattern in a production app.++## Direct runtime credential++Preserve your existing integration:++```dart+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++final keys = MutableApiKeyProvider(runtimeVmodalKey);+final project = VModal.configure(+ projectId: 'food_app',+ apiKeyProvider: keys,+);+final library = project.scope(+ collectionName: 'user_123',+ streamName: 'favorites',+);+final collections = await project.listCollections();+final results = await library.search('a person entering the room');++await project.close();+keys.close();+```++`SdkConfig(token:)`, `SdkConfig(apiKeyProvider:)`, `VmodalClient`, and custom+`ApiKeyProvider.current()` implementations retain their public contract.+`VModal.configure` performs no token exchange. Its logical collection mapping+uses `projectId__collectionName`; these names organize data and do not verify+app identity or narrow the API key's server authority.++For account-specific ownership under a shared runtime key, use+`TenantCredentialSource` and `UserSessionManager` as shown in+[manage_api_key.md](manage_api_key.md). The host resolves the verified subject+and allowed content mapping, and invalidates the outgoing session at the start+of a switch. `auth.me()` and `session.verifyPrincipal(...)` check the VModal+storage principal; they do not identify the host app user in this pattern.++The preserved [Framebase user-login example](../example/05_framebase_userlogin/README.md)+demonstrates this host orchestration and shared-key local isolation. Its mock+issuer and `api_token`/`firebase_uid` envelope are a separate contract from a+VModal-issued scoped token.++## Developer-backend scoped connection++Sign your user in using the host app's existing identity stack, then connect:++```dart+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++final backend = await VModal.connectWithBackend(+ expectedAppUserId: signedInUser.id,+ expectedProjectId: 'framebase',+ loadToken: () async {+ final json = await developerApi.createVmodalSession();+ return ScopedTokenEnvelope.fromJson(json);+ },+);++final collections = await backend.session.listCollections();+final library = backend.scope('my_library');+final info = await library.collectionInfo();+final results = await library.search('a person entering the room');+if (results.assets.isNotEmpty) {+ final image = await library.imageBytes(results.assets.first);+}++await backend.close();+```++`developerApi` is your authenticated host API client. The SDK does not hardcode+its URL or depend on Firebase, Auth0, Clerk, cookies or a particular backend+framework. The callback returns a typed envelope; it never returns your server+master key. The connection validates the expected app user and project, confirms+the complete binding and grants through VModal `/auth/me`, and then publishes+a guarded `UserSession`.++Choose a grant by its stable `grant_id`. The exact collection selector is+provided by the issuer and passed unchanged to VModal. Do not construct a+collection name from the user ID, prepend the project, lowercase selectors, or+reuse a logical direct-auth scope for a backend grant.++The example deliberately progresses from authentication to collection discovery+and search. Index/job discovery requires `indexation` and is available only+after the deployment enables and enforces that action. The initial scoped+read implementation denies unsupported writes and index operations. Your+direct tenant integration retains its existing upload/index APIs.++## Login patterns++| Host login pattern | Callback responsibility |+| --- | --- |+| Firebase/Auth0/Clerk identity token | Send current host token to your backend; backend verifies it and derives its stable subject |+| Existing session cookie | Use the authenticated host HTTP client; backend verifies the current cookie session |+| Custom login/session | Reuse your established verifier and policy store; derive identity server-side |+| Guest access | Backend verifies and assigns a stable guest subject with explicit grants; SDK does not invent authorization identity |+| Multi-project app | Create a separate connection for each registered project; project is part of local ownership |++Host identity tokens are not VModal credentials. Send them only to your+developer backend. VModal signs its own scoped token after authenticating your+registered backend credential; the developer does not sign VModal tokens.++## Lifetime and account changes++Keep the connection at the host account lifetime and inject its `UserScope`+into feature controllers. Pages dispose their own subscriptions, players and+operation tokens. The host account owner closes the connection.++At the start of logout or an account switch, call `close()` immediately, before+waiting for identity-provider sign-out. It invalidates local work synchronously+and then performs asynchronous cleanup. Clear host widgets, playback, image+caches, navigation state and history as part of that transition. Create a fresh+connection after verifying the next host identity.++Credential renewal with identical identity and policy preserves the active+session and local owner keys. Changed identity, tenant, principal, project,+policy revision or grants invalidates the connection and requires fresh+activation. A same-ID policy change is still a policy change.++Tokens are kept in memory. Archives and upload checkpoints may contain scoped+owner references, but never a bearer or envelope. Reauthorize before restoring+owner data. Logout does not instantly revoke a copied token or an already+issued standalone signed media URL; those capabilities have separate validity.++## Terminology and next guides++Both authentication patterns normally use `SdkConfig.mode == 'gateway'` and+`Authorization: Bearer <credential>`. The SDK's internal-development+`mode: 'direct'` / `unsafeDirect` is a different connection mode that can send+trusted identity fields. It is not the direct authentication pattern described+here. Mobile callers never supply `X-User-Id`, `X-Tenant-Id` or grant headers.++- [Backend setup, contracts and lifecycle](backend_authentication.md)+- [Tenant key rotation and local user sessions](manage_api_key.md)+- [Controller and widget integration](component_patterns.md)+- [Exact ownership and resource contract](sdk_contract.md)+- [Independent backend-auth reference](../example/06_backend_auth/README.md)diff --git a/doc/backend_authentication.md b/doc/backend_authentication.mdnew file mode 100644index 0000000..718161d--- /dev/null+++ b/doc/backend_authentication.md@@ -0,0 +1,332 @@+# Developer-backend authentication++Start with [Choose authentication](authentication.md) for the direct and scoped+quickstarts. This guide specifies the server handoff, connection lifecycle,+permissions and acceptance checks for a developer-backend scoped connection.++## Who owns each boundary++```mermaid+sequenceDiagram+ participant App as Host app / Flutter SDK+ participant Dev as Developer backend+ participant VM as VModal origin and edge+ participant Search as Search / media service+ App->>Dev: Authenticated request for VModal session+ Dev->>Dev: Verify current host identity and resolve policy+ Dev->>VM: Scoped issuance with registered server API key+ VM->>VM: Check principal/project ceiling and sign token+ VM-->>Dev: Short-lived version-1 envelope+ Dev-->>App: Envelope unchanged; no master key+ App->>VM: Scoped bearer to /auth/me+ VM-->>App: Verified identity and canonical grants+ App->>VM: Search/discovery/media with scoped bearer+ VM->>Search: Principal routing and trusted delegated context+ Search->>Search: Authorize exact resource before result or side effect+ Search-->>App: Authorized result through gateway+```++The SDK checks contracts and fences stale local work. Server signature,+registration and resource checks authorize requests even if a caller changes+the Flutter app or uses raw HTTP. The developer backend authorizes its own+app users within a delegation ceiling registered with VModal. VModal does not+query or replicate the developer's user directory.++## Implement your session endpoint++Your backend chooses its route and authentication mechanism. The independent+[Node handler reference](../example/06_backend_auth/developer_backend/session.mjs)+uses `POST /vmodal/session` with `{}` and mandatory injected identity/policy+adapters. Mount the equivalent handler in your existing backend stack.++For every acquisition and renewal:++1. Verify the current host token or cookie session and derive `app_user_id`.+2. Load enabled access, exact grants and a stable `policy_revision` from your+ policy store. Project and server credential come from server configuration.+3. Send the request below using the registered server-side `ak_...` credential.+4. Return the successful VModal envelope unchanged with `Cache-Control: no-store`.+5. Return classified safe errors; do not return a master-key fallback.++```http+POST /api/v1/auth/scoped-token+Authorization: Bearer <registered developer-server ak_ credential>+Content-Type: application/json++{+ "version": 1,+ "project_id": "framebase",+ "app_user_id": "verified_app_subject",+ "policy_revision": "policy_42",+ "expires_in": 300,+ "grants": [+ {+ "grant_id": "my_library",+ "collection_id": "library_a7f9",+ "stream_name": "street_study",+ "mode": "vid_file",+ "actions": ["discover", "search", "media"],+ "collection_wide": false+ }+ ]+}+```++The public issuance endpoint belongs to users_api; it is not a search route.+An ordinary runtime key cannot issue scoped tokens without explicit registered+issuance authority. A scoped token cannot issue child tokens. Do not send a host+identity token, refresh token, password, caller-selected principal or tenant to+this endpoint.++Use an opaque stable host subject, unique within the registered project. The+phone's expected subject is a consistency check; the backend must derive the+authorizing subject itself. Recheck identity and policy at every renewal,+including after host login changes. A previous VModal token is not proof that+the host session is still valid.++## Envelope contract++`ScopedTokenEnvelope.fromJson` parses this separate version-1 contract:++| Field | Meaning |+| --- | --- |+| `version`, `auth_mode`, `token_type` | `1`, `developer_backend`, `Bearer` |+| `access_token` | VModal-issued compact JWT, at most 8192 characters |+| `issued_at`, `expires_at` | UTC RFC 3339 timestamps ending in `Z` |+| `expires_in` | Original issuance lifetime, 60–900 seconds; default server request is 300 |+| `principal_id` | VModal owner resolved from the registered server key; storage and billing owner |+| `tenant_id` | Provisioned delegation tenant; never inferred from app UID |+| `project_id` | Registered developer integration |+| `app_user_id` | Backend-verified opaque app subject |+| `policy_revision` | Host version of this user's complete effective policy |+| `delegation_revision` | Monotonic VModal registration revision |+| `grants` | One to sixteen exact canonical grants |++The parser rejects unsupported versions, unknown fields, wrong scalar types,+invalid times, duplicate grant IDs/selector tuples, empty or unknown actions,+and unusable credentials. Parsed values are immutable and string formatting+redacts the bearer. Do not calculate expiry as “received now + expires_in”;+network time does not extend a token's lifetime. Use `expires_at`.++The JWT uses RS256, type `vmodal-scoped+jwt`, a configured `kid`, environment+issuer and audience `vmodal:search-api`. VModal retains the private key. Its+signature/time/schema/registration checks are independent of any identity+provider's JWT policy. JWT issuer, audience and expiration semantics follow+[RFC 7519](https://www.rfc-editor.org/rfc/rfc7519); separate token types and+explicit algorithm/issuer checks follow+[RFC 8725](https://www.rfc-editor.org/rfc/rfc8725). The particular VModal+algorithm, grants and lifetime limits are this service's product contract.++The envelope is not Framebase's legacy mock `api_token`/`firebase_uid`+response. Do not adapt that mock by renaming fields or presume its tenant-wide+key becomes scoped. The preserved example documents a different auth pattern.++## Exact grants and discovery++`grant_id` is a stable developer label used by `backend.scope('my_library')`.+`collection_id` is the exact backend selector serialized as `group_name`, not+an asset-association database ID. Stream and mode remain exact and+case-sensitive. A logical project prefix or a user ID never adds authority.++Each request must satisfy one complete grant. Action permission from one grant+cannot combine with collection/stream authority from another. Wildcards are+not accepted. `collection_wide: true` explicitly permits actions across the+collection/mode; it does not change the operation's default stream.++| Action | Scope behavior |+| --- | --- |+| `discover` | List allowed collections/streams; withhold inaccessible aggregates and versions |+| `search` | Require or safely narrow exact collection, stream and mode; restrict alternative sources |+| `media` | Resolve canonical ownership before bytes or URL issuance; validate every bulk member |+| `indexation` | Job/index discovery and creation require handler ownership enforcement before enablement |+| `upload`, `metadata` | Every upload side protocol or referenced asset must be authorized before enablement |+| `delete` | Requires explicit collection-wide authority and existing confirmation semantics before enablement |++The initial deployment supports a defined read-route allowlist and rejects+unsupported scoped actions at issuance. Direct credentials retain their existing+resource contract. Do not add a write action to a mobile envelope to enable it.+Generic forwarding, admin and raw storage-credential routes are denied to scoped+tokens regardless of the action strings.++Scoped job, media or asset routes with only an ID must resolve canonical+principal/collection/stream/mode ownership; principal membership alone is+insufficient. Explicit scope denial returns `403`. A missing or inaccessible+selector-less resource returns non-enumerating `404`. Bulk operations validate+all members before returning protected results or mutating data.++## Connect and own the connection++```dart+final connection = await VModal.connectWithBackend(+ expectedAppUserId: hostUser.id,+ expectedProjectId: 'framebase',+ loadToken: loadCurrentHostVmodalEnvelope,+ // baseUri: configuredPublicGatewayUri,+ timeout: const Duration(seconds: 30),+ refreshLeeway: const Duration(seconds: 60),+);+```++`initialToken` can seed a previously fetched envelope, but `loadToken` remains+required for renewal. Seeded and callback credentials undergo the same expected+identity, expiry and `/auth/me` checks. A candidate is not installed until the+gateway confirms principal, tenant, project, app subject, revisions and exact+grants. An older gateway that only understands API keys fails activation.++The connection reuses `UserSession` and `UserScope`. It does not expose an+unrestricted tenant client or duplicate search/upload implementations. Existing+feature controllers that accept `UserScope` can use the returned scope.++| API | Responsibility |+| --- | --- |+| `session` | Current active guarded session; invalid access fails |+| `scope(grantId)` | Select exact frozen mapping; unknown ID fails locally |+| `refresh()` | Explicit credential renewal, coalesced with an active renewal |+| `state`, `states` | Current lifecycle and token-free state events |+| `close()` | Immediate local invalidation followed by idempotent cleanup |++Subscribe to states in the connection owner, and cancel the subscription with+that owner. App resume can call `refresh()` when appropriate; request-time+expiry checks remain authoritative for dispatch. Do not implement another+per-widget token timer or send raw Authorization headers from resources.++## Renewal and failure behavior++Effective proactive leeway is the smaller of configured leeway and half the+issued lifetime. Parallel renewal uses one acquisition. Shared HTTP readiness+checks every gateway request before taking its immutable credential/revision+snapshot, including binary and streaming paths.++A still-valid accepted token may continue during a temporary renewal outage.+An expired or rejected revision cannot dispatch. Candidate validation failures+must not overwrite a valid accepted revision; authoritative identity or policy+rejection invalidates the connection. Acquisition has bounded attempts and a+timeout spanning callback and candidate verification.++| State | Host UI behavior |+| --- | --- |+| `ready` | Use permitted operations |+| `refreshing` | Renewal is in progress; still-valid old credentials may serve work |+| `unavailable` | Show a recoverable connection failure; preserve host login |+| `expired` | Require successful credential renewal before more requests |+| `invalidated` | Retire scopes and UI; resolve identity/policy and reconnect |+| `closed` | Permanently retired; create another connection for a new activation |++| Failure | Action |+| --- | --- |+| Host session `401` | Invalidate VModal connection; host decides how to sign in again |+| Host policy `403` | Invalidate; obtain a fresh authorized setup |+| Temporary backend/issuer failure | Keep a still-valid token; gate after expiry; retry within bounded acquisition policy |+| VModal eligible GET/HEAD `401` | One credential recovery and one eligible read replay; stale denial cannot reject a newer revision |+| VModal POST/mutation `401` | Surface failure; block reuse of failed revision; do not replay automatically |+| VModal `403` | Resource/action denial; no renewal loop or tenant-key fallback |+| VModal `404` | Preserve not-found semantics; no credential refresh |+| Identity/policy/envelope mismatch | Safe contract failure; invalidate or fail activation |++Search is currently a POST. A failed POST search is surfaced even though its+business intent is a read; the host may deliberately resubmit after credential+recovery. Unknown mutation completion after a timeout requires reconciliation,+not automatic replay. No scoped failure falls back to a master or tenant key.++Host callback adapters must map HTTP failures to SDK-classified errors; throwing+a generic exception for every response loses identity-versus-outage behavior.+The separate reference explains those classifications. Keep response bodies,+identity tokens and server credentials out of exception messages and logs.++Use the public error contract:++```dart+// These exceptions contain only classification and safe retry metadata.+throw const BackendAuthException(BackendAuthFailure.identityRejected); // 401+throw const BackendAuthException(BackendAuthFailure.accessDenied); // 403+throw BackendAuthException(+ BackendAuthFailure.unavailable, // timeout, 429 or temporary 5xx+ retryAfter: safeRetryAfter,+);+throw const BackendAuthException(BackendAuthFailure.invalidResponse);+```++Do not throw every response as a generic AuthException or expose backend bodies.+The coordinator bounds transient retries and interprets authoritative identity/+policy rejection separately. The+[reference adapter](../example/06_backend_auth/lib/backend_auth_example.dart)+maps HTTP status to these classifications.++### Enabled read routes++The initial origin/upstream allowlist is explicit:++| Downstream search route | Required action |+| --- | --- |+| `POST /api/external/v1/search` | `search` |+| `GET /api/external/v1/collection/groups` | `discover` |+| `POST /api/external/v1/image/get_url` | `media` |+| `POST /api/external/v1/image/get_url_bulk` | `media` |+| `POST /api/external/v1/image/get_image` | `media` |+| `POST /api/external/v1/image/get_image_bulk` | `media` |++Flutter uses its existing proxy routes for these operations; developers do not+manually build these downstream URLs. Modes are `img_file`, `vid_file`, and+`vid_stream_day`. Missing search selectors are narrowed only when one complete+grant matches. Empty/aggregate streams and widened metadata queries are denied.+Group discovery withholds collection aggregate versions/modalities/timestamps;+stream-only users cannot infer another stream's metadata. `collectionInfo()`+and `latestVersion()` return null when discovery supplies no exact stream row;+do not interpret absent aggregate data as an empty collection. Audio and ASR+search in `vid_stream_day` are denied because the legacy retrieval path cannot+preserve exact delegated stream ownership. All other data routes+and services are denied for scoped credentials until deliberately enabled.++## Ownership, persistence and revocation++Backend local ownership includes gateway namespace, project, tenant, app subject,+exact scope and policy. The same UID in different projects cannot share archived+content or checkpoints. Token text, expiry and `jti` are excluded from owner+identity so same-policy rotation preserves a live session and handles.++Changed grants or revisions require fresh activation even for the same subject.+Close the outgoing connection at the beginning of logout or an account switch;+late acquisition/search/progress/storage results cannot reactivate it. The host+still clears its own rendered state, player and caches.++VModal does not promise fleet-wide immediate per-user logout. A copied scoped+token remains valid until expiry unless its registered delegation is invalidated.+Disabling a registration or incrementing its revision takes effect within the+configured bounded registry distribution window, at most 30 seconds under the+deployment contract. Host policy revisions are checked on new issuance; changing+one does not remotely revoke an already issued token.++Standalone signed URLs and server jobs have separate lifetimes. Scope-check new+capability issuance and cap its lifetime to the bearer where supported; do not+claim closing a local connection cancels a server job or immediately revokes an+already issued storage capability.++## Deployment and acceptance++Keep delegation disabled until the complete chain is deployed and checked:++1. Provision authoritative principal-owned resource metadata and exact registered+ project ceiling, tenant, server-key fingerprint and lifetime/revision policy.+2. Configure signing and verification keys on users_api and the separate VModal+ verification policy on the Worker. Preserve old verification keys through the+ expiry of the last token using their `kid`.+3. Deploy upstream canonical scope checks and gateway default-deny route coverage.+4. Verify registration freshness/distribution in every origin process. Missing+ or stale registry/key dependencies deny scoped access and preserve direct auth.+5. Run direct regression and a dedicated registered-project smoke through the+ real public edge → origin → upstream path.+6. Use A's raw bearer to request B's collection, stream, media and bare resource+ IDs; verify `403`/non-enumerating `404` before output or side effects.+7. Check expiry, concurrent renewal, A→B→A fencing, same-policy rotation, changed+ policy, stable subject rate buckets, principal aggregate limits and log fields.+8. Enable the tested project and release a verified immutable SDK artifact.++Rollback disables issuance/registration for scoped access while retaining direct+credentials. Tokens, subject metadata and rate controls must continue using the+principal for billing and home selection; renewals must not reset rate buckets.+Access logs record nullable delegated metadata and a token identifier, never the+bearer or host session token.++Local checks cover lifecycle and contracts; only real public-path acceptance+establishes deployment compatibility. See [release.md](release.md) and the+server's auth/route/storage/release documentation for operational configuration.diff --git a/doc/component_patterns.md b/doc/component_patterns.mdindex c88a1f2..35d43e8 100644--- a/doc/component_patterns.md+++ b/doc/component_patterns.md@@ -33,15 +33,52 @@ Canonical contracts remain in [sdk_contract.md](sdk_contract.md) and[Framebase](../example/05_framebase_userlogin/README.md); its auth and issuerimplementations are mocks unless the host replaces them.+## Choose authentication first++[Choose authentication](authentication.md) puts the two quickstarts together.+The existing recipes below demonstrate direct keys with local app-user policy.+For server-issued exact user grants, replace that setup with:++```dart+final backend = await VModal.connectWithBackend(+ expectedAppUserId: verifiedHostUser.id,+ expectedProjectId: 'framebase',+ loadToken: () async => ScopedTokenEnvelope.fromJson(+ await authenticatedDeveloperApi.createVmodalSession(),+ ),+);+final collections = await backend.session.listCollections();+final library = backend.scope('my_library');+```++Inject `library` into the same session-bound search controller. BackendConnection+owns the manager/source lifecycle and confirms delegated binding/grants through+auth/me before return. The callback uses current host identity, maps failures+to `BackendAuthException`, and returns no master key. The separate+[backend-auth reference](../example/06_backend_auth/README.md) demonstrates+generation fencing and mandatory verified backend adapters, preserving Framebase.++Scope actions determine usable recipes. Initial scoped reads support discovery,+search and media; upload/index/metadata/delete recipes require enforced server+handler support and enabled grants. Direct scope instances keep their existing+resource contract. Mobile action sets do not enable server capabilities.++Close the backend connection at the start of account switch/logout, clear host+view/player/cache state, and activate another after authorization. Observe state+at the account owner. Temporary failure preserves host login; identity/policy+invalidation retires scopes. Same-policy rotation preserves handles/storage,+and project participates in backend owner identity.+## 1. Choose the API and own its lifetime| Integration | Use when | Host responsibility || --- | --- | --- |+| `BackendConnection` → `UserSession` → `UserScope` | Backend issues exact server-enforced user grants | Own host login/callback; close connection and clear UI on transition || `UserSessionManager` → `UserSession` → `UserScope` | A signed-in user has an exact allowed library policy | Verify host identity/policy; clear app-owned UI, players, caches, and navigation on transition || `VModalProject` → `VModalScope` | Tenant-scoped evaluation or an app that implements its own complete isolation | Own identity fencing, cancellation, storage partitions, and every low-level resource lifecycle || `VmodalClient` resources | Advanced tenant operations outside the restricted session interface | Own all isolation and selector contracts; never mix these calls into a feature claiming session guarantees |-A VModal bearer authenticates the tenant. `auth.me()` reports that tenant+A direct VModal API-key bearer authenticates the tenant. Its `auth.me()` reports that tenantprincipal. It cannot determine which app user is signed in or which contentthat user may access. Local session isolation does not establish server-sideapp-user authorization under a shared tenant key; the deployment must enforcediff --git a/doc/diagrams.md b/doc/diagrams.mdindex 63a1632..1922f6c 100644--- a/doc/diagrams.md+++ b/doc/diagrams.md@@ -5,6 +5,61 @@ API in the 1.3.0 source interface. The host app owns sign-in, trusted identityand policy resolution, and visible UI state. The SDK owns session guards,resource operations, transport, and tenant credential coordination.+## Dual authentication and the server authority boundary++The numbered tenant-session sequences below remain the direct-key pattern.+Backend-scoped mode adds a separate credential source while reusing guarded+session operations. Both use the same public gateway. See+[authentication.md](authentication.md) and+[backend_authentication.md](backend_authentication.md).++```mermaid+flowchart LR+ Host["Host identity and policy"] --> Dev["Developer backend"]+ Dev -->|"Registered server credential + exact user grants"| Issuer["VModal issuer / delegation ceiling"]+ Issuer -->|"Short-lived signed envelope"| Dev+ Dev -->|"Authenticated host callback"| Connection["BackendConnection"]+ Connection --> Source["Scoped readiness / renewal coordinator"]+ Connection --> Session["Existing UserSession / UserScope"]+ Source -->|"Candidate auth/me verification"| Gateway["Public edge and origin"]+ Session --> HTTP["Shared guarded HTTP"]+ Source -->|"Immutable accepted revision"| HTTP+ Direct["Direct ApiKeyProvider / tenant source"] --> HTTP+ HTTP -->|"Bearer credential"| Gateway+ Gateway -->|"Storage principal + trusted signed scope"| Search["Canonical resource authorization"]+```++The storage principal determines home selection, billing and aggregate quota.+App subject/project determine delegated ownership and a stable rate bucket.+Grant labels select exact collection/stream/mode and never manufacture authority.+Upstream handlers enforce complete grants even for raw HTTP clients.++```mermaid+stateDiagram-v2+ [*] --> ready: acquire, validate binding, confirm auth/me+ ready --> refreshing: renewal window or explicit refresh+ refreshing --> ready: same identity and policy verified+ refreshing --> unavailable: temporary acquisition failure+ unavailable --> refreshing: retry acquisition+ ready --> expired: expiry gates dispatch+ unavailable --> expired: accepted token expires+ expired --> refreshing: new acquisition+ ready --> invalidated: changed policy or rejected identity+ refreshing --> invalidated: binding or policy mismatch+ invalidated --> closed: close and reconnect separately+ ready --> closed: logout / account switch+ refreshing --> closed: invalidate before awaiting cleanup+ unavailable --> closed: host closes connection+ expired --> closed: host closes connection+```++State is observable behavior, not a host login state machine. A still-valid old+revision can serve independent requests during transient renewal failure;+expired/rejected revisions cannot dispatch. Closing fences late renewal and+search/progress/storage completions. Same-policy rotation preserves owner keys;+new project/user/policy requires a fresh session. Already issued remote jobs or+signed capabilities retain their independently documented lifetime.+## 1. App, user auth, VModal auth, and SDK layers```mermaiddiff --git a/doc/manage_api_key.md b/doc/manage_api_key.mdindex cfefe46..744e1f3 100644--- a/doc/manage_api_key.md+++ b/doc/manage_api_key.md@@ -1,10 +1,53 @@-# Manage tenant API keys and app-user sessions+# Manage runtime credentials and app-user sessions++Choose the credential pattern first in [authentication.md](authentication.md).+This guide's tenant coordinator applies to direct API-key authentication.+For server-enforced user grants, use `VModal.connectWithBackend` and the scoped+coordinator described in [backend_authentication.md](backend_authentication.md).+Do not share a scoped credential source across users or attach it to the+tenant-wide rotation flow.Retrieve credentials through the host's authenticated, trusted service and-keep them in memory. VModal credentials identify the tenant principal; Firebase,+keep them in memory. Direct VModal API keys identify the tenant principal; Firebase,Clerk, or another host identity system supplies the stable app-user ID. A and Bmay share one tenant key and `auth.me()` response. That response never selects-their local owner namespace or proves their content permissions.+their local owner namespace or proves their content permissions. Scoped auth/me+instead adds the verified app subject/project/policy/grants and is checked+against the envelope before the backend connection becomes ready.++## Backend connection lifecycle++```dart+final backend = await VModal.connectWithBackend(+ expectedAppUserId: signedInUser.id,+ expectedProjectId: 'framebase',+ loadToken: () async => ScopedTokenEnvelope.fromJson(+ await developerApi.createVmodalSession(),+ ),+);+final library = backend.scope('my_library');+await backend.refresh(); // coalesced renewal, no mutation replay+await backend.close(); // local VModal cleanup; host owns sign-out+```++The callback verifies current host login through the developer backend on every+acquisition and returns only a short-lived VModal-signed token. Parse/identity+errors differ from temporary availability failures; see the backend guide and+the [reference adapter](../example/06_backend_auth/lib/backend_auth_example.dart).++Shared HTTP gateway paths check readiness before taking Bearer snapshots.+Proactive renewal leeway is capped at half the lifetime. Expiry uses+`expires_at`, and renewal is coalesced. A valid token may continue during a+temporary outage; expired or rejected revisions block dispatch. Same-policy+renewal preserves session and owner; changed policy/binding requires reconnect.++Observe token-free `ready`, `refreshing`, `unavailable`, `expired`, `invalidated`+and `closed` events at the account owner. Call `close()` at the start of an+account transition and discard retired scopes/UI. Backend owner identity+includes project/service/tenant/user and excludes bearer, expiry and `jti`.++The tenant-specific sections below retain their contract. The tenant option+`retainOnRenewalFailure` is not a backend-mode fallback to broader credentials.## Session-bound configurationdiff --git a/doc/release.md b/doc/release.mdindex bb9afc0..8459912 100644--- a/doc/release.md+++ b/doc/release.md@@ -1,5 +1,37 @@# Release process+## Scoped authentication rollout gate++The source includes `connectWithBackend` and a separate+[backend-auth reference](../example/06_backend_auth/README.md). Neither local+fixtures nor source export establish live support. Before releasing this mode,+complete the [backend acceptance sequence](backend_authentication.md#deployment-and-acceptance):+registered project/key/resource authority, bounded registry distribution,+origin RS256 issuance/validation, independent Worker VModal policy, and upstream+default-deny canonical grant enforcement. Test the real public edge chain with+raw cross-user requests and preserve direct-key regression.++The initial scoped route allowlist covers search, filtered group discovery and+four image operations. Indexation/upload/metadata/delete are denied until their+complete handler and side-protocol ownership contracts are enabled and tested.+Do not document these writes as available merely because Flutter exposes those+actions in its existing direct-auth session API.++The normal Dart build gates include the backend reference's dependency,+format, analysis and tests. Node is optional for Flutter consumers. Run the+reference backend's separate offline gate explicitly with Node 22+:++```bash+node --test example/06_backend_auth/developer_backend/session_test.mjs+```++The Dart SDK suite covers strict envelopes, auth/me agreement, expiry, renewal,+and account fencing. The standalone export regression checks auth guides,+source, reference files and their local links, keeping `docs/todo` excluded.+Release workflows retain their existing secret-detection and publication gates.+Disabling issuance/registration rolls back scoped access while preserving direct+keys. No deployment or public publication is performed by adding these sources.+The package is pinned to Flutter 3.44.6. `install.sh` verifies the officialarchive checksum and installs only into a user-owned cache. Run `bash test.sh all`for the offline gate and `bash test.sh live` only after explicitly loading thediff --git a/doc/sdk_contract.md b/doc/sdk_contract.mdindex fdef1f3..304e05d 100644--- a/doc/sdk_contract.md+++ b/doc/sdk_contract.md@@ -7,6 +7,7 @@ behavior. `test/fixtures/routes_contract.json` is the reviewed normalized mirror| Resource | Public Flutter operations | Contract status ||---|---|---|+| Backend scoped connection | `VModal.connectWithBackend`, `BackendConnection`, `ScopedTokenEnvelope`, `ScopedGrant` | Async scoped acquisition/renewal and guarded session; requires enabled server deployment || App-user sessions | `UserSessionManager`, `UserSession`, `UserScope`, `ContentMapping` | Opt-in same-tenant app-user isolation; gateway only || Scoped facade | `VModal.configure`, `VModal.fromClient`, `VModalProject.scope`, `listCollections`, `close` | Compatible tenant-scoped API; bypasses session guarantees || Scoped operations | `upload`, `uploadMetadata`, `search`, `addAssets`, `updateAsset`, index lifecycle, collection deletion | Immutable organization; delegates to resources |@@ -49,16 +50,46 @@ or API-key-provider contract. `VmodalClient` remains public and compatible.`VModal.fromClient` transfers lifecycle ownership, so the project is the objectthat must be closed.+## Dual-auth credential contract++Direct `SdkConfig(token:)`, synchronous `ApiKeyProvider.current()`,+`VModal.configure` and tenant rotation APIs stay compatible. Backend mode is+explicit through `connectWithBackend`; both use gateway Bearer credentials.+Internal-development `unsafeDirect` is a separate connection mode.++The backend source performs async readiness before every gateway snapshot.+Its candidate auth/me probe bypasses coordinator renewal hooks, confirms the+complete delegated identity/policy/grants, and installs only after confirmation.+Eligible reads have bounded recovery; POST search/upload/index/delete never+receive automatic auth replay.++`ScopedTokenEnvelope` and `ScopedGrant` are strict immutable version-1 handoffs.+`BackendConnection` selects exact grants through an existing guarded `UserScope`,+exposes state, coalesces refresh, and retires its session synchronously before+awaited cleanup. It exposes no unrestricted tenant resources. SDK checks do+not replace origin and upstream enforcement against raw clients.++Same binding/policy renewal preserves session/handles/storage. Changed principal,+tenant, project, app user, policy, delegation revision or grants invalidates.+Project enters backend ownership before archive/checkpoint keys are derived;+direct key encoding stays compatible. Bearer, `jti` and expiry are excluded.++See [authentication.md](authentication.md) for pattern choice and+[backend_authentication.md](backend_authentication.md) for envelopes,+server-authorized actions, errors and rollout requirements.+## App-user session contractThis opt-in interface is implemented in the 1.3.0 source release. Existingpub.dev `1.2.3` and `v1.2.3` installs retain their earlier API. Source publicationthrough GitHub Actions does not create a pub.dev release or version tag.-VModal credentials authenticate a tenant principal. A and B can have identical+Direct VModal API keys authenticate a tenant principal. A and B can have identicaltenant IDs, API keys, and `auth.me()` responses while remaining different local-app users. The authenticated host resolves each stable `appUserId` and allowed-mapping; `auth.me()` does not supply them. Do not use app-user identity as+app users. For these direct-key sessions, the authenticated host resolves each+stable `appUserId` and allowed mapping; direct `auth.me()` does not supply them.+Backend-scoped `auth.me()` adds the signed app identity and grants, which the+connection must confirm against its envelope before activation. Do not use app-user identity as`SdkConfig.userId`, a direct-mode header, an API-key-derived cache name, or acollection typed by the user. No new environment variable represents the user.@@ -103,7 +134,9 @@ prefixing it. Both capture `streamName`, `mode`, an immutable `actions` set,and `collectionWide` (false by default). `session.scope(mapping)` matches therepresentation and all selectors, then uses the session's frozen permittedactions rather than a caller's replacement grants. Duplicate mappings are-rejected. Local actions are policy guardrails, not server-issued claims.+rejected. Host-selected direct-session actions are local policy guardrails.+Backend-session mappings come from VModal-issued grants confirmed by `auth.me()`;+the server checks those signed grants independently of the local mapping.| API | Required action / ownership || --- | --- |diff --git a/doc/sdk_doc.md b/doc/sdk_doc.mdindex 825b6e2..92c0a5c 100644--- a/doc/sdk_doc.md+++ b/doc/sdk_doc.md@@ -1,5 +1,10 @@# SDK guide+Begin with [Choose authentication](authentication.md). Direct runtime keys keep+the setup below; backend-scoped credentials use `VModal.connectWithBackend`+and its typed callback. [Backend authentication](backend_authentication.md)+describes strict envelopes, server grants, renewal and account transitions.+For account-based apps, start with [Component patterns](component_patterns.md):activate a verified app-user session, discover its allowed library, and injectthe resulting `UserScope` into a feature controller. The examples below use the@@ -59,7 +64,9 @@ change identity or content scope.usage, and direct resource access. `VModal.fromClient` accepts an existingfully configured client and transfers close ownership to the returned project.All ordinary operations are asynchronous. Gateway mode sends only-`Authorization: Bearer <key>` as caller identity.+`Authorization: Bearer <credential>` as caller identity. Scoped backend tokens+use the same header and data paths; they require the backend connection and+server capability described in the authentication guides.Resources are grouped under `auth`, `searches`, `collections`, `indexes`,`admin`, `r2`, and `images`. Request models preserve server snake_case duringdiff --git a/example/06_backend_auth/README.md b/example/06_backend_auth/README.mdnew file mode 100644index 0000000..4e242b8--- /dev/null+++ b/example/06_backend_auth/README.md@@ -0,0 +1,162 @@+# Developer-backend scoped authentication reference++This separate integration reference leaves `05_framebase_userlogin` unchanged.+That existing app demonstrates host login with shared-key local isolation. This+reference obtains a VModal-issued scoped token through your authenticated+developer backend and uses the same guarded SDK session operations.++It is a host integration library, not another login UI or deployable identity+provider. Prerequisites are a verified host identity/session, an existing policy+store, and a VModal deployment with registered scoped issuance and complete+resource enforcement. Use [Choose authentication](../../docs/authentication.md)+and [Backend authentication](../../docs/backend_authentication.md) alongside it.++## 1. Authenticate and connect++Add this SDK as a local development dependency or pin a verified immutable+published revision containing `connectWithBackend`. The reference `pubspec.yaml`+already points to the sibling SDK checkout.++```dart+final owner = BackendSessionOwner();+final connection = await owner.activate(+ appUserId: signedInUser.id,+ projectId: 'framebase',+ loadToken: () async {+ // Uses your CURRENT authenticated backend client; no master key in Flutter.+ final response = await developerApi.post('/vmodal/session', body: {});+ return parseBackendResponse(+ response.statusCode,+ response.decodedJson,+ retryAfter: response.safeRetryAfter,+ );+ },+);+```++`developerApi`, `signedInUser` and its response adapter belong to your host app.+Map network/timeouts to `BackendAuthFailure.unavailable`. JSON decoding or a+malformed envelope is `invalidResponse`; never include raw response bodies or+identity tokens in errors. `parseBackendResponse` demonstrates safe status+classification, including identity rejection, policy denial and throttling.++The SDK confirms the candidate through VModal auth/me before returning ready.+The owner fences activation results when login changes during acquisition.++## 2. Discover allowed content, then search++```dart+final collections = await connection.session.listCollections();+final library = connection.scope('my_library');+final info = await library.collectionInfo();+final results = await library.search('a cyclist entering the street');+if (results.assets.isNotEmpty) {+ final bytes = await library.imageBytes(results.assets.first);+}+```++The grant label resolves the backend's exact collection/stream/mode mapping;+Flutter constructs no collection name. Index discovery requires `indexation`+and is unavailable until the deployment enforces and enables that action.+The initial read-only scoped deployment does not offer upload, metadata,+indexation or delete. Those existing SDK APIs remain usable in direct auth.++## 3. Implement the developer backend handoff++[developer_backend/session.mjs](developer_backend/session.mjs) exports a small+`node:http` handler. Node 22+ provides the built-in fetch, AbortSignal and native+test APIs it uses. It has no npm dependencies. Translate its handoff into your+existing server stack if your application uses another language.++Mount it in your existing backend:++```js+import { createVmodalSessionHandler, IdentityRejected, AccessDenied }+ from './developer_backend/session.mjs';++const sessionHandler = createVmodalSessionHandler({+ projectId: serverConfig.vmodalProject,+ vmodalOrigin: serverConfig.vmodalOrigin,+ loadServerKey: async ({ signal }) => secrets.currentRegisteredVmodalKey({ signal }),+ verifyIdentity: async (req, { signal }) => {+ const session = await hostAuth.verifyCurrentRequest(req, { signal });+ if (!session) throw new IdentityRejected();+ return { subject: session.stableSubject };+ },+ resolvePolicy: async (subject, { signal }) => {+ const policy = await policies.forVerifiedSubject(subject, { signal });+ if (!policy?.enabled) throw new AccessDenied();+ return { enabled: true, revision: policy.revision, grants: policy.exactGrants };+ },+});+// Route POST /vmodal/session to sessionHandler(req, res) in your server.+```++The named configuration, auth, policy and secret objects are mandatory host+adapters. No built-in verifier accepts a phone-supplied user ID. A cookie-based+host can verify cookies instead of Bearer identity tokens. Do not validate+identity by decoding an unsigned JWT or comparing an unverified UID.++The handler accepts only `{}`; the host determines subject, project and grants.+It re-verifies identity and reloads policy for every renewal. Only the registered+server credential goes to `/api/v1/auth/scoped-token`. Issuer redirects are+rejected so that credential does not follow another origin. The host identity+credential is never forwarded to VModal.++Successful envelopes pass through unchanged after expected identity/project/+policy checks. Responses are not cacheable. Identity rejection is `401`, access+denial is `403`, issuer contract/configuration rejection is `502`, temporary+issuer failure is `503`, and throttling is `429` with bounded `Retry-After`.+Errors never relay issuer bodies or server secrets. Acquisition is bounded by a+single timeout, including response decoding, and adapters receive its cancellation+signal. The Dart adapter recognizes the safe `issuer_contract_rejected` code+on `502` as `invalidResponse`; other unclassified gateway `5xx` responses are+temporary `unavailable` errors.++This handler requires server configuration/secret injection; it creates no new+Flutter environment variables and no server process or deployment. Your backend+retains its own configuration conventions and login/session lifecycle.++## 4. Renewal, transition and cleanup++The SDK coalesces renewal and performs request-time expiry gating. A temporary+issuer outage preserves host login and may retain a still-valid scoped token.+Failed POST searches are surfaced, and writes are not automatically replayed.++At the start of account switch/logout, clear host UI and call:++```dart+await owner.close(); // immediately retires VModal state; host owns sign-out+await hostAuth.signOut();+```++For another verified account, call `activate` again. Changed policy/grants also+require fresh activation. Widgets retain a session-owned `UserScope` and must+discard it on invalidation. Feature pages do not close a connection shared by+other pages. Already issued signed URLs and remote jobs retain their separate+lifetime; local close does not promise distributed instant revocation.++## 5. Run offline reference checks++From the SDK root:++```bash+# The normal build gates include this reference's Dart pub_get/format/analyze/test.+# The backend handler has an optional separate Node gate (no npm dependencies).+node --test example/06_backend_auth/developer_backend/session_test.mjs+flutter_bin="$(bash install.sh flutter_bin)"+cd example/06_backend_auth+"$flutter_bin" pub get+"$flutter_bin" analyze+"$flutter_bin" test+```++Backend tests exercise verified identity, spoof attempts, denied policy, unchanged+envelopes, no master-key return, safe issuer errors, renewal re-verification and+timeout, malformed issuer JSON and response-decoding timeout. Dart checks cover callback error classification; the SDK's+`test/backend_auth_test.dart` covers credential/session behavior.++Expected result: all offline checks pass without a live key or identity provider.+Tests create temporary local HTTP listeners and close them after each case.+No scoped production availability is inferred from fake issuers. Before enabling+your integration, run the public-edge acceptance checks in the backend guide.diff --git a/example/06_backend_auth/developer_backend/session.mjs b/example/06_backend_auth/developer_backend/session.mjsnew file mode 100644index 0000000..4177c77--- /dev/null+++ b/example/06_backend_auth/developer_backend/session.mjs@@ -0,0 +1,187 @@+/**+ * Developer-owned POST /vmodal/session reference.+ * Inject the host's real identity verifier, policy resolver and server-key loader.+ * No identity provider, user directory or signing secret belongs in the SDK.+ */+export class IdentityRejected extends Error {}+export class AccessDenied extends Error {}++const envelopeFields = new Set([+ 'version', 'auth_mode', 'access_token', 'token_type', 'expires_in',+ 'issued_at', 'expires_at', 'principal_id', 'tenant_id', 'project_id',+ 'app_user_id', 'policy_revision', 'delegation_revision', 'grants',+]);+const grantFields = ['actions', 'collection_id', 'collection_wide', 'grant_id', 'mode', 'stream_name'];++function reply(res, status, code, extra = {}) {+ res.writeHead(status, {+ 'content-type': 'application/json',+ 'cache-control': 'no-store',+ pragma: 'no-cache',+ ...extra,+ });+ res.end(JSON.stringify({ detail: code, code }));+}++async function emptyBody(req) {+ let bytes = 0;+ const chunks = [];+ for await (const chunk of req) {+ bytes += chunk.length;+ if (bytes > 4096) throw new AccessDenied();+ chunks.push(chunk);+ }+ const text = Buffer.concat(chunks).toString('utf8');+ // This route deliberately accepts no mobile-selected user, project or grants.+ if (!/^\s*\{\s*\}\s*$/.test(text)) throw new AccessDenied();+}++async function issuerJson(response) {+ if (!response.body) throw new Error('invalid issuer response');+ const chunks = [];+ let bytes = 0;+ for await (const chunk of response.body) {+ bytes += chunk.length;+ if (bytes > 65536) throw new Error('issuer response too large');+ chunks.push(Buffer.from(chunk));+ }+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));+}++function checkEnvelope(data, identity, policy, projectId, serverKey) {+ if (!data || typeof data !== 'object' || Array.isArray(data) ||+ Object.keys(data).some(key => !envelopeFields.has(key)) ||+ Object.keys(data).length !== envelopeFields.size ||+ data.version !== 1 || data.auth_mode !== 'developer_backend' ||+ data.token_type !== 'Bearer' || data.project_id !== projectId ||+ data.app_user_id !== identity.subject ||+ data.policy_revision !== policy.revision ||+ typeof data.access_token !== 'string' ||+ data.access_token.length > 8192 ||+ !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(data.access_token) ||+ data.access_token === serverKey ||+ !Array.isArray(data.grants) || data.grants.length === 0 || data.grants.length > 16 ||+ !Number.isInteger(data.expires_in) || data.expires_in < 60 || data.expires_in > 900 ||+ !Number.isInteger(data.delegation_revision) || data.delegation_revision < 1 ||+ typeof data.issued_at !== 'string' || typeof data.expires_at !== 'string' ||+ !data.issued_at.endsWith('Z') || !data.expires_at.endsWith('Z') ||+ !Number.isFinite(Date.parse(data.issued_at)) ||+ Date.parse(data.expires_at) - Date.parse(data.issued_at) !== data.expires_in * 1000 ||+ Date.parse(data.expires_at) <= Date.now() ||+ ['principal_id', 'tenant_id'].some(key => typeof data[key] !== 'string' || !data[key]) ||+ data.grants.some(grant => !grant ||+ Object.keys(grant).sort().join(',') !== grantFields.join(',') ||+ typeof grant.grant_id !== 'string' || !grant.grant_id ||+ typeof grant.collection_wide !== 'boolean' ||+ ['collection_id', 'stream_name', 'mode'].some(key =>+ typeof grant[key] !== 'string' || !/^[A-Za-z0-9_]{1,80}$/.test(grant[key])) ||+ !Array.isArray(grant.actions) || !grant.actions.length ||+ new Set(grant.actions).size !== grant.actions.length ||+ grant.actions.some(action => !['discover', 'search', 'media'].includes(action)))) {+ throw new Error('invalid issuer contract');+ }+ const byId = grants => grants.map(grant => JSON.stringify([+ grant.grant_id, grant.collection_id, grant.stream_name, grant.mode,+ [...grant.actions].sort(), grant.collection_wide,+ ])).sort();+ if (JSON.stringify(byId(data.grants)) !== JSON.stringify(byId(policy.grants))) {+ throw new Error('invalid issuer grants');+ }+}++/**+ * Returns a node:http handler to mount in an existing authenticated backend.+ * verifyIdentity(req, {signal}) must verify the CURRENT host credential and+ * return {subject}; resolvePolicy(subject, {signal}) returns server-owned+ * {enabled, revision, grants}. Adapters throw IdentityRejected/AccessDenied.+ * loadServerKey({signal}) retrieves a registered ak_ credential server-side.+ */+export function createVmodalSessionHandler({+ verifyIdentity, resolvePolicy, loadServerKey, projectId, vmodalOrigin,+ fetchImpl = fetch, timeoutMs = 10000, expiresIn = 300,+}) {+ for (const fn of [verifyIdentity, resolvePolicy, loadServerKey, fetchImpl]) {+ if (typeof fn !== 'function') throw new TypeError('adapter required');+ }+ const origin = new URL(vmodalOrigin);+ if (!['http:', 'https:'].includes(origin.protocol) || origin.username ||+ origin.password || origin.search || origin.hash || origin.pathname !== '/' ||+ typeof projectId !== 'string' || !projectId ||+ !Number.isInteger(timeoutMs) || timeoutMs < 1 ||+ !Number.isInteger(expiresIn) || expiresIn < 60 || expiresIn > 900) {+ throw new TypeError('invalid backend configuration');+ }+ const issuer = new URL('/api/v1/auth/scoped-token', origin);+ return async (req, res) => {+ if (req.url !== '/vmodal/session') return reply(res, 404, 'not_found');+ if (req.method !== 'POST') return reply(res, 405, 'method_not_allowed', { allow: 'POST' });+ const signal = AbortSignal.timeout(timeoutMs);+ let status = 503;+ let code = 'issuer_unavailable';+ let retryAfter;+ const work = async () => {+ await emptyBody(req);+ const identity = await verifyIdentity(req, { signal });+ if (!identity || typeof identity.subject !== 'string' || !identity.subject) {+ throw new IdentityRejected();+ }+ const policy = await resolvePolicy(identity.subject, { signal });+ if (!policy?.enabled || typeof policy.revision !== 'string' ||+ !policy.revision || !Array.isArray(policy.grants) || !policy.grants.length) {+ throw new AccessDenied();+ }+ signal.throwIfAborted();+ const serverKey = await loadServerKey({ signal });+ if (typeof serverKey !== 'string' || !serverKey.startsWith('ak_')) {+ throw new Error('server credential unavailable');+ }+ signal.throwIfAborted();+ const response = await fetchImpl(issuer, {+ method: 'POST', redirect: 'error', signal,+ headers: { authorization: `Bearer ${serverKey}`, 'content-type': 'application/json' },+ body: JSON.stringify({+ version: 1, project_id: projectId, app_user_id: identity.subject,+ policy_revision: policy.revision, expires_in: expiresIn, grants: policy.grants,+ }),+ });+ if (!response.ok) {+ if (response.status === 429) {+ status = 429;+ code = 'rate_limited';+ const value = response.headers.get('retry-after');+ if (/^\d{1,4}$/.test(value ?? '')) retryAfter = String(Math.min(900, Number(value)));+ } else if (response.status >= 400 && response.status < 500) {+ status = 502;+ code = 'issuer_contract_rejected';+ }+ // Issuer failure details may contain operational data: never relay them.+ throw new Error('issuer rejected');+ }+ status = 502;+ code = 'issuer_contract_rejected';+ const data = await issuerJson(response);+ checkEnvelope(data, identity, policy, projectId, serverKey);+ signal.throwIfAborted();+ return data;+ };+ let cancel;+ const aborted = new Promise((_, reject) => {+ cancel = () => reject(signal.reason);+ signal.addEventListener('abort', cancel, { once: true });+ });+ try {+ const data = await Promise.race([work(), aborted]);+ res.writeHead(200, {+ 'content-type': 'application/json', 'cache-control': 'no-store', pragma: 'no-cache',+ });+ res.end(JSON.stringify(data));+ } catch (error) {+ if (signal.aborted) { status = 503; code = 'issuer_unavailable'; }+ if (error instanceof IdentityRejected) { status = 401; code = 'identity_rejected'; }+ if (error instanceof AccessDenied) { status = 403; code = 'access_denied'; }+ reply(res, status, code, retryAfter ? { 'retry-after': retryAfter } : {});+ } finally {+ signal.removeEventListener('abort', cancel);+ }+ };+}diff --git a/example/06_backend_auth/developer_backend/session_test.mjs b/example/06_backend_auth/developer_backend/session_test.mjsnew file mode 100644index 0000000..80b1c7b--- /dev/null+++ b/example/06_backend_auth/developer_backend/session_test.mjs@@ -0,0 +1,138 @@+import assert from 'node:assert/strict';+import { createServer } from 'node:http';+import { test } from 'node:test';+import { AccessDenied, IdentityRejected, createVmodalSessionHandler } from './session.mjs';++const grant = {+ grant_id: 'my_library', collection_id: 'library_a7f9', stream_name: 'street_study',+ mode: 'vid_file', actions: ['discover', 'search', 'media'], collection_wide: false,+};+function envelope() {+ const now = Math.floor(Date.now() / 1000) * 1000;+ return {+ version: 1, auth_mode: 'developer_backend', access_token: 'header.payload.signature',+ token_type: 'Bearer', expires_in: 300, issued_at: new Date(now).toISOString(),+ expires_at: new Date(now + 300000).toISOString(), principal_id: 'owner', tenant_id: 'tenant',+ project_id: 'demo', app_user_id: 'verified_user', policy_revision: 'policy_1',+ delegation_revision: 1, grants: [grant],+ };+}++async function request(overrides = {}, { body = '{}', method = 'POST' } = {}) {+ let call;+ const handler = createVmodalSessionHandler({+ projectId: 'demo', vmodalOrigin: 'https://users.example.com', timeoutMs: 1000,+ verifyIdentity: async req => {+ assert.equal(req.headers.authorization, 'Bearer host_session');+ return { subject: 'verified_user' };+ },+ resolvePolicy: async () => ({ enabled: true, revision: 'policy_1', grants: [grant] }),+ loadServerKey: async () => 'ak_registered_server_fixture',+ fetchImpl: async (url, init) => {+ call = { url: String(url), ...init, body: JSON.parse(init.body) };+ return Response.json(envelope());+ },+ ...overrides,+ });+ const server = createServer(handler);+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ try {+ const response = await fetch(`http://127.0.0.1:${server.address().port}/vmodal/session`, {+ method, headers: { authorization: 'Bearer host_session' }, body,+ });+ return { status: response.status, headers: response.headers, data: await response.json(), call };+ } finally {+ await new Promise(resolve => server.close(resolve));+ }+}++test('verified host subject and server policy issue unchanged scoped envelope', async () => {+ const result = await request();+ assert.equal(result.status, 200);+ assert.equal(result.data.app_user_id, 'verified_user');+ assert.deepEqual(result.data.grants, [grant]);+ assert.equal(result.headers.get('cache-control'), 'no-store');+ assert.equal(result.call.headers.authorization, 'Bearer ak_registered_server_fixture');+ assert.equal(result.call.url, 'https://users.example.com/api/v1/auth/scoped-token');+ assert.equal(result.call.redirect, 'error');+ assert.equal(result.call.body.app_user_id, 'verified_user');+ assert.ok(!JSON.stringify(result.call.body).includes('host_session'));+ assert.ok(!JSON.stringify(result.data).includes('ak_registered_server_fixture'));+});++test('identity rejection and access denial stop before server issuance', async () => {+ for (const [field, error, status] of [+ ['verifyIdentity', new IdentityRejected('secret host diagnostic'), 401],+ ['resolvePolicy', new AccessDenied('secret policy diagnostic'), 403],+ ]) {+ const result = await request({ [field]: async () => { throw error; } });+ assert.equal(result.status, status);+ assert.equal(result.call, undefined);+ assert.ok(!JSON.stringify(result.data).includes('secret'));+ }+});++test('mobile cannot choose identity, project or grants and method is fixed', async () => {+ const result = await request({}, { body: '{"app_user_id":"other"}' });+ assert.equal(result.status, 403);+ assert.equal(result.call, undefined);+ assert.equal((await request({}, { method: 'PUT' })).status, 405);+});++test('issuer errors are classified and never expose issuer secrets', async () => {+ for (const [upstream, status] of [[401, 502], [403, 502], [422, 502], [500, 503], [429, 429]]) {+ const result = await request({ fetchImpl: async () => new Response('secret issuer diagnostics', {+ status: upstream, headers: { 'retry-after': '19' },+ }) });+ assert.equal(result.status, status);+ assert.ok(!JSON.stringify(result.data).includes('secret'));+ if (status === 429) assert.equal(result.headers.get('retry-after'), '19');+ }+});++test('incorrect identity, grants, token family or extra secret fails contract', async () => {+ for (const change of [+ { app_user_id: 'other' }, { access_token: 'ak_master_key' },+ { grants: [{ ...grant, collection_id: 'other' }] }, { secret: 'unexpected' },+ { grants: [{ ...grant, server_secret: 'secret' }] },+ { expires_at: '2020-01-01T00:00:00Z' },+ ]) {+ const result = await request({ fetchImpl: async () => Response.json({ ...envelope(), ...change }) });+ assert.equal(result.status, 502);+ assert.equal(result.data.code, 'issuer_contract_rejected');+ }+});++test('each renewal re-verifies host identity and resolves policy', async () => {+ let identities = 0;+ let policies = 0;+ const adapters = {+ verifyIdentity: async () => { identities++; return { subject: 'verified_user' }; },+ resolvePolicy: async () => { policies++; return { enabled: true, revision: 'policy_1', grants: [grant] }; },+ };+ assert.equal((await request(adapters)).status, 200);+ assert.equal((await request(adapters)).status, 200);+ assert.equal(identities, 2);+ assert.equal(policies, 2);+});++test('malformed successful issuer output is a contract failure', async () => {+ const result = await request({ fetchImpl: async () => new Response('invalid JSON') });+ assert.equal(result.status, 502);+ assert.equal(result.data.code, 'issuer_contract_rejected');+});++test('issuer response decoding is covered by the acquisition timeout', async () => {+ const result = await request({+ timeoutMs: 20,+ fetchImpl: async () => new Response(new ReadableStream({ start() {} })),+ });+ assert.equal(result.status, 503);+ assert.equal(result.data.code, 'issuer_unavailable');+});++test('unresponsive host adapter reaches bounded timeout without issuance', async () => {+ const result = await request({ timeoutMs: 20, verifyIdentity: () => new Promise(() => {}) });+ assert.equal(result.status, 503);+ assert.equal(result.call, undefined);+});diff --git a/example/06_backend_auth/lib/backend_auth_example.dart b/example/06_backend_auth/lib/backend_auth_example.dartnew file mode 100644index 0000000..e5c3548--- /dev/null+++ b/example/06_backend_auth/lib/backend_auth_example.dart@@ -0,0 +1,74 @@+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++/// Host HTTP adapters pass only safe status/Retry-After data into SDK errors.+ScopedTokenEnvelope parseBackendResponse(+ int status,+ Map<String, Object?>? json, {+ Duration? retryAfter,+}) {+ if (status == 401) {+ throw const BackendAuthException(BackendAuthFailure.identityRejected);+ }+ if (status == 403) {+ throw const BackendAuthException(BackendAuthFailure.accessDenied);+ }+ if (status == 502 && json?['code'] == 'issuer_contract_rejected') {+ throw const BackendAuthException(BackendAuthFailure.invalidResponse);+ }+ if (status == 429 || status >= 500) {+ throw BackendAuthException(+ BackendAuthFailure.unavailable,+ retryAfter: retryAfter,+ );+ }+ if (status != 200 || json == null) {+ throw const BackendAuthException(BackendAuthFailure.invalidResponse);+ }+ return ScopedTokenEnvelope.fromJson(json);+}++/// One owner at the host account lifetime; feature pages retain only UserScope.+/// The host clears widgets/players/caches when initiating a transition.+final class BackendSessionOwner {+ BackendConnection? _connection;+ int _generation = 0;++ BackendConnection? get current => _connection;++ Future<BackendConnection> activate({+ required String appUserId,+ required String projectId,+ required Future<ScopedTokenEnvelope> Function() loadToken,+ Uri? baseUri,+ }) async {+ final ticket = ++_generation;+ final old = _connection;+ _connection = null;+ await old?.close();+ if (ticket != _generation) throw const SessionInvalidated();+ final next = await VModal.connectWithBackend(+ expectedAppUserId: appUserId,+ expectedProjectId: projectId,+ baseUri: baseUri,+ loadToken: () async {+ if (ticket != _generation) throw const SessionInvalidated();+ final token = await loadToken();+ if (ticket != _generation) throw const SessionInvalidated();+ return token;+ },+ );+ if (ticket != _generation) {+ await next.close();+ throw const SessionInvalidated();+ }+ _connection = next;+ return next;+ }++ Future<void> close() {+ _generation++;+ final old = _connection;+ _connection = null;+ return old?.close() ?? Future<void>.value();+ }+}diff --git a/example/06_backend_auth/pubspec.yaml b/example/06_backend_auth/pubspec.yamlnew file mode 100644index 0000000..a12943a--- /dev/null+++ b/example/06_backend_auth/pubspec.yaml@@ -0,0 +1,13 @@+name: vmodal_backend_auth_example+description: Host-owned scoped VModal authentication integration reference.+publish_to: none+environment:+ sdk: '>=3.12.0 <4.0.0'+dependencies:+ vmodal_sdk_flutter:+ path: ../..+dev_dependencies:+ flutter_test:+ sdk: flutter+flutter:+ uses-material-design: truediff --git a/example/06_backend_auth/test/backend_auth_example_test.dart b/example/06_backend_auth/test/backend_auth_example_test.dartnew file mode 100644index 0000000..800822c--- /dev/null+++ b/example/06_backend_auth/test/backend_auth_example_test.dart@@ -0,0 +1,128 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_backend_auth_example/backend_auth_example.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++void main() {+ test('host HTTP classifications preserve identity and temporary failure', () {+ for (final entry in <int, BackendAuthFailure>{+ 401: BackendAuthFailure.identityRejected,+ 403: BackendAuthFailure.accessDenied,+ 429: BackendAuthFailure.unavailable,+ 503: BackendAuthFailure.unavailable,+ 422: BackendAuthFailure.invalidResponse,+ 200: BackendAuthFailure.invalidResponse,+ }.entries) {+ expect(+ () => parseBackendResponse(entry.key, null),+ throwsA(+ isA<BackendAuthException>().having(+ (error) => error.failure,+ 'classified host failure',+ entry.value,+ ),+ ),+ );+ }+ });++ test('temporary throttle retains safe bounded retry information', () {+ expect(+ () => parseBackendResponse(+ 429,+ null,+ retryAfter: const Duration(seconds: 2),+ ),+ throwsA(+ isA<BackendAuthException>().having(+ (error) => error.retryAfter,+ 'retry-after',+ const Duration(seconds: 2),+ ),+ ),+ );+ });++ test('reference issuer contract rejection is not a temporary outage', () {+ expect(+ () => parseBackendResponse(502, {'code': 'issuer_contract_rejected'}),+ throwsA(+ isA<BackendAuthException>().having(+ (error) => error.failure,+ 'issuer contract rejection',+ BackendAuthFailure.invalidResponse,+ ),+ ),+ );+ expect(+ () => parseBackendResponse(502, null),+ throwsA(+ isA<BackendAuthException>().having(+ (error) => error.failure,+ 'unclassified gateway outage',+ BackendAuthFailure.unavailable,+ ),+ ),+ );+ });++ test('owner close is repeatable and retains no active connection', () async {+ final owner = BackendSessionOwner();+ await owner.close();+ await owner.close();+ expect(owner.current, isNull);+ });++ test(+ 'host logout fences a callback still acquiring initial authorization',+ () async {+ final owner = BackendSessionOwner();+ final started = Completer<void>();+ final token = Completer<ScopedTokenEnvelope>();+ final opening = owner.activate(+ appUserId: 'app_user',+ projectId: 'project',+ loadToken: () {+ if (!started.isCompleted) started.complete();+ return token.future;+ },+ );+ final denied = expectLater(opening, throwsA(isA<SessionInvalidated>()));+ await started.future;+ await owner.close();+ final issued = DateTime.now().toUtc();+ token.complete(+ ScopedTokenEnvelope.fromJson({+ 'version': 1,+ 'auth_mode': 'developer_backend',+ 'access_token': 'header.payload.signature',+ 'token_type': 'Bearer',+ 'expires_in': 300,+ 'issued_at': issued.toIso8601String(),+ 'expires_at': issued+ .add(const Duration(seconds: 300))+ .toIso8601String(),+ 'principal_id': 'principal',+ 'tenant_id': 'tenant',+ 'project_id': 'project',+ 'app_user_id': 'app_user',+ 'policy_revision': 'policy',+ 'delegation_revision': 1,+ 'grants': [+ {+ 'grant_id': 'library',+ 'collection_id': 'library',+ 'stream_name': 'stream',+ 'mode': 'vid_file',+ 'actions': ['search'],+ 'collection_wide': false,+ },+ ],+ }),+ );+ await denied;+ expect(owner.current, isNull);+ },+ );+}diff --git a/lib/src/api_key_provider.dart b/lib/src/api_key_provider.dartindex 125eebf..7657b91 100644--- a/lib/src/api_key_provider.dart+++ b/lib/src/api_key_provider.dart@@ -12,6 +12,24 @@ abstract interface class ApiKeyProvider {String current();}+/// @nodoc+abstract interface class AsyncCredentialProvider implements ApiKeyProvider {+ int get revision;+ Future<void> ensureReady();+ bool isRevisionUsable(int revision);+ void reject(int revision);+ Future<void> recover(int failedRevision);+}++/// @nodoc+abstract interface class SessionCredentialSource {+ String get serviceNamespace;+ String get tenantId;+ String get expectedPrincipal;+ String? get projectId;+ MutableApiKeyProvider createProvider({required bool Function() isActive});+}+/// In-memory credential provider supporting rotation and explicit clearing.////// [close] permanently disables the provider. Values are redacted from@@ -97,7 +115,7 @@ class TenantCredentialSnapshot {/// external install fences older results using both ticket and base revision./// No key is persisted, and failures block calls unless the host explicitly/// permits retaining the previous credential under its validity policy.-class TenantCredentialSource {+class TenantCredentialSource implements SessionCredentialSource {TenantCredentialSource({required this.serviceNamespace,required this.tenantId,@@ -127,9 +145,14 @@ class TenantCredentialSource {);}+ @overridefinal String serviceNamespace;+ @overridefinal String tenantId;+ @overridefinal String expectedPrincipal;+ @override+ String? get projectId => null;final Future<TenantCredential> Function()? renew;final bool retainOnRenewalFailure;late TenantCredentialSnapshot _snapshot;@@ -151,6 +174,7 @@ class TenantCredentialSource {}/// Attaches and reads the latest committed revision without an await gap.+ @overrideTenantSessionApiKeyProvider createProvider({required bool Function() isActive,}) {diff --git a/lib/src/backend_auth.dart b/lib/src/backend_auth.dartnew file mode 100644index 0000000..b7c1854--- /dev/null+++ b/lib/src/backend_auth.dart@@ -0,0 +1,717 @@+import 'dart:async';+import 'dart:convert';++import 'api_key_provider.dart';+import 'config.dart';+import 'errors.dart';+import 'http.dart';+import 'transport.dart';+import 'upload.dart';+import 'user_session.dart';++/// Observable VModal connection lifecycle; host login remains host-owned.+enum BackendConnectionState {+ ready,+ refreshing,+ unavailable,+ expired,+ invalidated,+ closed,+}++/// Immutable exact resource grant returned by the VModal issuer.+final class ScopedGrant {+ ScopedGrant._(+ this.grantId,+ this.collectionId,+ this.streamName,+ this.mode,+ Set<UserAction> actions,+ this.collectionWide,+ ) : actions = Set<UserAction>.unmodifiable(actions);++ factory ScopedGrant.fromJson(Map<String, Object?> json) {+ _fields(json, const {+ 'grant_id',+ 'collection_id',+ 'stream_name',+ 'mode',+ 'actions',+ 'collection_wide',+ });+ final values = json['actions'];+ if (values is! List || values.isEmpty) _invalid();+ final actions = <UserAction>{};+ for (final value in values) {+ if (value is! String) _invalid();+ final matches = UserAction.values.where((a) => a.name == value);+ if (matches.isEmpty || !actions.add(matches.single)) _invalid();+ }+ if (json['collection_wide'] is! bool) _invalid();+ return ScopedGrant._(+ _identifier(json, 'grant_id', 128),+ _selector(json, 'collection_id'),+ _selector(json, 'stream_name'),+ _selector(json, 'mode'),+ actions,+ json['collection_wide']! as bool,+ );+ }++ final String grantId, collectionId, streamName, mode;+ final Set<UserAction> actions;+ final bool collectionWide;+ ContentMapping get mapping => ContentMapping.opaque(+ collectionId: collectionId,+ streamName: streamName,+ mode: mode,+ actions: actions,+ collectionWide: collectionWide,+ );++ Map<String, Object?> toJson() => {+ 'grant_id': grantId,+ 'collection_id': collectionId,+ 'stream_name': streamName,+ 'mode': mode,+ 'actions': actions.map((a) => a.name).toList()..sort(),+ 'collection_wide': collectionWide,+ };++ @override+ String toString() => 'ScopedGrant(actions=${actions.length})';+}++/// Strict version-1 server envelope. The bearer stays in memory.+final class ScopedTokenEnvelope {+ ScopedTokenEnvelope._({+ required this.accessToken,+ required this.expiresIn,+ required this.issuedAt,+ required this.expiresAt,+ required this.principalId,+ required this.tenantId,+ required this.projectId,+ required this.appUserId,+ required this.policyRevision,+ required this.delegationRevision,+ required List<ScopedGrant> grants,+ }) : grants = List<ScopedGrant>.unmodifiable(grants);++ factory ScopedTokenEnvelope.fromJson(Map<String, Object?> json) {+ _fields(json, const {+ 'version',+ 'auth_mode',+ 'access_token',+ 'token_type',+ 'expires_in',+ 'issued_at',+ 'expires_at',+ 'principal_id',+ 'tenant_id',+ 'project_id',+ 'app_user_id',+ 'policy_revision',+ 'delegation_revision',+ 'grants',+ });+ if (json['version'] is! int ||+ json['version'] != 1 ||+ json['auth_mode'] != 'developer_backend' ||+ json['token_type'] != 'Bearer') {+ _invalid();+ }+ final lifetime = json['expires_in'];+ final revision = json['delegation_revision'];+ if (lifetime is! int ||+ lifetime < 60 ||+ lifetime > 900 ||+ revision is! int ||+ revision < 1) {+ _invalid();+ }+ final issued = _time(json, 'issued_at');+ final expires = _time(json, 'expires_at');+ if (expires.difference(issued) != Duration(seconds: lifetime)) _invalid();+ final token = json['access_token'];+ if (token is! String || token.trim() != token) _invalid();+ strApiKey(token);+ if (!RegExp(+ r'^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$',+ ).hasMatch(token)) {+ _invalid();+ }+ return ScopedTokenEnvelope._(+ accessToken: token,+ expiresIn: lifetime,+ issuedAt: issued,+ expiresAt: expires,+ principalId: _identifier(json, 'principal_id', 256),+ tenantId: _identifier(json, 'tenant_id', 256),+ projectId: _identifier(json, 'project_id', 256),+ appUserId: _identifier(json, 'app_user_id', 256),+ policyRevision: _identifier(json, 'policy_revision', 128),+ delegationRevision: revision,+ grants: _grants(json['grants']),+ );+ }++ int get version => 1;+ String get authMode => 'developer_backend';+ String get tokenType => 'Bearer';+ final String accessToken,+ principalId,+ tenantId,+ projectId,+ appUserId,+ policyRevision;+ final int expiresIn, delegationRevision;+ final DateTime issuedAt, expiresAt;+ final List<ScopedGrant> grants;++ String get _binding =>+ jsonEncode([principalId, tenantId, projectId, appUserId]);+ String get _policy =>+ jsonEncode([policyRevision, delegationRevision, _grantPolicy(grants)]);+ @override+ String toString() =>+ 'ScopedTokenEnvelope(version=1, grants=${grants.length}, [REDACTED])';+}++/// Thin owner of a guarded user session and its scoped credential lifecycle.+final class BackendConnection {+ BackendConnection._(this._source, this._manager);+ final _ScopedCredentialSource _source;+ final UserSessionManager _manager;+ Future<void>? _closing;++ UserSession get session {+ _source._check();+ final value = _manager.current;+ if (value == null) throw const SessionInvalidated();+ return value;+ }++ BackendConnectionState get state {+ if (_source.state == BackendConnectionState.ready &&+ _source._envelope != null &&+ !_source.clock().isBefore(_source._envelope!.expiresAt)) {+ _source._emit(BackendConnectionState.expired);+ }+ return _source.state;+ }++ Stream<BackendConnectionState> get states => _source.states.stream;+ UserScope scope(String grantId) {+ final active = session;+ final grants = _source.envelope.grants.where((g) => g.grantId == grantId);+ if (grants.isEmpty) throw const ValidationException('Unknown grant ID');+ return active.scope(grants.single.mapping);+ }++ Future<void> refresh() => _source.refresh();+ Future<void> close() {+ if (_closing != null) return _closing!;+ final done = Completer<void>();+ _closing = done.future;+ // Retire guards before publishing closed to reentrant stream listeners.+ final cleanup = _manager.close();+ _source.close();+ unawaited(cleanup.then(done.complete, onError: done.completeError));+ return done.future;+ }++ /// @nodoc+ static Future<BackendConnection> connect({+ required String expectedAppUserId,+ required String expectedProjectId,+ required Future<ScopedTokenEnvelope> Function() loadToken,+ Uri? baseUri,+ Duration timeout = const Duration(seconds: 30),+ int maxRetries = 1,+ Duration refreshLeeway = const Duration(seconds: 60),+ ScopedTokenEnvelope? initialToken,+ DateTime Function()? clock,+ DelayStrategy? delay,+ VmodalTransport Function(SdkConfig)? transportFactory,+ SignedUploadTransport Function(SdkConfig)? signedUploadTransportFactory,+ }) async {+ if (expectedAppUserId.isEmpty ||+ expectedProjectId.isEmpty ||+ refreshLeeway.isNegative) {+ _invalid();+ }+ final config = SdkConfig(+ baseUrl: baseUri?.toString(),+ timeout: timeout,+ maxRetries: maxRetries,+ );+ final source = _ScopedCredentialSource(+ config,+ expectedAppUserId,+ expectedProjectId,+ loadToken,+ refreshLeeway,+ clock ?? DateTime.now,+ delay ?? Future<void>.delayed,+ transportFactory ?? HttpVmodalTransport.new,+ );+ UserSessionManager? manager;+ try {+ await source.refresh(initialToken: initialToken);+ manager = UserSessionManager(+ config: config,+ credentialSource: source,+ transportFactory: transportFactory,+ signedUploadTransportFactory: signedUploadTransportFactory,+ );+ source.onInvalidated = () {+ unawaited(manager!.logout());+ };+ final envelope = source.envelope;+ await manager.openUserSession(+ tenantId: envelope.tenantId,+ appUserId: envelope.appUserId,+ allowedContentMapping: envelope.grants.map((g) => g.mapping),+ policyRevision: envelope.policyRevision,+ );+ return BackendConnection._(source, manager);+ } on Object {+ source.close();+ await manager?.close();+ rethrow;+ }+ }+}++class _ScopedCredentialSource implements SessionCredentialSource {+ _ScopedCredentialSource(+ this.config,+ this.expectedAppUserId,+ this.expectedProjectId,+ this.loadToken,+ this.leeway,+ this.clock,+ this.delay,+ this.transportFactory,+ );+ final SdkConfig config;+ final String expectedAppUserId, expectedProjectId;+ final Future<ScopedTokenEnvelope> Function() loadToken;+ final Duration leeway;+ final DateTime Function() clock;+ final DelayStrategy delay;+ final VmodalTransport Function(SdkConfig) transportFactory;+ final states = StreamController<BackendConnectionState>.broadcast();+ BackendConnectionState state = BackendConnectionState.refreshing;+ ScopedTokenEnvelope? _envelope;+ ScopedTokenEnvelope get envelope {+ _check();+ return _envelope!;+ }++ int revision = 0, _generation = 0;+ int? _rejectedRevision;+ final Map<int, DateTime> _expiries = {};+ final Set<int> _rejections = {};+ Future<void>? _pending;+ final CancellationToken _lifetime = CancellationToken();+ void Function()? onInvalidated;+ final Set<_ScopedProvider> _providers = {};+ @override+ String get serviceNamespace => SessionContext.serviceNamespaceFor(config);+ @override+ String get tenantId => envelope.tenantId;+ @override+ String get expectedPrincipal => envelope.principalId;+ @override+ String? get projectId => expectedProjectId;+ bool get usable =>+ _envelope != null &&+ clock().isBefore(_envelope!.expiresAt) &&+ _rejectedRevision != revision;++ void _check() {+ if (state == BackendConnectionState.closed ||+ state == BackendConnectionState.invalidated) {+ throw const SessionInvalidated();+ }+ }++ void _emit(BackendConnectionState next) {+ if (state == next) return;+ state = next;+ states.add(next);+ }++ void _invalidate() {+ ++_generation;+ _lifetime.cancel();+ state = BackendConnectionState.invalidated;+ onInvalidated?.call();+ if (state == BackendConnectionState.invalidated && !states.isClosed) {+ states.add(BackendConnectionState.invalidated);+ }+ }++ @override+ MutableApiKeyProvider createProvider({required bool Function() isActive}) {+ _check();+ final provider = _ScopedProvider(this, isActive);+ _providers.add(provider);+ return provider;+ }++ Future<void> ensureReady() async {+ _check();+ if (!usable) {+ if (_envelope != null && !clock().isBefore(_envelope!.expiresAt)) {+ _emit(BackendConnectionState.expired);+ }+ await refresh();+ _check();+ if (!usable) {+ throw const BackendAuthException(BackendAuthFailure.unavailable);+ }+ return;+ }+ final effective = Duration(+ microseconds: leeway.inMicroseconds < envelope.expiresIn * 500000+ ? leeway.inMicroseconds+ : envelope.expiresIn * 500000,+ );+ if (!clock().add(effective).isBefore(envelope.expiresAt)) {+ unawaited(refresh().catchError((Object _) {}));+ }+ }++ void reject(int failedRevision) {+ _check();+ _rejections.add(failedRevision);+ if (failedRevision == revision) _rejectedRevision = revision;+ }++ Future<void> recover(int failedRevision) async {+ _check();+ if (failedRevision < revision && usable) return;+ reject(failedRevision);+ await refresh();+ }++ Future<void> refresh({ScopedTokenEnvelope? initialToken}) {+ _check();+ if (_pending != null) return _pending!;+ final generation = _generation;+ _emit(BackendConnectionState.refreshing);+ final done = Completer<void>();+ final future = done.future;+ _pending = future;+ final probeCancellation = CancellationToken();+ final removeCancel = _lifetime.onCancel(probeCancellation.cancel);+ unawaited(+ _acquire(generation, initialToken, probeCancellation)+ .timeout(+ config.timeout,+ onTimeout: () {+ probeCancellation.cancel();+ throw const BackendAuthException(BackendAuthFailure.unavailable);+ },+ )+ .then((candidate) {+ _check();+ if (generation != _generation) throw const SessionInvalidated();+ if (!clock().isBefore(candidate.expiresAt)) {+ throw const BackendAuthException(+ BackendAuthFailure.invalidResponse,+ );+ }+ _envelope = candidate;+ revision++;+ _expiries[revision] = candidate.expiresAt;+ _expiries.removeWhere((_, expiry) => !clock().isBefore(expiry));+ _rejections.removeWhere(+ (revision) => !_expiries.containsKey(revision),+ );+ _rejectedRevision = null;+ _emit(BackendConnectionState.ready);+ })+ .then(+ (_) => done.complete(),+ onError: (Object error, StackTrace stack) {+ if (state == BackendConnectionState.closed ||+ state == BackendConnectionState.invalidated) {+ done.completeError(const SessionInvalidated(), stack);+ } else if (error is OperationCanceled ||+ error is BackendAuthException &&+ error.failure != BackendAuthFailure.unavailable ||+ error is ValidationException) {+ _invalidate();+ done.completeError(error, stack);+ } else {+ _emit(BackendConnectionState.unavailable);+ done.completeError(+ const BackendAuthException(BackendAuthFailure.unavailable),+ stack,+ );+ }+ },+ )+ .whenComplete(() {+ removeCancel();+ if (identical(_pending, future)) _pending = null;+ }),+ );+ return future;+ }++ Future<T> _live<T>(Future<T> work, CancellationToken cancellation) async {+ cancellation.throwIfCanceled();+ final result = await Future.any<T>([+ work,+ cancellation.whenCanceled.then<T>((_) => throw const OperationCanceled()),+ ]);+ cancellation.throwIfCanceled();+ _check();+ return result;+ }++ Future<ScopedTokenEnvelope> _acquire(+ int generation,+ ScopedTokenEnvelope? seed,+ CancellationToken cancellation,+ ) async {+ for (var attempt = 0; attempt < 3; attempt++) {+ try {+ final candidate =+ seed ??+ await _live<ScopedTokenEnvelope>(+ Future<ScopedTokenEnvelope>.sync(loadToken),+ cancellation,+ );+ _check();+ cancellation.throwIfCanceled();+ if (generation != _generation) throw const SessionInvalidated();+ if (candidate.appUserId != expectedAppUserId ||+ candidate.projectId != expectedProjectId ||+ !clock().isBefore(candidate.expiresAt) ||+ candidate.issuedAt.isAfter(+ clock().add(const Duration(seconds: 30)),+ )) {+ throw const BackendAuthException(BackendAuthFailure.invalidResponse);+ }+ if (_envelope != null &&+ (candidate._binding != envelope._binding ||+ candidate._policy != envelope._policy)) {+ throw const BackendAuthException(BackendAuthFailure.invalidResponse);+ }+ await _live(_verify(candidate, cancellation), cancellation);+ if (!clock().isBefore(candidate.expiresAt)) {+ throw const BackendAuthException(BackendAuthFailure.invalidResponse);+ }+ return candidate;+ } on Object catch (error) {+ cancellation.throwIfCanceled();+ _check();+ if (error is OperationCanceled) rethrow;+ if (error is ValidationException ||+ error is BackendAuthException &&+ error.failure != BackendAuthFailure.unavailable) {+ rethrow;+ }+ if ((error is AuthException && error is! BackendAuthException) ||+ error is ApiException && error.statusCode == 403) {+ throw const BackendAuthException(BackendAuthFailure.invalidResponse);+ }+ if (attempt == 2 || seed != null) rethrow;+ var wait = Duration(milliseconds: attempt == 0 ? 250 : 1000);+ if (error is BackendAuthException && error.retryAfter != null) {+ final retry = error.retryAfter!;+ if (retry > wait) {+ wait = retry > config.timeout ? config.timeout : retry;+ }+ }+ await _live(delay(wait), cancellation);+ }+ }+ throw const BackendAuthException(BackendAuthFailure.unavailable);+ }++ Future<void> _verify(+ ScopedTokenEnvelope candidate,+ CancellationToken cancellation,+ ) async {+ final probeConfig = config.copyWith(+ token: candidate.accessToken,+ maxRetries: 0,+ );+ final transport = transportFactory(probeConfig);+ Future<void>? closing;+ Future<void> closeProbe() => closing ??= Future<void>.sync(transport.close);+ final removeCancel = cancellation.onCancel(() {+ unawaited(closeProbe().catchError((Object _) {}));+ });+ try {+ final json = await VmodalHttp(+ probeConfig,+ transport,+ ).requestUsers('GET', '/api/v1/auth/me', cancellation: cancellation);+ if (json['auth_mode'] != 'developer_backend' ||+ json['type'] != 'scoped_user' ||+ _time(json, 'expires_at') != candidate.expiresAt ||+ json['user_id'] != candidate.principalId ||+ json['principal_id'] != candidate.principalId ||+ json['tenant_id'] != candidate.tenantId ||+ json['project_id'] != candidate.projectId ||+ json['app_user_id'] != candidate.appUserId ||+ json['policy_revision'] != candidate.policyRevision ||+ json['delegation_revision'] is! int ||+ json['delegation_revision'] != candidate.delegationRevision ||+ _grantPolicy(_grants(json['grants'])) !=+ _grantPolicy(candidate.grants)) {+ throw const BackendAuthException(BackendAuthFailure.invalidResponse);+ }+ } finally {+ removeCancel();+ await closeProbe();+ }+ }++ void close() {+ if (state == BackendConnectionState.closed) return;+ ++_generation;+ _lifetime.cancel();+ _emit(BackendConnectionState.closed);+ for (final provider in _providers.toList()) {+ provider.close();+ }+ _envelope = null;+ unawaited(states.close());+ }+}++class _ScopedProvider extends MutableApiKeyProvider+ implements AsyncCredentialProvider {+ _ScopedProvider(this.source, this.isActive)+ : super(source.envelope.accessToken);+ final _ScopedCredentialSource source;+ final bool Function() isActive;+ void _check() {+ if (isClosed || !isActive()) throw const SessionInvalidated();+ source._check();+ }++ @override+ int get revision {+ _check();+ return source.revision;+ }++ @override+ String current() {+ _check();+ if (!source.usable) {+ throw const BackendAuthException(BackendAuthFailure.unavailable);+ }+ return source.envelope.accessToken;+ }++ @override+ Future<void> ensureReady() async {+ _check();+ await source.ensureReady();+ _check();+ }++ @override+ bool isRevisionUsable(int revision) {+ _check();+ final expiry = source._expiries[revision];+ return expiry != null &&+ source.clock().isBefore(expiry) &&+ !source._rejections.contains(revision);+ }++ @override+ void reject(int revision) {+ _check();+ source.reject(revision);+ }++ @override+ Future<void> recover(int failedRevision) async {+ _check();+ await source.recover(failedRevision);+ _check();+ }++ @override+ void rotate(String newKey) =>+ throw const AuthException('Scoped credentials require backend renewal');+ @override+ void close() {+ source._providers.remove(this);+ super.close();+ }+}++Never _invalid() =>+ throw const ValidationException('Invalid scoped token contract');+void _fields(Map<String, Object?> json, Set<String> fields) {+ if (json.length != fields.length || !json.keys.every(fields.contains)) {+ _invalid();+ }+}++String _identifier(Map<String, Object?> json, String key, int limit) {+ final value = json[key];+ if (value is! String ||+ value.trim().isEmpty ||+ utf8.encode(value).length > limit ||+ value.runes.any((n) => n < 32 || (n >= 127 && n <= 159))) {+ _invalid();+ }+ return value;+}++String _selector(Map<String, Object?> json, String key) {+ final value = _identifier(json, key, 80);+ if (!RegExp(r'^[a-zA-Z0-9_]{1,80}$').hasMatch(value)) _invalid();+ return value;+}++DateTime _time(Map<String, Object?> json, String key) {+ final value = json[key];+ if (value is! String ||+ !RegExp(+ r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$',+ ).hasMatch(value)) {+ _invalid();+ }+ final time = DateTime.tryParse(value);+ if (time == null ||+ time.toIso8601String().substring(0, 19) != value.substring(0, 19)) {+ _invalid();+ }+ return time;+}++List<ScopedGrant> _grants(Object? raw) {+ if (raw is! List || raw.isEmpty || raw.length > 16) _invalid();+ final ids = <String>{}, selectors = <String>{};+ return raw.map((value) {+ if (value is! Map<String, Object?>) _invalid();+ final grant = ScopedGrant.fromJson(value);+ if (!ids.add(grant.grantId) ||+ !selectors.add(+ jsonEncode([grant.collectionId, grant.streamName, grant.mode]),+ )) {+ _invalid();+ }+ return grant;+ }).toList();+}++String _grantPolicy(List<ScopedGrant> grants) {+ final values = grants.map((g) => jsonEncode(g.toJson())).toList()..sort();+ return jsonEncode(values);+}diff --git a/lib/src/errors.dart b/lib/src/errors.dartindex 5f3bf45..8c1b133 100644--- a/lib/src/errors.dart+++ b/lib/src/errors.dart@@ -45,6 +45,22 @@ class TenantAuthException extends AuthException {]);}+/// Safe failures reported by the host's authenticated backend callback.+enum BackendAuthFailure {+ identityRejected,+ accessDenied,+ unavailable,+ invalidResponse,+}++/// Contains no host response, identity token, or VModal credential.+class BackendAuthException extends AuthException {+ const BackendAuthException(this.failure, {this.retryAfter})+ : super('developer backend authentication failed');+ final BackendAuthFailure failure;+ final Duration? retryAfter;+}+/// Valid service response that represents an unsuccessful operation.class ApiException extends SdkException {const ApiException(diff --git a/lib/src/http.dart b/lib/src/http.dartindex 232091e..a5b2e80 100644--- a/lib/src/http.dart+++ b/lib/src/http.dart@@ -22,6 +22,20 @@ class VmodalHttp {final DelayStrategy _delay;final Expando<TenantCredentialSnapshot> _credentialSnapshots =Expando<TenantCredentialSnapshot>();+ final Expando<int> _scopedRevisions = Expando<int>();++ Future<T> _withReady<T>(+ Future<T> Function(Map<String, String>) work, {+ bool usersApi = false,+ }) {+ final provider = config.apiKeyProvider;+ Map<String, String> capture() =>+ headers(forceToken: usersApi, requireUserId: !usersApi);+ if (provider is AsyncCredentialProvider) {+ return provider.ensureReady().then((_) => work(capture()));+ }+ return work(capture());+ }Map<String, String> headers({bool forceToken = false,@@ -59,6 +73,10 @@ class VmodalHttp {_assertGatewayHeaders(out);final frozen = Map<String, String>.unmodifiable(out);if (snapshot != null) _credentialSnapshots[frozen] = snapshot;+ final provider = config.apiKeyProvider;+ if (provider is AsyncCredentialProvider) {+ _scopedRevisions[frozen] = provider.revision;+ }return frozen;}@@ -70,15 +88,17 @@ class VmodalHttp {List<VmodalFilePart> files = const <VmodalFilePart>[],Map<String, Object?> params = const <String, Object?>{},CancellationToken? cancellation,- }) => _requestJson(- method,- path,- headers: headers(),- json: json,- data: data,- files: files,- params: params,- cancellation: cancellation,+ }) => _withReady(+ (captured) => _requestJson(+ method,+ path,+ headers: captured,+ json: json,+ data: data,+ files: files,+ params: params,+ cancellation: cancellation,+ ),);Future<Map<String, Object?>> requestUsers(@@ -87,14 +107,17 @@ class VmodalHttp {Object? json,Map<String, Object?> params = const <String, Object?>{},CancellationToken? cancellation,- }) => _requestJson(- method,- path,- headers: headers(forceToken: true, requireUserId: false),- json: json,- params: params,+ }) => _withReady(+ (captured) => _requestJson(+ method,+ path,+ headers: captured,+ json: json,+ params: params,+ usersApi: true,+ cancellation: cancellation,+ ),usersApi: true,- cancellation: cancellation,);Future<Uint8List> requestBytes(@@ -107,21 +130,23 @@ class VmodalHttp {}) async {final limit = _binaryLimit(maxBytes);final token = cancellation ?? CancellationToken();- return _executeRead<Uint8List>(- method,- path,- headers: headers(),- json: json,- params: params,- responseMode: VmodalResponseMode.bytes,- cancellation: token,- reader: (VmodalResponse response, CancellationToken attempt) =>- readBounded(- response,- limit,- cancellation: attempt,- idleTimeout: config.idleTimeout,- ),+ return _withReady(+ (captured) => _executeRead<Uint8List>(+ method,+ path,+ headers: captured,+ json: json,+ params: params,+ responseMode: VmodalResponseMode.bytes,+ cancellation: token,+ reader: (VmodalResponse response, CancellationToken attempt) =>+ readBounded(+ response,+ limit,+ cancellation: attempt,+ idleTimeout: config.idleTimeout,+ ),+ ),);}@@ -136,22 +161,24 @@ class VmodalHttp {}) async {final limit = _binaryLimit(maxBytes);final token = cancellation ?? CancellationToken();- await _executeRead<void>(- method,- path,- headers: headers(),- json: json,- params: params,- responseMode: VmodalResponseMode.bytes,- cancellation: token,- reader: (VmodalResponse response, CancellationToken attempt) =>- writeBounded(- response,- sink,- limit,- cancellation: attempt,- idleTimeout: config.idleTimeout,- ),+ await _withReady(+ (captured) => _executeRead<void>(+ method,+ path,+ headers: captured,+ json: json,+ params: params,+ responseMode: VmodalResponseMode.bytes,+ cancellation: token,+ reader: (VmodalResponse response, CancellationToken attempt) =>+ writeBounded(+ response,+ sink,+ limit,+ cancellation: attempt,+ idleTimeout: config.idleTimeout,+ ),+ ),);}@@ -207,18 +234,39 @@ class VmodalHttp {final tenantProvider = provider is TenantSessionApiKeyProvider? provider: null;+ final scopedProvider = provider is AsyncCredentialProvider+ ? provider+ : null;var requestHeaders = headers;var snapshot = _credentialSnapshots[requestHeaders];+ var scopedRevision = _scopedRevisions[requestHeaders];var recovered = false;var retries = 0;final retryBudget =config.normalizedMaxRetries +- (canRetry && tenantProvider != null ? 1 : 0);+ (canRetry && (tenantProvider != null || scopedProvider != null)+ ? 1+ : 0);for (var attempt = 0; attempt <= retryBudget; attempt++) {cancellation.throwIfCanceled();final attemptCancellation = CancellationToken();final removeCancel = cancellation.onCancel(attemptCancellation.cancel);try {+ if (scopedProvider != null &&+ scopedRevision != null &&+ !scopedProvider.isRevisionUsable(scopedRevision)) {+ if (recovered || (!canRetry && attempt > 0)) {+ throw const AuthException('scoped credential expired');+ }+ recovered = true;+ await scopedProvider.recover(scopedRevision);+ cancellation.throwIfCanceled();+ requestHeaders = this.headers(+ forceToken: usersApi,+ requireUserId: !usersApi,+ );+ scopedRevision = _scopedRevisions[requestHeaders];+ }final request = VmodalRequest(method: normalized,uri: uri,@@ -233,6 +281,23 @@ class VmodalHttp {// revocation or after its session lease has expired.tenantProvider?.snapshot();final response = await transport.send(request);+ if (scopedProvider != null && response.statusCode == 401) {+ await _discard(response, attemptCancellation);+ cancellation.throwIfCanceled();+ scopedProvider.reject(scopedRevision!);+ if (!canRetry || recovered || attempt >= retryBudget) {+ throw const AuthException('scoped request authentication failed');+ }+ recovered = true;+ await scopedProvider.recover(scopedRevision);+ cancellation.throwIfCanceled();+ requestHeaders = this.headers(+ forceToken: usersApi,+ requireUserId: !usersApi,+ );+ scopedRevision = _scopedRevisions[requestHeaders];+ continue;+ }if (tenantProvider != null && response.statusCode == 401) {await _discard(response, attemptCancellation);cancellation.throwIfCanceled();diff --git a/lib/src/models.dart b/lib/src/models.dartindex 65dc227..199467b 100644--- a/lib/src/models.dart+++ b/lib/src/models.dart@@ -852,6 +852,15 @@ class UserProfile extends JsonBackedResponse {.map((Object? value) => '$value').toList(): <String>[],+ authMode = raw['auth_mode'] as String?,+ principalId = raw['principal_id'] as String?,+ projectId = raw['project_id'] as String?,+ appUserId = raw['app_user_id'] as String?,+ policyRevision = raw['policy_revision'] as String?,+ delegationRevision = raw['delegation_revision'] as int?,+ expiresAt = raw['expires_at'] is String+ ? DateTime.tryParse(raw['expires_at']! as String)+ : null,type = '${raw['type'] ?? 'user'}';final String? userId;@@ -861,6 +870,9 @@ class UserProfile extends JsonBackedResponse {final String? tenantId;final List<String> permissions;final String type;+ final String? authMode, principalId, projectId, appUserId, policyRevision;+ final int? delegationRevision;+ final DateTime? expiresAt;}/// Usage totals grouped by operation for one date.diff --git a/lib/src/user_session.dart b/lib/src/user_session.dartindex ccc5e5a..1b33f65 100644--- a/lib/src/user_session.dart+++ b/lib/src/user_session.dart@@ -230,7 +230,7 @@ final class SessionContext {final class UserSessionManager {UserSessionManager({required SdkConfig config,- required TenantCredentialSource credentialSource,+ required SessionCredentialSource credentialSource,VmodalTransport Function(SdkConfig config)? transportFactory,SignedUploadTransport Function(SdkConfig config)?signedUploadTransportFactory,@@ -255,7 +255,7 @@ final class UserSessionManager {}final SdkConfig _config;- final TenantCredentialSource _credentials;+ final SessionCredentialSource _credentials;final UploadSessionStore? _uploadSessionStore;final VmodalTransport Function(SdkConfig) _transportFactory;final SignedUploadTransport Function(SdkConfig) _signedFactory;@@ -305,7 +305,12 @@ final class UserSessionManager {);}final context = SessionContext._(- SessionContext.serviceNamespaceFor(_config),+ _credentials.projectId == null+ ? SessionContext.serviceNamespaceFor(_config)+ : jsonEncode(<String>[+ SessionContext.serviceNamespaceFor(_config),+ _credentials.projectId!,+ ]),policy,);final selectors = <String>{};@@ -1302,6 +1307,8 @@ Future<T> _safeWork<T>(Future<T> Function() work) async {throw const FeatureDisabled('Operation is unavailable in this scope');} on ValidationException {throw const ValidationException('Operation validation failed');+ } on BackendAuthException {+ rethrow;} on AuthException {throw const TenantAuthException();} on ApiException catch (error) {diff --git a/lib/src/vmodal.dart b/lib/src/vmodal.dartindex 077927c..d7e6473 100644--- a/lib/src/vmodal.dart+++ b/lib/src/vmodal.dart@@ -1,8 +1,10 @@import 'api_key_provider.dart';+import 'backend_auth.dart';import 'client.dart';import 'collection_uploads.dart';import 'config.dart';import 'content_scope.dart';+import 'http.dart';import 'models.dart';import 'transport.dart';import 'upload.dart';@@ -10,6 +12,36 @@ import 'utils.dart';/// Preferred entry point for project, collection, and stream scoped clients.abstract final class VModal {+ /// Acquires a scoped VModal token through the host's authenticated backend.+ /// Readiness requires authoritative identity and grant confirmation.+ static Future<BackendConnection> connectWithBackend({+ required String expectedAppUserId,+ required String expectedProjectId,+ required Future<ScopedTokenEnvelope> Function() loadToken,+ Uri? baseUri,+ Duration timeout = const Duration(seconds: 30),+ int maxRetries = 1,+ Duration refreshLeeway = const Duration(seconds: 60),+ ScopedTokenEnvelope? initialToken,+ DateTime Function()? clock,+ DelayStrategy? delay,+ VmodalTransport Function(SdkConfig)? transportFactory,+ SignedUploadTransport Function(SdkConfig)? signedUploadTransportFactory,+ }) => BackendConnection.connect(+ expectedAppUserId: expectedAppUserId,+ expectedProjectId: expectedProjectId,+ loadToken: loadToken,+ baseUri: baseUri,+ timeout: timeout,+ maxRetries: maxRetries,+ refreshLeeway: refreshLeeway,+ initialToken: initialToken,+ clock: clock,+ delay: delay,+ transportFactory: transportFactory,+ signedUploadTransportFactory: signedUploadTransportFactory,+ );+/// Creates one owned project client without performing network I/O.static VModalProject configure({required String projectId,diff --git a/lib/vmodal_sdk_flutter.dart b/lib/vmodal_sdk_flutter.dartindex 5a1f8ff..957f3bd 100644--- a/lib/vmodal_sdk_flutter.dart+++ b/lib/vmodal_sdk_flutter.dart@@ -31,6 +31,7 @@ library vmodal_sdk_flutter;export 'src/adaptive_upload.dart';export 'src/api_key_provider.dart';+export 'src/backend_auth.dart';export 'src/client.dart';export 'src/collection_uploads.dart';export 'src/config.dart';diff --git a/test/backend_auth_test.dart b/test/backend_auth_test.dartnew file mode 100644index 0000000..d1420d2--- /dev/null+++ b/test/backend_auth_test.dart@@ -0,0 +1,728 @@+import 'dart:async';+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:vmodal_sdk_flutter/vmodal_sdk_flutter.dart';++import 'fakes.dart';++final _start = DateTime.utc(2026, 10, 2);++String _token(String label) =>+ 'eyJhbGciOiJSUzI1NiIsInR5cCI6InZtb2RhbC1zY29wZWQrand0Iiwia2lkIjoidGVzdCJ9.'+ '${base64Url.encode(utf8.encode(label)).replaceAll('=', '')}.c2lnbmF0dXJl';++Map<String, Object?> _envelope({+ String token = 'scoped-one',+ String project = 'framebase',+ String user = 'app-A',+ String policy = 'policy-1',+ DateTime? issued,+}) {+ final time = issued ?? _start;+ return {+ 'version': 1,+ 'auth_mode': 'developer_backend',+ 'access_token': _token(token),+ 'token_type': 'Bearer',+ 'expires_in': 300,+ 'issued_at': time.toIso8601String(),+ 'expires_at': time.add(const Duration(seconds: 300)).toIso8601String(),+ 'principal_id': 'principal-owner',+ 'tenant_id': 'tenant-T',+ 'project_id': project,+ 'app_user_id': user,+ 'policy_revision': policy,+ 'delegation_revision': 3,+ 'grants': [+ {+ 'grant_id': 'my_library',+ 'collection_id': 'opaque_A7f9',+ 'stream_name': 'street_study',+ 'mode': 'vid_file',+ 'actions': ['discover', 'search', 'media'],+ 'collection_wide': false,+ },+ ],+ };+}++Map<String, Object?> _profile(Map<String, Object?> value) => {+ for (final field in [+ 'auth_mode',+ 'principal_id',+ 'tenant_id',+ 'project_id',+ 'app_user_id',+ 'policy_revision',+ 'delegation_revision',+ 'grants',+ ])+ field: value[field],+ 'user_id': value['principal_id'],+ 'type': 'scoped_user',+ 'expires_at': value['expires_at'],+};++class _Harness {+ DateTime now = _start;+ Map<String, Object?> next = _envelope();+ final Map<String, Map<String, Object?>> tokens = {};+ final List<VmodalRequest> requests = [];+ final List<Duration> delays = [];+ int loads = 0;+ Future<ScopedTokenEnvelope> Function()? load;+ Future<VmodalResponse> Function(VmodalRequest)? data;+ Map<String, Object?> Function(Map<String, Object?>)? profile;++ Future<ScopedTokenEnvelope> acquire() async {+ loads++;+ debugPrint('backend callback attempt $loads at $now');+ if (load != null) return load!();+ tokens[next['access_token']! as String] = next;+ return ScopedTokenEnvelope.fromJson(next);+ }++ VmodalTransport transport(SdkConfig config) => HandlerTransport((+ request,+ ) async {+ requests.add(request);+ debugPrint(+ '${request.method} ${request.uri.path} credential dispatched (redacted)',+ );+ expect(+ request.headers.keys.where((k) => k.toLowerCase().startsWith('x-user')),+ isEmpty,+ );+ if (request.uri.path == '/api/v1/auth/me') {+ final token = request.headers['Authorization']!.substring(7);+ final envelope = tokens[token] ?? next;+ return jsonResponse(+ jsonEncode(profile?.call(envelope) ?? _profile(envelope)),+ );+ }+ if (data != null) return data!(request);+ return jsonResponse(+ '{"data":[{"group_name":"opaque_A7f9","mode":"vid_file"}]}',+ );+ });+ Future<BackendConnection> connect({+ String project = 'framebase',+ String user = 'app-A',+ Duration leeway = const Duration(seconds: 60),+ ScopedTokenEnvelope? initial,+ Duration timeout = const Duration(seconds: 30),+ }) => VModal.connectWithBackend(+ expectedAppUserId: user,+ expectedProjectId: project,+ loadToken: acquire,+ baseUri: Uri.parse('https://gateway.test'),+ clock: () => now,+ refreshLeeway: leeway,+ timeout: timeout,+ initialToken: initial,+ delay: (duration) async {+ delays.add(duration);+ },+ transportFactory: transport,+ signedUploadTransportFactory: (_) => FakeSignedUploadTransport(),+ );+ List<VmodalRequest> get dataRequests =>+ requests.where((r) => r.uri.path != '/api/v1/auth/me').toList();+}++void main() {+ test(+ 'strict immutable envelope accepts exact opaque grants and redacts bearer',+ () {+ debugPrint('Strict version, UTC lifetime, exact grant parsing');+ final raw = _envelope();+ final envelope = ScopedTokenEnvelope.fromJson(raw);+ expect(+ envelope.expiresAt.difference(envelope.issuedAt),+ const Duration(seconds: 300),+ );+ expect(envelope.grants.single.mapping.collectionId, 'opaque_A7f9');+ expect(+ envelope.grants.single.mapping.representation,+ ScopeRepresentation.opaque,+ );+ expect('$envelope', isNot(contains(_token('scoped-one'))));+ (raw['grants']! as List).clear();+ expect(envelope.grants, hasLength(1));+ expect(() => envelope.grants.clear(), throwsUnsupportedError);+ expect(+ () => envelope.grants.single.actions.clear(),+ throwsUnsupportedError,+ );+ },+ );++ test(+ 'reject unknown fields, versions, types, timestamps, sizes and grants',+ () {+ final bad = <Map<String, Object?>>[+ {..._envelope(), 'unexpected': true},+ {..._envelope(), 'version': true},+ {..._envelope(), 'version': 2},+ {..._envelope(), 'auth_mode': 'direct'},+ {..._envelope(), 'expires_in': 300.0},+ {..._envelope(), 'expires_in': 901},+ {..._envelope(), 'delegation_revision': true},+ {..._envelope(), 'expires_at': '2026-10-02T00:06:00Z'},+ {..._envelope(), 'issued_at': '2026-10-02T00:00:00+00:00'},+ {..._envelope(), 'issued_at': '2026-02-30T00:00:00Z'},+ {..._envelope(), 'access_token': 'x' * 8193},+ {..._envelope(), 'access_token': 'bad\nkey'},+ {..._envelope(), 'access_token': 'ak_master_key'},+ {..._envelope(), 'access_token': 'a..c'},+ {..._envelope(), 'app_user_id': '界' * 86},+ {..._envelope(), 'policy_revision': ''},+ {..._envelope(), 'app_user_id': 'user\u0085'},+ {..._envelope(), 'project_id': 'p' * 257},+ {..._envelope(), 'grants': []},+ ];+ final grant =+ (_envelope()['grants']! as List).single as Map<String, Object?>;+ for (final altered in [+ {...grant, 'actions': <String>[]},+ {+ ...grant,+ 'actions': ['search', 'unknown'],+ },+ {+ ...grant,+ 'actions': ['search', 'search'],+ },+ {...grant, 'collection_id': '*'},+ {...grant, 'collection_wide': 'false'},+ {...grant, 'extra': 1},+ ]) {+ bad.add({+ ..._envelope(),+ 'grants': [altered],+ });+ }+ bad.add({+ ..._envelope(),+ 'grants': [grant, grant],+ });+ for (var i = 0; i < bad.length; i++) {+ debugPrint('reject malformed envelope case $i');+ expect(+ () => ScopedTokenEnvelope.fromJson(bad[i]),+ throwsA(isA<ValidationException>()),+ );+ }+ },+ );++ test(+ 'activate after auth/me agreement and scope does not prefix selectors',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ expect(connection.state, BackendConnectionState.ready);+ expect(h.loads, 1);+ expect(h.requests.single.uri.path, '/api/v1/auth/me');+ final scope = connection.scope('my_library');+ expect(scope.mapping.collectionId, 'opaque_A7f9');+ expect(+ () => connection.scope('unknown'),+ throwsA(isA<ValidationException>()),+ );+ await scope.search('person entering');+ expect(+ h.dataRequests.single.headers['Authorization'],+ 'Bearer ${_token('scoped-one')}',+ );+ final json = h.dataRequests.single.jsonBody as Map;+ expect(json['group_name'], 'opaque_A7f9');+ expect(json['stream_name'], 'street_study');+ final session = connection.session;+ final closing = connection.close();+ expect(session.isActive, isFalse);+ expect(connection.state, BackendConnectionState.closed);+ expect(() => connection.session, throwsA(isA<SessionInvalidated>()));+ expect(identical(closing, connection.close()), isTrue);+ await closing;+ },+ );++ test(+ 'initial token has identical verification without calling host loader',+ () async {+ final h = _Harness();+ final connection = await h.connect(+ initial: ScopedTokenEnvelope.fromJson(h.next),+ );+ expect(h.loads, 0);+ expect(h.requests.single.uri.path, '/api/v1/auth/me');+ await connection.close();+ },+ );++ test(+ 'expected app/project mismatch and expired token fail before probe',+ () async {+ for (final raw in [+ _envelope(user: 'B'),+ _envelope(project: 'other'),+ _envelope(issued: _start.subtract(const Duration(seconds: 300))),+ ]) {+ final h = _Harness()..next = raw;+ await expectLater(h.connect(), throwsA(isA<BackendAuthException>()));+ expect(h.loads, 1);+ expect(h.requests, isEmpty);+ }+ },+ );++ test(+ 'authoritative profile rejects missing binding and forged copied grants',+ () async {+ for (final field in [+ 'user_id',+ 'principal_id',+ 'tenant_id',+ 'project_id',+ 'app_user_id',+ 'policy_revision',+ 'delegation_revision',+ 'auth_mode',+ 'grants',+ ]) {+ final h = _Harness()..profile = (raw) => _profile(raw)..remove(field);+ debugPrint('auth/me must contain agreeing $field');+ await expectLater(h.connect(), throwsA(isA<SdkException>()));+ expect(h.loads, 1);+ }+ final h = _Harness();+ h.profile = (raw) => {+ ..._profile(raw),+ 'grants': [+ {+ ...(raw['grants']! as List).single as Map<String, Object?>,+ 'collection_id': 'other_collection',+ },+ ],+ };+ await expectLater(h.connect(), throwsA(isA<BackendAuthException>()));+ },+ );++ test(+ 'same policy rotation coalesces and preserves session, owner and lease',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ final session = connection.session;+ final lease = connection.scope('my_library').storageLease;+ final pending = Completer<ScopedTokenEnvelope>();+ h.next = _envelope(+ token: 'scoped-two',+ issued: _start.add(const Duration(seconds: 30)),+ );+ h.load = () => pending.future;+ final states = <BackendConnectionState>[];+ final subscription = connection.states.listen(states.add);+ final first = connection.refresh(), second = connection.refresh();+ expect(identical(first, second), isTrue);+ pending.complete(ScopedTokenEnvelope.fromJson(h.next));+ await Future.wait([first, second]);+ expect(h.loads, 2);+ expect(identical(session, connection.session), isTrue);+ lease.check();+ await connection.session.listCollections();+ expect(+ h.dataRequests.last.headers['Authorization'],+ 'Bearer ${_token('scoped-two')}',+ );+ expect(states, [+ BackendConnectionState.refreshing,+ BackendConnectionState.ready,+ ]);+ await subscription.cancel();+ await connection.close();+ },+ );++ test(+ 'policy, grants, tenant or principal change invalidates synchronously',+ () async {+ for (final field in [+ 'policy_revision',+ 'delegation_revision',+ 'principal_id',+ 'tenant_id',+ 'grants',+ ]) {+ final h = _Harness();+ final connection = await h.connect();+ final old = connection.session;+ h.next = {+ ..._envelope(token: 'scoped-two'),+ field: field == 'delegation_revision'+ ? 4+ : field == 'grants'+ ? [+ {+ ...(_envelope()['grants']! as List).single+ as Map<String, Object?>,+ 'actions': ['search'],+ },+ ]+ : 'changed',+ };+ await expectLater(+ connection.refresh(),+ throwsA(isA<BackendAuthException>()),+ );+ expect(connection.state, BackendConnectionState.invalidated);+ expect(old.isActive, isFalse);+ expect(() => connection.session, throwsA(isA<SessionInvalidated>()));+ await connection.close();+ }+ },+ );++ test(+ 'same app user in different projects has different owner and scope keys',+ () async {+ final a = _Harness(),+ b = _Harness()..next = _envelope(project: 'project-B');+ final ca = await a.connect(), cb = await b.connect(project: 'project-B');+ expect(ca.session.context.ownerKey, isNot(cb.session.context.ownerKey));+ expect(+ ca.scope('my_library').scopeKey,+ isNot(cb.scope('my_library').scopeKey),+ );+ await ca.close();+ await cb.close();+ },+ );++ test(+ 'transient acquisition is bounded to three attempts with injected delays',+ () async {+ final h = _Harness()+ ..load = () async =>+ throw const BackendAuthException(BackendAuthFailure.unavailable);+ await expectLater(h.connect(), throwsA(isA<BackendAuthException>()));+ expect(h.loads, 3);+ expect(h.delays, [+ const Duration(milliseconds: 250),+ const Duration(milliseconds: 1000),+ ]);+ expect(h.requests, isEmpty);+ },+ );++ test(+ 'backend 401 or 403 invalidates while transient outage retains valid token',+ () async {+ for (final failure in BackendAuthFailure.values) {+ final h = _Harness();+ final connection = await h.connect();+ final old = connection.session;+ h.load = () async => throw BackendAuthException(failure);+ await expectLater(+ connection.refresh(),+ throwsA(isA<BackendAuthException>()),+ );+ if (failure == BackendAuthFailure.unavailable) {+ expect(old.isActive, isTrue);+ expect(connection.state, BackendConnectionState.unavailable);+ await old.listCollections();+ expect(h.dataRequests, hasLength(1));+ h.now = _start.add(const Duration(seconds: 301));+ await expectLater(+ old.listCollections(),+ throwsA(isA<BackendAuthException>()),+ );+ expect(h.dataRequests, hasLength(1));+ } else {+ expect(old.isActive, isFalse);+ expect(connection.state, BackendConnectionState.invalidated);+ }+ await connection.close();+ }+ },+ );++ test(+ 'parallel expired requests join one renewal and never dispatch expired bearer',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ h.now = _start.add(const Duration(seconds: 301));+ h.next = _envelope(token: 'scoped-two', issued: h.now);+ final pending = Completer<ScopedTokenEnvelope>();+ h.load = () => pending.future;+ final first = connection.session.listCollections(),+ second = connection.session.listCollections();+ await Future<void>.delayed(Duration.zero);+ expect(h.loads, 2);+ expect(h.dataRequests, isEmpty);+ pending.complete(ScopedTokenEnvelope.fromJson(h.next));+ await Future.wait([first, second]);+ expect(h.dataRequests, hasLength(2));+ expect(+ h.dataRequests.map((r) => r.headers['Authorization']),+ everyElement('Bearer ${_token('scoped-two')}'),+ );+ await connection.close();+ },+ );++ test(+ 'close cancels pending renewal immediately and fences late callback',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ final pending = Completer<ScopedTokenEnvelope>();+ h.load = () => pending.future;+ final renewal = connection.refresh();+ final failure = expectLater(renewal, throwsA(isA<OperationCanceled>()));+ await connection.close();+ await failure;+ pending.complete(ScopedTokenEnvelope.fromJson(_envelope(token: 'late')));+ await Future<void>.delayed(Duration.zero);+ expect(connection.state, BackendConnectionState.closed);+ expect(h.requests, hasLength(1));+ },+ );++ test('GET 401 recovers once; POST and 403 never replay or broaden', () async {+ final h = _Harness();+ final connection = await h.connect();+ h.next = _envelope(token: 'scoped-two');+ var calls = 0;+ h.data = (_) async => jsonResponse('{}', status: calls++ == 0 ? 401 : 200);+ await connection.session.listCollections();+ expect(h.loads, 2);+ expect(h.dataRequests, hasLength(2));+ h.data = (_) async => jsonResponse('{}', status: 401);+ await expectLater(+ connection.scope('my_library').search('query'),+ throwsA(isA<AuthException>()),+ );+ expect(h.dataRequests, hasLength(3));+ expect(h.loads, 2);+ h.next = _envelope(token: 'scoped-three');+ h.data = (_) async => jsonResponse('{}', status: 403);+ await expectLater(+ connection.session.listCollections(),+ throwsA(isA<ApiException>()),+ );+ expect(h.loads, 3); // Recovery before later request, never mutation replay.+ expect(h.dataRequests, hasLength(4));+ expect(connection.session.isActive, isTrue);+ await connection.close();+ });++ test(+ 'stale 401 cannot revoke a replacement and uses it without another callback',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ final denied = Completer<VmodalResponse>();+ final started = Completer<void>();+ var calls = 0;+ h.data = (_) {+ if (calls++ == 0) {+ started.complete();+ return denied.future;+ }+ return Future.value(jsonResponse('{}'));+ };+ final read = connection.session.listCollections();+ await started.future;+ h.next = _envelope(token: 'scoped-two');+ await connection.refresh();+ denied.complete(jsonResponse('{}', status: 401));+ await read;+ expect(h.loads, 2);+ expect(+ h.dataRequests.last.headers['Authorization'],+ 'Bearer ${_token('scoped-two')}',+ );+ await connection.close();+ },+ );++ test('acquisition timeout gates data and discards late envelope', () async {+ final h = _Harness();+ final pending = Completer<ScopedTokenEnvelope>();+ h.load = () => pending.future;+ await expectLater(+ h.connect(timeout: const Duration(milliseconds: 20)),+ throwsA(isA<BackendAuthException>()),+ );+ pending.complete(ScopedTokenEnvelope.fromJson(h.next));+ await Future<void>.delayed(Duration.zero);+ expect(h.requests, isEmpty);+ });++ test(+ 'near-expiry reads retain valid token while one proactive renewal runs',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ h.now = _start.add(const Duration(seconds: 250));+ h.next = _envelope(token: 'renewed', issued: h.now);+ final pending = Completer<ScopedTokenEnvelope>();+ h.load = () => pending.future;+ await Future.wait([+ connection.session.listCollections(),+ connection.session.listCollections(),+ ]);+ expect(h.loads, 2);+ expect(connection.state, BackendConnectionState.refreshing);+ expect(+ h.dataRequests.map((r) => r.headers['Authorization']),+ everyElement('Bearer ${_token('scoped-one')}'),+ );+ pending.complete(ScopedTokenEnvelope.fromJson(h.next));+ await connection.refresh();+ expect(connection.state, BackendConnectionState.ready);+ await connection.close();+ },+ );++ test('binary media gates expiry between URL grant and byte request', () async {+ final h = _Harness();+ final connection = await h.connect();+ var calls = 0;+ h.data = (_) async {+ switch (calls++) {+ case 0:+ return jsonResponse(+ '{"data":[{"asset_id":"a","filename":"a.mp4","playback_offset_ms":2300}]}',+ );+ case 1:+ h.now = _start.add(const Duration(seconds: 301));+ h.next = _envelope(token: 'renewed', issued: h.now);+ return jsonResponse(+ '{"found":true,"url_pre_signed":"https://objects.test/scoped"}',+ );+ default:+ return VmodalResponse(statusCode: 200, body: Stream.value([1, 2, 3]));+ }+ };+ final scope = connection.scope('my_library');+ final asset = (await scope.search('person')).assets.single;+ expect(await scope.imageBytes(asset), [1, 2, 3]);+ expect(h.loads, 2);+ expect(h.dataRequests.last.responseMode, VmodalResponseMode.bytes);+ expect(+ h.dataRequests.last.headers['Authorization'],+ 'Bearer ${_token('renewed')}',+ );+ await connection.close();+ });++ test('second 401 exhausts read credential budget without looping', () async {+ final h = _Harness();+ final connection = await h.connect();+ h.next = _envelope(token: 'renewed');+ h.data = (_) async => jsonResponse('{}', status: 401);+ await expectLater(+ connection.session.listCollections(),+ throwsA(isA<AuthException>()),+ );+ expect(h.loads, 2);+ expect(h.dataRequests, hasLength(2));+ await connection.close();+ });++ test(+ 'host cancellation is not retried and invalidates the active session',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ final active = connection.session;+ var observed = false;+ final subscription = connection.states.listen((state) {+ if (state == BackendConnectionState.invalidated) {+ observed = true;+ expect(active.isActive, isFalse);+ }+ });+ h.load = () async => throw const SessionInvalidated();+ await expectLater(+ connection.refresh(),+ throwsA(isA<OperationCanceled>()),+ );+ expect(h.loads, 2);+ expect(h.delays, isEmpty);+ expect(active.isActive, isFalse);+ expect(observed, isTrue);+ expect(connection.state, BackendConnectionState.invalidated);+ await subscription.cancel();+ await connection.close();+ },+ );++ test(+ 'closed lifecycle event sees a retired guard and unavailable session',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ final active = connection.session;+ var observed = false;+ final subscription = connection.states.listen((state) {+ if (state == BackendConnectionState.closed) {+ observed = true;+ expect(active.isActive, isFalse);+ expect(() => connection.session, throwsA(isA<SessionInvalidated>()));+ }+ });+ await connection.close();+ expect(observed, isTrue);+ await subscription.cancel();+ },+ );++ test(+ 'ordinary retry renews a snapshot that expired during retry delay',+ () async {+ final h = _Harness();+ final connection = await h.connect();+ var calls = 0;+ h.data = (_) async {+ if (calls++ == 0) {+ h.now = _start.add(const Duration(seconds: 301));+ h.next = _envelope(token: 'renewed', issued: h.now);+ return jsonResponse('{}', status: 503);+ }+ return jsonResponse('{}');+ };+ await connection.session.listCollections();+ expect(h.loads, 2);+ expect(h.dataRequests, hasLength(2));+ expect(+ h.dataRequests.last.headers['Authorization'],+ 'Bearer ${_token('renewed')}',+ );+ await connection.close();+ },+ );++ test('lifecycle listeners can close reentrantly during renewal', () async {+ final h = _Harness();+ final connection = await h.connect();+ final pending = Completer<ScopedTokenEnvelope>();+ h.load = () => pending.future;+ final subscription = connection.states.listen((state) {+ if (state == BackendConnectionState.refreshing) {+ unawaited(connection.close());+ }+ });+ await expectLater(connection.refresh(), throwsA(isA<OperationCanceled>()));+ expect(connection.state, BackendConnectionState.closed);+ pending.complete(ScopedTokenEnvelope.fromJson(_envelope(token: 'late')));+ await subscription.cancel();+ });+}diff --git a/test/docs_reference_test.dart b/test/docs_reference_test.dartindex cc7ed91..6d9cb4f 100644--- a/test/docs_reference_test.dart+++ b/test/docs_reference_test.dart@@ -16,6 +16,19 @@ final requiredDocs = <String>['vmodal_sdk_flutter/VmodalClient/close.html','vmodal_sdk_flutter/VModal-class.html','vmodal_sdk_flutter/VModal/configure.html',+ 'vmodal_sdk_flutter/VModal/connectWithBackend.html',+ 'vmodal_sdk_flutter/BackendConnection-class.html',+ 'vmodal_sdk_flutter/BackendConnection/session.html',+ 'vmodal_sdk_flutter/BackendConnection/scope.html',+ 'vmodal_sdk_flutter/BackendConnection/refresh.html',+ 'vmodal_sdk_flutter/BackendConnection/close.html',+ 'vmodal_sdk_flutter/BackendConnectionState.html',+ 'vmodal_sdk_flutter/ScopedTokenEnvelope-class.html',+ 'vmodal_sdk_flutter/ScopedTokenEnvelope/ScopedTokenEnvelope.fromJson.html',+ 'vmodal_sdk_flutter/ScopedGrant-class.html',+ 'vmodal_sdk_flutter/ScopedGrant/ScopedGrant.fromJson.html',+ 'vmodal_sdk_flutter/BackendAuthException-class.html',+ 'vmodal_sdk_flutter/BackendAuthFailure.html','vmodal_sdk_flutter/VModalProject-class.html','vmodal_sdk_flutter/VModalProject/scope.html','vmodal_sdk_flutter/VModalProject/listCollections.html',@@ -102,6 +115,19 @@ void main() {'vmodal_sdk_flutter.VModalProject','vmodal_sdk_flutter.VModalScope','vmodal_sdk_flutter.VModal.configure',+ 'vmodal_sdk_flutter.VModal.connectWithBackend',+ 'vmodal_sdk_flutter.BackendConnection',+ 'vmodal_sdk_flutter.BackendConnection.session',+ 'vmodal_sdk_flutter.BackendConnection.scope',+ 'vmodal_sdk_flutter.BackendConnection.refresh',+ 'vmodal_sdk_flutter.BackendConnection.close',+ 'vmodal_sdk_flutter.BackendConnectionState',+ 'vmodal_sdk_flutter.ScopedTokenEnvelope',+ 'vmodal_sdk_flutter.ScopedTokenEnvelope.ScopedTokenEnvelope.fromJson',+ 'vmodal_sdk_flutter.ScopedGrant',+ 'vmodal_sdk_flutter.ScopedGrant.ScopedGrant.fromJson',+ 'vmodal_sdk_flutter.BackendAuthException',+ 'vmodal_sdk_flutter.BackendAuthFailure','vmodal_sdk_flutter.VModalProject.scope','vmodal_sdk_flutter.VModalProject.listCollections','vmodal_sdk_flutter.VModalScope.upload',diff --git a/test/regression_manifest_test.dart b/test/regression_manifest_test.dartindex 97fee4b..5047215 100644--- a/test/regression_manifest_test.dart+++ b/test/regression_manifest_test.dart@@ -178,6 +178,8 @@ void main() {'tool/perf_benchmark.dart','lib/src/user_session.dart','lib/src/session_guard.dart',+ 'lib/src/backend_auth.dart',+ 'test/backend_auth_test.dart','test/user_session_test.dart','test/session_guard_test.dart','test/tenant_credentials_test.dart',@@ -219,6 +221,14 @@ void main() {'docs/sdk_contract.md','docs/README.md','docs/component_patterns.md',+ 'docs/authentication.md',+ 'docs/backend_authentication.md',+ 'example/06_backend_auth/README.md',+ 'example/06_backend_auth/pubspec.yaml',+ 'example/06_backend_auth/lib/backend_auth_example.dart',+ 'example/06_backend_auth/test/backend_auth_example_test.dart',+ 'example/06_backend_auth/developer_backend/session.mjs',+ 'example/06_backend_auth/developer_backend/session_test.mjs',]) {expect(File('${dir.path}/$path').existsSync(), isTrue, reason: path);}@@ -228,6 +238,14 @@ void main() {for (final guide in <String>['docs/README.md','docs/component_patterns.md',+ 'docs/authentication.md',+ 'docs/backend_authentication.md',+ 'docs/manage_api_key.md',+ 'docs/sdk_contract.md',+ 'docs/diagrams.md',+ 'docs/release.md',+ 'README.md',+ 'example/06_backend_auth/README.md',]) {final content = File('${dir.path}/$guide').readAsStringSync();for (final match in RegExp(r'\]\(([^)]+)\)').allMatches(content)) {diff --git a/test/shell_scripts_test.dart b/test/shell_scripts_test.dartindex 120ae07..7d557e5 100644--- a/test/shell_scripts_test.dart+++ b/test/shell_scripts_test.dart@@ -69,6 +69,24 @@ void main() {},);+ test('backend auth reference participates in the offline Dart gates', () {+ final build = File('build.sh').readAsStringSync();+ for (final command in <String>['pub_get', 'analyze', 'test']) {+ final body = RegExp(+ 'sdk_$command\\(\\) \\{([\\s\\S]*?)\\n\\}',+ ).firstMatch(build)!.group(1)!;+ final operation = command == 'pub_get' ? 'pub get' : command;+ expect(+ body,+ contains('(cd example/06_backend_auth && sdk_flutter $operation)'),+ reason: 'Missing backend reference gate: $command',+ );+ }+ expect(build, contains('example/06_backend_auth/lib'));+ expect(build, contains('example/06_backend_auth/test'));+ expect(build, isNot(contains('node --test')));+ });+test('security commands and fixed all ordering are registered', () {final text = File('security_check.sh').readAsStringSync();for (final command in <String>[