net_kit 6.0.0-dev.2
net_kit: ^6.0.0-dev.2 copied to clipboard
Secure, flexible networking for Dart and Flutter: typed requests, per-request auth, safe token refresh, replayable streaming uploads, signed URLs, and raw HTTP.
6.0.0-dev.1 #
Pre-release of the 6.0 major version. The public API no longer exposes Dio; see
MIGRATION.md ("Migrating from 5.x to 6.0") for the full breaking-change ledger.
Breaking Changes #
package:net_kit/net_kit.dartno longer exportspackage:dio. Every type in the main entrypoint is owned by net_kit. The Dio adapter and a Dio re-export live in the newpackage:net_kit/net_kit_dio.dartNetKitManagercomposes aNetKitTransportinstead of being a Dio instance. Constructor changes:httpClientAdapter→transport,baseOptions→headers+timeout(NetKitTimeout),interceptor(Dio) →interceptors(List<NetKitInterceptor>); the deprecatedtestModeis removed;INetKitManager.baseOptionsis removed andINetKitManager.transportis added- Request methods take
headers,timeout,cancellationToken(NetKitCancellationToken),NetKitProgressCallbacks, andauthPolicyinstead ofoptions,cancelToken,ProgressCallback,containsAccessToken, andskipTokenRefresh AuthPolicy { inherit, none, required }replaces the two auth booleans.nonenever attaches the access token and never refreshes;requiredfails before sending when no token is storedallowCrossOriginRequestsnow defaults tofalse. When enabled, requests and redirects to another origin are sent without the stored headers and access tokenuploadFilestreams the file from disk (File.openRead()); it no longer reads the whole file into memory. Uploads takeNetKitFormData/NetKitMultipartFileinstead of DioFormData/MultipartFile;uploadMultipartDatagainedfieldName; thecontentTypeparameter ofuploadFormData/uploadMultipartDatais gone (the transport sets the multipart boundary)ApiExceptiongainedtype(ApiFailureType: response, transport, timeout, cancelled, auth, decoding, invalidRequest, sessionInvalidated, unknown).RequestExtraKeysis removed;RefreshTokenContentTypemoved to its own fileonRefreshFailedis removed.onSessionInvalidatedis called once, and the stored tokens are cleared, only when the refresh endpoint answers HTTP401. Every other refresh failure (offline, DNS, TLS, timeout, cancellation,429,5xx, other4xx, malformed or token-less responses) keeps the tokens, reaches the caller with its ownApiFailureTypeandApiException.fromRefresh == true, and is retried on the next401removeAccessTokenBeforeRefreshno longer deletes the stored access token; it only omits the header from the refresh request- A
401without a configuredrefreshTokenPathis now returned to the caller instead of failing with "Refresh token path is not set" - Raw transport:
RawHttpClientis an alias ofNetKitTransport,DioRawHttpClientan alias ofDioNetKitTransport(importnet_kit_dio.dart).RawHttpRequesttakestimeout: NetKitTimeoutinstead of three durations.RawHttpResponse.body→bodyBytes;header(name)returns the first value instead of comma-joining.RawHttpFailureTypegainedtls(certificate failures, previouslyconnection) andinvalidResponse(previouslyunknown) - Redirects are no longer followed by the HTTP client.
NetKitManagerfollows up to five redirects itself under the origin policy; the raw transport returns3xxunlessRawHttpRequest.followRedirectsis true
Features #
NetKitTransport: the net_kit-owned transport contract (send,sendStreamed,close).DioNetKitTransportis the default implementation; any implementation can be injectedNetKitInterceptor: application hooks (onRequest,onResponse,onError) over the final transport request, response, andApiException- Streamed responses:
NetKitTransport.sendStreamedreturnsRawHttpStreamedResponsewith the status and headers first and a back-pressured body stream; cancellation ends the stream - Replayable request bodies:
ReplayableRawHttpBody(fresh stream per attempt) andFileRawHttpBody(streams from disk).NetKitManagerreopens them for the retry after a token refresh and for307/308redirects, so large uploads never buffer NetKitFormData/NetKitMultipartFiledescribe multipart bodies without Dio; file parts are stream factories, so multipart uploads stream and replayNetKitTimeout(connect, send, receive) for the manager, per request, and on raw requests- Redirect policy: same-origin redirects keep headers;
303and301/302afterPOSTbecomeGET; cross-origin redirects are blocked by default and never forward credentials RawHttpResponse.contentLength,isSuccessful,bodyText;RawHttpRequest.copyWith,onReceiveProgress,followRedirects;RawHttpBody.isReplayableNetKitManager(logResponseBodies: ...): response bodies are kept out of the injected logger and the development log interceptor unless opted in.RedactingLogInterceptoris aNetKitInterceptorwithlogBodiesandbodySanitizer- New
NetKitErrorParamsmessages:missingAccessTokenError,timeoutError,requestCancelledError,transportError,tooManyRedirectsError,nonReplayableBodyError,sessionInvalidatedError,unverifiedRedirectError RawHttpResponse.redirected/RawHttpStreamedResponse.redirectedreport redirects the HTTP client followed on its own (browsers always do)NetKitManager(sensitiveQueryParameters: ...)andRedactingLogInterceptor(sensitiveQueryParameters: ...)
Security #
- Refresh requests are pinned to the API origin:
allowCrossOriginRequests,onBeforeRefreshRequest, interceptors, and redirects cannot send the refresh credential to another origin. On the web, a refresh response that came from a browser-followed redirect is rejected - Origin rules are re-applied after interceptors run, so an interceptor cannot carry stored credentials to another origin
- Logged URLs redact credential-like query parameters (signed URL signatures, OAuth codes, API keys, tokens) and user-info
- A refresh result that arrives after the application stored new credentials is discarded instead
of overwriting them, and a refresh
401for superseded credentials does not end the new session - Cancelling a request that waits for a refresh releases it immediately without cancelling the shared refresh
Improvements #
- Timeouts, cancellation, connection, and TLS failures are reported as typed
ApiExceptions instead of a generic parse error uploadMultipartDatasends a real multipart body (the file underfieldName) instead of the string form of the file object
5.5.0 #
Features #
- Added
RawHttpClient, an isolated, transport-independent client for raw HTTP to absolute URLs (for example signed object-storage uploads). It sends only caller-owned headers, never attaches theNetKitManageraccess token, never refreshes tokens, never retries, and returns every HTTP status (including 401 and 5xx) as aRawHttpResponse; only transport failures throwRawHttpException DioRawHttpClientis the built-in implementation; application code should depend onRawHttpClientso the transport can change without caller changesStreamRawHttpBodystreams request bodies (for exampleFile.openRead()) without buffering them, withContent-Length, upload progress (onSendProgress), and timeoutsRawHttpCancellationTokencancels raw requests without exposing Dio'sCancelToken. One token may be shared by several in-flight requests; cancellation is idempotent, a cancelled token fails new requests before sending, and completed requests release their bindingRawHttpMethodcoversGET,POST,PUT,PATCH,DELETE,HEAD, andOPTIONSRawHttpResponse.headerValues(name)returns repeated header values unjoined (for exampleSet-Cookie); response header collections are unmodifiable- Optional cross-origin protection:
NetKitManager(allowCrossOriginRequests: false)rejects requests whose absolute URL has a different origin thanbaseUrlbefore anything is sent, so the access token cannot reach an unrelated host. AddsNetKitErrorParams.crossOriginRequestBlockedError. The default (true) keeps 5.4.x behavior NetKitManager(sensitiveHeaders: [...])adds header names to redact from development HTTP logs
Improvements #
- Compatible with the whole
dio: ^5.8.0range including Dio 5.10+ (DioExceptionType.transformTimeoutmaps toRawHttpFailureType.timeout); new Dio failure types no longer break compilation - Development HTTP logging (
logInterceptorEnabled) now uses a redacting interceptor instead of Dio'sLogInterceptor: values ofAuthorization,Proxy-Authorization,Cookie,Set-Cookie, common API-key/token headers, andsensitiveHeadersprint as[REDACTED], and request/response bodies are not printed - In dev mode, a logger warning is emitted when the access token is about to be sent to a cross-origin absolute URL
- Documented that
uploadFilereads the whole file into memory (so the request can be replayed after a token refresh); large or external uploads should useRawHttpClientwithStreamRawHttpBody - Resolved
parameter_assignmentsanalyzer findings
Bug Fixes #
uploadRawDatasent aList<int>that was not aUint8Listas text instead of raw bytes; the payload is now always sent as binary
5.4.1 #
Bug Fixes #
- Fix
requestListtreating HTTP 200 with an empty JSON array ([]) as an empty response body; empty lists are now parsed as[]instead of throwingemptyResponseBodyError
5.4.0 #
Features #
- Completer-based single-flight token refresh (concurrent 401s share one refresh)
- Per-request
skipTokenRefresh,allowRetryOn401, and optionalidempotencyKey - RFC 9110-safe default: POST/PATCH are not replayed after 401 unless
allowRetryOn401: true - Optional
refreshTokenContentType: formUrlEncodedfor OAuth backends requestVoidaccepts 204;requestModel/requestListthrowemptyResponseBodyErroron 204/empty body- Added
uploadRawDatafor direct binary uploads (application/octet-stream) without multipart encoding - Added
uploadFileconvenience method to read a file from disk and upload as raw bytes (IO platforms only)
Improvements #
- Renamed
testModetodevModeonNetKitManagerandNetKitParamsfor clarity - Retry requests merge per-request headers and forward
cancelToken/ progress callbacks - Refresh requests tagged with internal
__isRefreshRequestguard; normalized refresh path matching devModelogs a warning when access tokens contain whitespace (RFC 6750)- Clarify that
loggerEnabledandlogInterceptorEnabledonly take effect whendevModeis true - Added
invalidTokenResponseErrortoNetKitErrorParamsfor refresh token parse failures - Preserve wrapped
ApiExceptionmessages when convertingDioExceptiontoApiException - Run CI
dart analyzefrompackages/net-kit - Backfill CHANGELOG entries for 5.3.1–5.3.4
- Correct misleading docs (retry claim,
setAccessTokenexample,MIGRATION.mdtoken mapping)
Bug Fixes #
- Fix runtime crash when
containsAccessToken: falseis used with caller-providedMap<String, String>headers - Fix refresh failure propagation (
Completer.completeErrorno longer leaks uncaught errors) - Fix retry limit so retried 401s do not trigger a second refresh
- Propagate refresh/retry
DioExceptionresponses correctly to callers - Fix metadata map mutation in
requestModelMetaandrequestListMeta(response maps are no longer modified in place) - Fix
useDataKey: falsehandling on meta endpoints to match non-meta methods and README - Prevent double
Bearerprefix whensetAccessTokenis called with a token that already includes the prefix - Fix header race when
containsAccessToken: falseby applying token omission per request instead of mutating shared headers - Parse
List<dynamic>error message arrays inApiException.fromJson - Validate HTTP status codes after token-refresh retries (consistent with
_sendRequest) - Fail token refresh immediately with
noInternetErrorwheninternetStatusStreamreports offline - Register the user-provided
interceptorinNetKitManager(was stored but never added to Dio) - Validate HTTP status codes in
uploadMultipartDataanduploadFormData(consistent with other request methods) - Fail token refresh when the refresh response is missing a valid access token (previously succeeded silently)
- Remove fragile
package:dio/src/*re-exports; public Dio types remain available viapackage:dio/dio.dart
Deprecations #
testModeis deprecated in favor ofdevMode(alias retained for one release; removed in a future major version)
See MIGRATION.md for auth refresh and devMode migration details.
5.3.4-dev #
Pre-release for 5.3.4.
5.3.3-dev #
Pre-release for 5.3.3.
5.3.2-dev #
Pre-release for 5.3.2.
5.3.1 #
Patch release.
5.3.0 #
New Features #
- Added
useDataKeyparameter to all request methods (requestModel,requestModelMeta,requestList,requestListMeta,uploadMultipartData,uploadFormData) - The
useDataKeyparameter allows you to control whether to use the configureddataKeywrapper for individual requests - Default value is
trueto maintain backward compatibility - When set to
false, the response data will be used directly without dataKey extraction - This is useful when you have different API endpoints that return data in different formats
Improvements #
- Enhanced flexibility for handling APIs with different response structures
- Better control over data extraction on a per-request basis
5.2.5 #
- updated sponsors
5.2.1 #
- Fixed issue with
NetKitManagernot properly handling theloggerEnabledoption.
5.2.0 #
- Added
loggerEnabledoption toNetKitManagerto enable or disable logging.
5.1.2 #
- Added more tests to make sure Refresh Token works as intended.
5.1.1 #
- updated README regarding
VoidModelusage inUpload
5.1.0 #
- update type check for VoidModel in UploadManagerMixin
5.0.0 #
Breaking Changes #
- refresh token request is now sent via body. Reference: Refreshing an Access Token
- removal:
refreshTokenHeaderKeyis removed since refreshToken should not be in the header. Reference: Refreshing an Access Token
New Features #
- Added
removeAccessTokenBeforeRefresh: A new top-level option in NetKitManager to remove the access token from headers during a token refresh. - Added
accessTokenPrefix: Allows you to define a custom token prefix (e.g., Bearer, Token) when setting the access token. - Introduced
onBeforeRefreshRequestcallback: Lets you modify the refresh token request before it is sent — useful for injecting custom headers or modifying the request body. IntroducedNetKitRequestOptions: A new abstraction to simplify and standardize refresh token request configuration. - Introduced
onRefreshFailedcallback: This callback is triggered when the refresh token request fails. It provides a way to handle errors or perform specific actions when the refresh token process encounters issues. - Added
metadataDataKey: Enables support for parsing the actual data nested inside metadata wrappers from API responses. - Added
requestModelMetaandrequestListMetamethods:
Improvements #
Improved error handling in ApiException
- Added
debugMessageanderrorfields to provide more detailed diagnostics. - Better support for SocketException and network-related errors via
ApiException.fromJson
4.0.0 #
Breaking change: removed authenticate methodBreaking change: refresh tokens are now parsed from only body, since it is a common practice to return the new access token and, if needed, the new refresh token via body for more security. If you want to handle the refresh token manually, you can use add custom interceptor to handle the refresh token. **Reference **: Issuing an Access Token: Successful ResponseBreaking change: updatedaccessTokenKeyasaccessTokenHeaderKeyBreaking change: updatedrefreshTokenKeyasrefreshTokenHeaderKey- added
accessTokenBodyKeytoNetKitManagerto parse the access token from the body - added
refreshTokenBodyKeytoNetKitManagerto parse the refresh token from the body
3.6.0 #
- deprecated
authenticatemethod - updated the code for the latest lint rules
3.5.1 #
- improved error handling in uploadMultipartData and uploadMultipartDataList methods
3.5.0 #
- fixed: uploadMultipartData and uploadMultipartDataList methods do not cover all error handling
3.4.3 #
- configured import of http-adapter to support wasm
3.4.2 #
- added @override to _logger in NetKitManager
3.4.1 #
- added logger.error in _sendRequest method
3.4.0 #
Note: This release has breaking changes.
logLevelis removed, since INetKitLogger instance injected to the NetKitManager. This is done to provide more flexibility to the developers to use their own logger.loggerEnabledis renamed tologInterceptorEnabledinNetKitManagerto provide more clarity.- added
loggerparameter to theNetKitManagerto provide more flexibility to the developers to use their own logger.
3.3.4 #
- authentication issue fixed
3.3.2 #
- exported
VoidModelclass
3.3.1 #
- fixed
authenticationissue while parsing the response
3.3.0 #
- added
containsAccessTokento requests
3.2.0 #
- fixed bug in _retryRequest with FormData
3.1.0 #
- added
VoidModelclass for void responses - added
uploadMultipartDatamethod to upload files - internal refactoring
3.0.9-dev #
- internal refactoring
3.0.8-dev #
- added
VoidModelclass
3.0.2-dev #
- added
uploadMultipartDatamethod
3.0.1 #
- updated README.md
3.0.0 #
Note: This release has breaking change.
Breaking change: Renamed methodsaddBearerTokentosetAccessTokenaddRefreshTokentosetRefreshTokenremoveBearerTokentoremoveAccessToken
Feature: AddedrefreshTokenfeature. Refresh token is automatically refreshed when the access token is expired. Just addrefreshTokenPathto theNetKitManagerand it will automatically refresh the token. Note: the refresh token API in backend should return the new access token and, if needed, the new refresh token via headers for more security. If you want to handle the refresh token manually, you can use add custom interceptor to handle the refresh token.
2.4.5-dev #
- updated error handling
2.4.4-dev #
- added loggers in error handling interceptor
- fixed issue in error handling interceptor
2.4.0 #
- added
authenticatemethod and provided the example in README.md - added
addRefreshTokenandremoveRefreshTokenmethods toNetKitManager - updated documentation on how to use
authenticatemethod
2.3.3-dev #
- updated documentation on how to use
authenticatemethod
2.3.2-dev #
- exported
AuthTokenModelclass
2.3.1-dev #
- added
authenticatemethod and provided the example in README.md - added
addRefreshTokenandremoveRefreshTokenmethods toNetKitManager
2.3.0 #
- fixed error
Cannot read properties of undefined (reading 'new')in web with workaround - added integration test for -release tags
2.2.0-dev #
- fixed error
Cannot read properties of undefined (reading 'new')in web with workaround - added flutter-project to test web
2.1.2 #
- updated NetKitLogger to use only required imports from logger
2.1.0 #
Note: This release has breaking change.
- downgraded SDK version to support more versions
- Breaking change: body's type parameter in
requestModelandrequestListmethods is changed toMap<String, dynamic>
2.0.1 #
- updated README.md
2.0.0 #
Note: This release has breaking changes.
- Removed the generic type parameter
<T>fromINetKitModel. When you extendINetKitModel, you don't need to provide the generic type parameter anymore. - updated documentations
2.0.0-dev.2 #
- updated documentations
2.0.0-dev.1 #
Note: This release has breaking changes.
- Removed the generic type parameter
<T>fromINetKitModel. When you extendINetKitModel, you don't need to provide the generic type parameter anymore.
1.8.3 #
- Exported
NetKitErrorParamsclass
1.8.2 #
- exported
LogLevelenum
1.8.1 #
- fixed data is not parsed to json.
1.8.0 #
- added JsonUnsupportedObjectError to handle unsupported objects in json
- added String for error message:
JsonUnsupportedObjectError
1.7.0 #
- updated error handling to provide more information
1.6.2 #
- added more integration test cases
- added missing documentations
1.6.1 #
- added integration test from typicode
1.6.0 #
- log messages improved
1.6.0-dev.1 #
- updated HttpClientAdapter to support web
- added log messages
1.5.3 #
- added example
- updated error handling
1.5.2 #
- updated README.md
- declared platform supports
1.5.1 #
- updated README.md
- declared
websupport
1.5.0 #
- Stable: Added
internetStatusStreamto listen to the internet status
1.5.0-dev.2 #
- fixed no internet connection handler
1.5.0-dev.1 #
- Added
internetStatusStreamto listen to the internet status
1.4.1 #
Note: This release has breaking changes.
NetKitErrorParamsintroduced to handle error messages and status codes. It is required to provide internationalized error messages.errorMessageKeyin the NetKitManager key is moved toNetKitErrorParamsclass asmessageKeyerrorStatusCodeKeyin the NetKitManager key is moved toNetKitErrorParamsclass asstatusCodeKey
1.3.1 #
- added tasks to be done in the future
1.3.0 #
- Equality operator removed from
ApiExceptionclass - Updated README.md with correct examples
- Empty
jsonerror handling improved
1.2.2 #
- Equality operator added to
ApiExceptionclass
1.2.1 #
- error handler updated
1.2.0 #
- error handler updated
1.1.1 #
- exported dio classes
1.1.0 #
- updated README.md
- exported ApiException
- updated documentation
1.0.0 #
Note: This release has breaking changes.
- Return type of
requestModelchanged toFuture<T> - Return type of
requestListchanged toFuture<List<T>> - Return type of
requestVoidchanged toFuture<void> ApiExceptionis introduced as an exception that is thrown when an error occurs during the request
0.2.2 #
- integration tests added
- unit tests updated
- error handler improved
0.2.1 #
- updated README.md
0.2.0 #
- added documentations for public methods
- equatable dependency removed
0.1.3 #
- updated README.md: added image
- web dependency added
0.1.2 #
- fixed homepage and issue_tracker
0.1.1 #
- Updated README.md
0.1.0 #
- Initial release.