diff --git a/CHANGELOG.md b/CHANGELOG.md index 13ef9fb..40b8fa3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - macOS 12.0 or later is now supported. Authentication opens in `ASWebAuthenticationSession`, the same system sheet as on iOS, and the callback returns to the app without registering the URL scheme in `Info.plist`. The app needs the `com.apple.security.network.client` and `keychain-access-groups` entitlements; see [Platform Setup](https://librarylibrarian.github.io/misskey_auth/platform-setup#macos). +- `MisskeyTokenRevocationClient` revokes an access token on the server through `/api/i/revoke-token`, available for app tokens from Misskey 2026.9.0. It works for MiAuth and OAuth tokens regardless of their permissions, and it does not touch stored tokens, so it can be used with your own storage. `revoke` never throws; it returns a `TokenRevocationResult` whose `status` is `revoked`, `alreadyInvalid` (the server no longer recognizes the token), `unsupported` (servers before 2026.9.0), or `failed`. The request is not retried, and an optional `timeout` limits the whole request, including the interceptors of an injected `Dio`. Responses are classified by their status and Misskey error code, and by status alone when the body is not valid JSON. The result never includes the token, even when the server or an interceptor echoes it in an error message. Pass a token issued to an app through MiAuth or OAuth: for the session token of the Misskey web client, the server answers 204 without revoking it. +- `signOut` and `signOutAll` accept a `mode` and a `timeout`. `SignOutMode.revokeAndDelete` (the default) revokes the token and then deletes it from the device whatever the result; `SignOutMode.revokeOrKeep` deletes it only when the server confirms that the token is invalid, so tokens on servers that do not support revocation are kept; `SignOutMode.localOnly` deletes it without contacting the server. `timeout` limits the revocation request; for `signOutAll`, all requests share one deadline counted from the call. Reading and deleting stored tokens is not cut off by the timeout. A token that is not stored or cannot be read is deleted without revocation. `signOutAll` revokes all accounts in parallel. A token saved again for the same account while revocation is in progress is not deleted. +- `MisskeyAuthManager` accepts a `revocation` client. By default it uses the manager's `dio`, so the manager's timeouts also apply to revocation. + +### Changed +- **Breaking:** `signOut` and `signOutAll` now revoke the token on the server before deleting it from the device, so they make a network request and can take as long as the request timeouts. The device copy is still deleted even if revocation fails or the server does not support it. To keep the previous behavior, pass `mode: SignOutMode.localOnly`. +- **Breaking:** `signOut` now returns `Future` and `signOutAll` returns `Future>`, which report the revocation result and whether the token was deleted. Code that only awaits them keeps compiling; classes that implement or mock `MisskeyAuthManager` must update these signatures. + +### Fixed +- `SecureTokenStore.list` no longer throws when a stored token cannot be read or is corrupted. The account is listed without `userName` and `createdAt`, so it can still be signed out. Errors reading the account index itself are still thrown. ## [0.2.0-beta.2] - 2026-09-26 diff --git a/README.de.md b/README.de.md index 78a76c0..ac66440 100644 --- a/README.de.md +++ b/README.de.md @@ -19,6 +19,7 @@ Eine Flutter-Bibliothek zur Authentifizierung bei [Misskey](https://misskey-hub. - Callback zur App über ein benutzerdefiniertes URL-Schema - Sichere Token-Speicherung mit `flutter_secure_storage` - Token-Speicherung für mehrere Konten und Wechsel des aktiven Kontos +- Widerruf des Tokens auf dem Server beim Abmelden (Misskey 2026.9.0 und höher) - `MisskeyAuthManager`, eine High-Level-API, die Authentifizierungsabläufe ausführt und Tokens speichert - iOS, Android und macOS diff --git a/README.fr.md b/README.fr.md index 2fb84a9..99ab373 100644 --- a/README.fr.md +++ b/README.fr.md @@ -19,6 +19,7 @@ Une bibliothèque Flutter pour l'authentification auprès des serveurs [Misskey] - Retour vers l'application via un schéma d'URL personnalisé - Stockage sécurisé des jetons avec `flutter_secure_storage` - Stockage des jetons de plusieurs comptes et changement du compte actif +- Révocation du jeton sur le serveur lors de la déconnexion (Misskey 2026.9.0 et ultérieures) - `MisskeyAuthManager`, une API de haut niveau qui exécute les flux d'authentification et enregistre les jetons - iOS, Android et macOS diff --git a/README.ja.md b/README.ja.md index 5f69a03..2ec4536 100644 --- a/README.ja.md +++ b/README.ja.md @@ -19,6 +19,7 @@ - カスタム URL スキームによるアプリへのコールバック - `flutter_secure_storage` を使用した安全なトークン保存 - 複数アカウントのトークン保存と、アクティブなアカウントの切り替え +- サインアウト時のサーバー側でのトークン失効(Misskey 2026.9.0 以降) - 認証の実行とトークンの保存を仲介する高レベル API `MisskeyAuthManager` - iOS、Android、macOS diff --git a/README.ko.md b/README.ko.md index 54af101..dc29136 100644 --- a/README.ko.md +++ b/README.ko.md @@ -19,6 +19,7 @@ - 사용자 지정 URL 스킴을 통한 앱 콜백 - `flutter_secure_storage`를 사용한 안전한 토큰 저장 - 여러 계정의 토큰 저장 및 활성 계정 전환 +- 로그아웃 시 서버에서 토큰 폐기(Misskey 2026.9.0 이상) - 인증 흐름 실행과 토큰 저장을 중개하는 고수준 API `MisskeyAuthManager` - iOS, Android 및 macOS diff --git a/README.md b/README.md index f6794e2..f292472 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ A Flutter library for authenticating with [Misskey](https://misskey-hub.net/) se - Callbacks to the app through a custom URL scheme - Secure token storage using `flutter_secure_storage` - Token storage for multiple accounts and switching the active account +- Revoking the token on the server when signing out (Misskey 2026.9.0 and later) - `MisskeyAuthManager`, a high-level API that runs the flows and saves tokens - iOS, Android, and macOS diff --git a/README.zh-Hans.md b/README.zh-Hans.md index 45be95c..3dc567d 100644 --- a/README.zh-Hans.md +++ b/README.zh-Hans.md @@ -19,6 +19,7 @@ - 通过自定义 URL scheme 回调到应用 - 使用 `flutter_secure_storage` 安全保存令牌 - 保存多个账户的令牌并切换当前账户 +- 退出登录时在服务器上撤销令牌(Misskey 2026.9.0 及更高版本) - `MisskeyAuthManager`:高层 API,负责执行身份验证流程并保存令牌 - iOS、Android 和 macOS diff --git a/docs/docs/error-handling.md b/docs/docs/error-handling.md index 44330d8..11fe97a 100644 --- a/docs/docs/error-handling.md +++ b/docs/docs/error-handling.md @@ -64,6 +64,14 @@ Each exception has: | `MiAuthSessionInvalidException` | The callback is for a different session, or the check API returned 404 or 410 | | `MiAuthCheckFailedException` | The check API returned another error status | +### Token Revocation + +| Exception | Returned when | +|---|---| +| `TokenRevocationException` | The server answered the revocation request with an error status or another unexpected response. `details` contains the HTTP status and, if any, the error from the server | + +Revocation never throws. `signOut`, `signOutAll`, and `MisskeyTokenRevocationClient.revoke` return the cause in `TokenRevocationResult.error`, which can also be a `NetworkException` or a `ResponseParseException`. These exceptions carry no `originalException`, so that the token in the request is not exposed. See [Signing Out](./token-storage.md#signing-out). + ### Not Thrown by the Current Version `InvalidAuthConfigException`, `SecureStorageException`, and `MiAuthNotSupportedException` are defined but not thrown by the current version. @@ -74,10 +82,13 @@ Each exception has: `loginWithOAuth` and `loginWithMiAuth` save the token first and then make the account active. If only the second step fails, the token stays saved but the account is not active. +`signOut` and `signOutAll` do not throw when a stored token cannot be read; they delete it without revocation. They do throw when deleting the token fails. + ## Retries - Fetching the OAuth server information and calling `/api/i` are retried up to three attempts in total, on timeouts, connection errors, other transport errors, and HTTP 429, 500, 502, 503, and 504. - The token exchange and the MiAuth check API are not retried. An authorization code and a MiAuth session can be used only once, and the server may have completed the request even if the response was lost. Start the authentication again from the beginning. +- Token revocation is not retried. See [Timeout and Retries](./token-storage.md#timeout-and-retries). ## When Login Fails After Authentication diff --git a/docs/docs/token-storage.md b/docs/docs/token-storage.md index 5753723..64060af 100644 --- a/docs/docs/token-storage.md +++ b/docs/docs/token-storage.md @@ -23,15 +23,103 @@ final active = await auth.getActive(); await auth.clearActive(); // Sign out -await auth.signOut(key); // Deletes the token of one account -await auth.signOutAll(); // Deletes the tokens of all accounts +await auth.signOut(key); // Revokes and deletes the token of one account +await auth.signOutAll(); // Revokes and deletes the tokens of all accounts ``` -Signing out deletes the token from the device only. It does not revoke the token on the server. +## Signing Out + +Signing out revokes the token on the server and then deletes it from the device. Revocation requires Misskey 2026.9.0 or later, which lets an app token revoke itself through `/api/i/revoke-token`. It works for MiAuth and OAuth tokens, whatever their permissions. + +```dart +final result = await auth.signOut(key); +final revocation = result.revocation; +if (revocation == null) { + // Revocation was not attempted. See result.skipReason. +} else if (revocation.isInvalidated) { + // revoked or alreadyInvalid: the token can no longer be used on the server. +} else if (revocation.status == TokenRevocationStatus.unsupported) { + // The server is older than 2026.9.0. The token stays valid there. +} else { + // failed: network error, timeout, or an unexpected response. +} +``` + +### Modes + +Pass `mode` to choose what happens to the token on the device: + +| `SignOutMode` | Revokes | Deletes from the device | +|---|---|---| +| `revokeAndDelete` (default) | Yes | Always, whatever the revocation result | +| `revokeOrKeep` | Yes | Only when the result is `revoked` or `alreadyInvalid` | +| `localOnly` | No | Always | + +With `revokeOrKeep`, a token that could not be revoked stays saved, so the user can try again later. A server that does not support revocation always returns `unsupported`, and an account that the server refuses for another reason, such as a suspended one, may fail every time. To remove such accounts from the device, sign out again with `SignOutMode.localOnly`. + +If the token is not stored or cannot be read, for example because the stored data is corrupted, it is deleted in every mode without revocation. + +### Results + +`signOut` returns a `SignOutResult`, and `signOutAll` returns one for each account in the order of `listAccounts`: + +| Field | Meaning | +|---|---| +| `key` | The account | +| `revocation` | The `TokenRevocationResult`, or `null` if revocation was not attempted | +| `skipReason` | Why revocation was not attempted: `localOnly`, `noStoredToken`, or `unreadableToken`. `null` if it was attempted | +| `deleted` | Whether the token was deleted from the device | + +`TokenRevocationResult` has: + +| Field | Meaning | +|---|---| +| `status` | `revoked`, `alreadyInvalid`, `unsupported`, or `failed` | +| `isInvalidated` | `true` for `revoked` and `alreadyInvalid` | +| `statusCode` | The HTTP status, or `null` if no response was received | +| `errorCode` | The Misskey error code, such as `RATE_LIMIT_EXCEEDED`, if any | +| `error` | The cause for `unsupported` and `failed`: usually `TokenRevocationException` for an error or unexpected response, and `NetworkException` for a network error or timeout | + +`alreadyInvalid` means that the server did not recognize the token: it was already revoked, or the account was deleted. It is treated like `revoked`. + +Revocation failures are reported in the result and never thrown. Errors from deleting the token on the device are thrown as before; `signOutAll` tries to delete every account first and then throws the first error. + +`deleted` is `false` in two cases: `revokeOrKeep` kept the token, or a new token was saved for the same account while revocation was in progress, for example because the user signed in again. The new token is not deleted, because it was never revoked. + +### Timeout and Retries + +Revocation is not retried. Without a `timeout`, a request that does not respond waits for the request timeouts (see [Timeouts](#timeouts)). Pass `timeout` to limit it: + +```dart +await auth.signOut(key, timeout: const Duration(seconds: 5)); +await auth.signOutAll(timeout: const Duration(seconds: 5)); +``` + +`signOutAll` revokes all accounts in parallel, and all requests share one deadline counted from the call. Reading and deleting stored tokens is not cut off by the timeout. A request that runs out of time is reported as `failed`. The server may still have revoked the token: if the token was kept, for example by `revokeOrKeep`, revoking it again reports `alreadyInvalid`. + +### Revoking Without the Manager + +If you store tokens yourself, use `MisskeyTokenRevocationClient` directly. It revokes the token on the server and does not touch any storage: + +```dart +final revocation = MisskeyTokenRevocationClient(); +final result = await revocation.revoke( + host: 'misskey.io', + accessToken: token, + timeout: const Duration(seconds: 5), +); +if (result.isInvalidated) { + // Delete the token from your storage. +} +``` + +`revoke` never throws and returns the same `TokenRevocationResult`. The client sends the token in the request body. If you pass your own `Dio`, its interceptors can see the token, so do not log request bodies. + +Pass a token issued to an app through MiAuth or OAuth. The session token that the Misskey web client uses is not an app token: the server answers 204 without revoking it, so the result is `revoked` even though the token stays valid. ## Timeouts -`MisskeyAuthManager.defaultInstance()` uses the default timeouts: 10 seconds to connect, and 20 seconds each to send and receive. To change them, build the manager yourself. The timeouts of the manager apply only to its own request to `/api/i`, so pass them to each client as well: +`MisskeyAuthManager.defaultInstance()` uses the default timeouts: 10 seconds to connect, and 20 seconds each to send and receive. To change them, build the manager yourself. The timeouts of the manager apply to its own requests, `/api/i` and token revocation, so pass them to each client as well: ```dart const timeout = Duration(seconds: 30); @@ -43,7 +131,7 @@ final auth = MisskeyAuthManager( ); ``` -The constructors accept `connectTimeout`, `sendTimeout`, and `receiveTimeout`. They also accept a `dio`. The clients apply the timeout arguments to a `Dio` that you pass, but `MisskeyAuthManager` ignores them when `dio` is given; configure that `Dio` directly. +The constructors accept `connectTimeout`, `sendTimeout`, and `receiveTimeout`. They also accept a `dio`. `MisskeyOAuthClient` and `MisskeyMiAuthClient` apply the timeout arguments to a `Dio` that you pass. `MisskeyTokenRevocationClient` applies them only to its own requests and leaves that `Dio` unchanged. `MisskeyAuthManager` ignores them when `dio` is given; configure that `Dio` directly. To use a different revocation client, pass it as `revocation`. ## Models diff --git a/docs/docs/upgrading.md b/docs/docs/upgrading.md index 98e997c..5638965 100644 --- a/docs/docs/upgrading.md +++ b/docs/docs/upgrading.md @@ -15,6 +15,34 @@ title: Upgrading Keep `android.builtInKotlin=false` and `android.newDsl=false` while the stable `flutter_web_auth_2` release still applies the Kotlin Android plugin. Retain that plugin, but replace `android.kotlinOptions` with `kotlin.compilerOptions` to configure its JVM target. Future Flutter versions may require built-in Kotlin support from dependencies. +## Upgrading from 0.2.0-beta.2 + +### Signing Out Revokes the Token + +`signOut` and `signOutAll` now revoke the token on the server before deleting it from the device. They make a network request, so they can take as long as the request timeouts. The token is still deleted from the device when revocation fails or the server does not support it. + +- To keep the previous behavior, pass `mode: SignOutMode.localOnly`. +- To limit the wait, pass `timeout`. +- Servers before Misskey 2026.9.0 do not support revocation. Their tokens stay valid on the server, as before. + +See [Signing Out](./token-storage.md#signing-out). + +### New Return Types + +`signOut` now returns `Future`, and `signOutAll` returns `Future>`. Code that only awaits them does not need changes. Classes that implement or mock `MisskeyAuthManager` must update the signatures: + +```dart +Future signOut( + AccountKey key, { + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +Future> signOutAll({ + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +``` + ## Upgrading to 0.2.0-beta.1 ### Android Users Must Sign In Again diff --git a/docs/i18n/de/docusaurus-plugin-content-docs/current/error-handling.md b/docs/i18n/de/docusaurus-plugin-content-docs/current/error-handling.md index df202ca..5558911 100644 --- a/docs/i18n/de/docusaurus-plugin-content-docs/current/error-handling.md +++ b/docs/i18n/de/docusaurus-plugin-content-docs/current/error-handling.md @@ -64,6 +64,14 @@ Jede Ausnahme hat die folgenden Eigenschaften. | `MiAuthSessionInvalidException` | Der Callback gehört zu einer anderen Sitzung oder die Prüf-API hat 404 oder 410 zurückgegeben. | | `MiAuthCheckFailedException` | Die Prüf-API hat einen anderen Fehlerstatus zurückgegeben. | +### Token-Widerruf + +| Ausnahme | Rückgabebedingung | +|---|---| +| `TokenRevocationException` | Der Server hat die Widerrufsanfrage mit einem Fehlerstatus oder einer anderen unerwarteten Antwort beantwortet. `details` enthält den HTTP-Status und gegebenenfalls den vom Server gemeldeten Fehler. | + +Der Widerruf löst nie eine Ausnahme aus. `signOut`, `signOutAll` und `MisskeyTokenRevocationClient.revoke` geben die Ursache in `TokenRevocationResult.error` zurück. Dabei kann es sich auch um eine `NetworkException` oder eine `ResponseParseException` handeln. Diese Ausnahmen enthalten keine `originalException`, damit das Token in der Anfrage nicht offengelegt wird. Siehe [Abmelden](./token-storage.md#signing-out). + ### In der aktuellen Version nicht ausgelöste Ausnahmen `InvalidAuthConfigException`, `SecureStorageException` und `MiAuthNotSupportedException` sind definiert, werden in der aktuellen Version jedoch nicht ausgelöst. @@ -74,10 +82,13 @@ Jede Ausnahme hat die folgenden Eigenschaften. `loginWithOAuth` und `loginWithMiAuth` speichern das Token und aktivieren anschließend das Konto. Schlägt nur die Aktivierung des Kontos fehl, bleibt das Token gespeichert, das Konto wird jedoch nicht aktiviert. +`signOut` und `signOutAll` lösen keine Ausnahme aus, wenn ein gespeichertes Token nicht gelesen werden kann; sie löschen es ohne Widerruf. Schlägt das Löschen des Tokens fehl, lösen sie dagegen eine Ausnahme aus. + ## Wiederholungsversuche - OAuth-Abrufe der Serverinformationen und Aufrufe von `/api/i` werden bei Timeouts, Verbindungsfehlern, sonstigen Kommunikationsfehlern und HTTP 429, 500, 502, 503 oder 504 insgesamt bis zu dreimal versucht. - Der Token-Austausch und die MiAuth-Prüf-API werden nicht erneut versucht. Autorisierungscodes und MiAuth-Sitzungen können nur einmal verwendet werden. Selbst wenn die Antwort verloren geht, kann der Server den Vorgang bereits abgeschlossen haben. Starten Sie die Authentifizierung von vorn. +- Der Token-Widerruf wird nicht erneut versucht. Siehe [Timeout und Wiederholungsversuche](./token-storage.md#timeout-and-retries). ## Wenn die Anmeldung nach der Authentifizierung fehlschlägt diff --git a/docs/i18n/de/docusaurus-plugin-content-docs/current/token-storage.md b/docs/i18n/de/docusaurus-plugin-content-docs/current/token-storage.md index 1453e07..9bcf788 100644 --- a/docs/i18n/de/docusaurus-plugin-content-docs/current/token-storage.md +++ b/docs/i18n/de/docusaurus-plugin-content-docs/current/token-storage.md @@ -23,15 +23,103 @@ final active = await auth.getActive(); await auth.clearActive(); // Abmelden -await auth.signOut(key); // Token für ein Konto löschen -await auth.signOutAll(); // Token für alle Konten löschen +await auth.signOut(key); // Token für ein Konto widerrufen und löschen +await auth.signOutAll(); // Token für alle Konten widerrufen und löschen ``` -Beim Abmelden wird nur das Token auf dem Gerät gelöscht. Das Token auf dem Server wird dadurch nicht widerrufen. +## Abmelden {#signing-out} -## Timeouts +Beim Abmelden wird das Token auf dem Server widerrufen und anschließend vom Gerät gelöscht. Der Widerruf erfordert Misskey 2026.9.0 oder höher; ab dieser Version kann sich ein App-Token über `/api/i/revoke-token` selbst widerrufen. Das funktioniert für MiAuth- und OAuth-Token, unabhängig von ihren Berechtigungen. -`MisskeyAuthManager.defaultInstance()` verwendet die Standard-Timeouts (Verbindung: 10 Sekunden, Senden und Empfangen jeweils 20 Sekunden). Wenn Sie diese ändern möchten, erstellen Sie `MisskeyAuthManager` selbst. Die Timeouts von `MisskeyAuthManager` gelten nur für die von ihm selbst ausgeführte Anfrage an `/api/i`. Übergeben Sie die Timeouts daher auch an die einzelnen Clients. +```dart +final result = await auth.signOut(key); +final revocation = result.revocation; +if (revocation == null) { + // Widerruf wurde nicht versucht. Siehe result.skipReason. +} else if (revocation.isInvalidated) { + // revoked oder alreadyInvalid: Das Token kann auf dem Server nicht mehr verwendet werden. +} else if (revocation.status == TokenRevocationStatus.unsupported) { + // Der Server ist älter als 2026.9.0. Das Token bleibt dort gültig. +} else { + // failed: Netzwerkfehler, Timeout oder unerwartete Antwort. +} +``` + +### Modi + +Mit `mode` legen Sie fest, was mit dem Token auf dem Gerät geschieht: + +| `SignOutMode` | Widerruf | Löschen vom Gerät | +|---|---|---| +| `revokeAndDelete` (Standard) | Ja | Immer, unabhängig vom Ergebnis des Widerrufs | +| `revokeOrKeep` | Ja | Nur wenn das Ergebnis `revoked` oder `alreadyInvalid` ist | +| `localOnly` | Nein | Immer | + +Mit `revokeOrKeep` bleibt ein Token, das nicht widerrufen werden konnte, gespeichert, sodass der Benutzer es später erneut versuchen kann. Ein Server, der den Widerruf nicht unterstützt, gibt immer `unsupported` zurück, und bei einem Konto, das der Server aus einem anderen Grund ablehnt, etwa einem gesperrten Konto, kann der Widerruf jedes Mal fehlschlagen. Um solche Konten vom Gerät zu entfernen, melden Sie sie erneut mit `SignOutMode.localOnly` ab. + +Wenn das Token nicht gespeichert ist oder nicht gelesen werden kann, zum Beispiel weil die gespeicherten Daten beschädigt sind, wird es in jedem Modus ohne Widerruf gelöscht. + +### Ergebnisse + +`signOut` gibt ein `SignOutResult` zurück, `signOutAll` eines pro Konto in der Reihenfolge von `listAccounts`: + +| Feld | Bedeutung | +|---|---| +| `key` | Das Konto | +| `revocation` | Das `TokenRevocationResult` oder `null`, wenn kein Widerruf versucht wurde | +| `skipReason` | Der Grund, warum kein Widerruf versucht wurde: `localOnly`, `noStoredToken` oder `unreadableToken`. `null`, wenn er versucht wurde | +| `deleted` | Ob das Token vom Gerät gelöscht wurde | + +`TokenRevocationResult` hat die folgenden Felder: + +| Feld | Bedeutung | +|---|---| +| `status` | `revoked`, `alreadyInvalid`, `unsupported` oder `failed` | +| `isInvalidated` | `true` bei `revoked` und `alreadyInvalid` | +| `statusCode` | Der HTTP-Status oder `null`, wenn keine Antwort empfangen wurde | +| `errorCode` | Der Misskey-Fehlercode, etwa `RATE_LIMIT_EXCEEDED`, falls vorhanden | +| `error` | Die Ursache bei `unsupported` und `failed`: in der Regel `TokenRevocationException` bei einer Fehlerantwort oder einer unerwarteten Antwort und `NetworkException` bei einem Netzwerkfehler oder Timeout | + +`alreadyInvalid` bedeutet, dass der Server das Token nicht erkannt hat: Es wurde bereits widerrufen, oder das Konto wurde gelöscht. Dieses Ergebnis wird wie `revoked` behandelt. + +Fehlschläge beim Widerruf werden im Ergebnis gemeldet und nie als Ausnahme ausgelöst. Fehler beim Löschen des Tokens auf dem Gerät werden wie bisher ausgelöst; `signOutAll` versucht zunächst, alle Konten zu löschen, und löst dann den ersten Fehler aus. + +`deleted` ist in zwei Fällen `false`: `revokeOrKeep` hat das Token behalten, oder während des Widerrufs wurde ein neues Token für dasselbe Konto gespeichert, zum Beispiel weil sich der Benutzer erneut angemeldet hat. Das neue Token wird nicht gelöscht, da es nie widerrufen wurde. + +### Timeout und Wiederholungsversuche {#timeout-and-retries} + +Der Widerruf wird nicht erneut versucht. Ohne `timeout` wartet eine Anfrage, auf die keine Antwort kommt, bis die Timeouts der Anfrage ablaufen (siehe [Timeouts](#timeouts)). Übergeben Sie `timeout`, um die Wartezeit zu begrenzen: + +```dart +await auth.signOut(key, timeout: const Duration(seconds: 5)); +await auth.signOutAll(timeout: const Duration(seconds: 5)); +``` + +`signOutAll` widerruft alle Konten parallel, und alle Anfragen teilen sich eine Frist, die ab dem Aufruf zählt. Das Lesen und Löschen gespeicherter Token wird durch das Timeout nicht abgebrochen. Eine Anfrage, deren Zeit abläuft, wird als `failed` gemeldet. Der Server hat das Token möglicherweise trotzdem widerrufen: Wurde das Token behalten, etwa mit `revokeOrKeep`, meldet ein erneuter Widerruf `alreadyInvalid`. + +### Widerruf ohne den Manager + +Wenn Sie Token selbst speichern, verwenden Sie `MisskeyTokenRevocationClient` direkt. Der Client widerruft das Token auf dem Server und greift auf keinen Speicher zu: + +```dart +final revocation = MisskeyTokenRevocationClient(); +final result = await revocation.revoke( + host: 'misskey.io', + accessToken: token, + timeout: const Duration(seconds: 5), +); +if (result.isInvalidated) { + // Token aus Ihrem eigenen Speicher löschen +} +``` + +`revoke` löst nie eine Ausnahme aus und gibt dasselbe `TokenRevocationResult` zurück. Der Client sendet das Token im Anfragetext. Wenn Sie ein eigenes `Dio` übergeben, können dessen Interceptors das Token sehen. Protokollieren Sie daher keine Anfragetexte. + +Übergeben Sie ein Token, das einer App über MiAuth oder OAuth ausgestellt wurde. Das Sitzungstoken, das der Misskey-Webclient verwendet, ist kein App-Token: Der Server antwortet mit 204, ohne es zu widerrufen, daher lautet das Ergebnis `revoked`, obwohl das Token gültig bleibt. + +## Timeouts {#timeouts} + +`MisskeyAuthManager.defaultInstance()` verwendet die Standard-Timeouts (Verbindung: 10 Sekunden, Senden und Empfangen jeweils 20 Sekunden). Wenn Sie diese ändern möchten, erstellen Sie `MisskeyAuthManager` selbst. Die Timeouts von `MisskeyAuthManager` gelten für die von ihm selbst ausgeführten Anfragen, also für `/api/i` und den Widerruf von Token. Übergeben Sie die Timeouts daher auch an die einzelnen Clients. ```dart const timeout = Duration(seconds: 30); @@ -43,7 +131,7 @@ final auth = MisskeyAuthManager( ); ``` -Alle Konstruktoren akzeptieren `connectTimeout`, `sendTimeout` und `receiveTimeout`. Sie akzeptieren auch `dio`. Die Clients wenden die Timeout-Argumente auch auf das übergebene `Dio` an. `MisskeyAuthManager` ignoriert die Timeout-Argumente jedoch, wenn `dio` übergeben wird. Legen Sie die Timeouts in diesem Fall direkt in `Dio` fest. +Alle Konstruktoren akzeptieren `connectTimeout`, `sendTimeout` und `receiveTimeout`. Sie akzeptieren auch `dio`. `MisskeyOAuthClient` und `MisskeyMiAuthClient` wenden die Timeout-Argumente auch auf das übergebene `Dio` an. `MisskeyTokenRevocationClient` wendet sie nur auf seine eigenen Anfragen an und lässt das übergebene `Dio` unverändert. `MisskeyAuthManager` ignoriert die Timeout-Argumente, wenn `dio` übergeben wird. Legen Sie die Timeouts in diesem Fall direkt in `Dio` fest. Wenn Sie einen anderen Client für den Widerruf verwenden möchten, übergeben Sie ihn als `revocation`. ## Modelle diff --git a/docs/i18n/de/docusaurus-plugin-content-docs/current/upgrading.md b/docs/i18n/de/docusaurus-plugin-content-docs/current/upgrading.md index fa8523d..45bbe53 100644 --- a/docs/i18n/de/docusaurus-plugin-content-docs/current/upgrading.md +++ b/docs/i18n/de/docusaurus-plugin-content-docs/current/upgrading.md @@ -15,6 +15,34 @@ title: Hinweise zum Upgrade Solange die stabile Version von `flutter_web_auth_2` das Kotlin-Android-Plugin anwendet, behalten Sie `android.builtInKotlin=false` und `android.newDsl=false` bei. Behalten Sie die Anwendung des Plugins bei und ändern Sie die JVM-Zielkonfiguration von `android.kotlinOptions` zu `kotlin.compilerOptions`. Bei zukünftigen Flutter-Versionen kann es erforderlich sein, dass abhängige Plugins die integrierte Kotlin-Unterstützung verwenden. +## Upgrade von 0.2.0-beta.2 + +### Beim Abmelden wird das Token widerrufen + +`signOut` und `signOutAll` widerrufen das Token jetzt auf dem Server, bevor sie es vom Gerät löschen. Da sie eine Netzwerkanfrage ausführen, kann der Vorgang bis zum Ablauf der Timeouts der Anfrage dauern. Wenn der Widerruf fehlschlägt oder der Server ihn nicht unterstützt, wird das Token trotzdem vom Gerät gelöscht. + +- Um das bisherige Verhalten beizubehalten, übergeben Sie `mode: SignOutMode.localOnly`. +- Um die Wartezeit zu begrenzen, übergeben Sie `timeout`. +- Server vor Misskey 2026.9.0 unterstützen den Widerruf nicht. Die Token dieser Server bleiben wie bisher auf dem Server gültig. + +Siehe [Abmelden](./token-storage.md#signing-out). + +### Neue Rückgabetypen + +`signOut` gibt jetzt `Future` zurück und `signOutAll` gibt `Future>` zurück. Code, der die Aufrufe nur mit `await` abwartet, muss nicht geändert werden. Klassen, die `MisskeyAuthManager` implementieren oder mocken, müssen die Signaturen anpassen: + +```dart +Future signOut( + AccountKey key, { + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +Future> signOutAll({ + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +``` + ## Upgrade auf 0.2.0-beta.1 ### Unter Android ist eine erneute Anmeldung erforderlich diff --git a/docs/i18n/fr/docusaurus-plugin-content-docs/current/error-handling.md b/docs/i18n/fr/docusaurus-plugin-content-docs/current/error-handling.md index 1a099f3..643d2cf 100644 --- a/docs/i18n/fr/docusaurus-plugin-content-docs/current/error-handling.md +++ b/docs/i18n/fr/docusaurus-plugin-content-docs/current/error-handling.md @@ -64,6 +64,14 @@ Chaque exception possède les propriétés suivantes : | `MiAuthSessionInvalidException` | Le rappel concerne une autre session, ou l’API de vérification a renvoyé 404 ou 410 | | `MiAuthCheckFailedException` | L’API de vérification a renvoyé un autre statut d’erreur | +### Révocation des jetons + +| Exception | Condition de renvoi | +|---|---| +| `TokenRevocationException` | Le serveur a répondu à la requête de révocation par un statut d’erreur ou une autre réponse inattendue. `details` contient le statut HTTP et, le cas échéant, l’erreur renvoyée par le serveur | + +La révocation ne lève jamais d’exception. `signOut`, `signOutAll` et `MisskeyTokenRevocationClient.revoke` renvoient la cause dans `TokenRevocationResult.error`, qui peut aussi être une `NetworkException` ou une `ResponseParseException`. Ces exceptions ne contiennent pas d’`originalException`, afin de ne pas exposer le jeton présent dans la requête. Consultez [Déconnexion](./token-storage.md#signing-out). + ### Exceptions non levées par la version actuelle `InvalidAuthConfigException`, `SecureStorageException` et `MiAuthNotSupportedException` sont définies, mais ne sont pas levées par la version actuelle. @@ -74,10 +82,13 @@ Chaque exception possède les propriétés suivantes : `loginWithOAuth` et `loginWithMiAuth` enregistrent d’abord le jeton, puis activent le compte. Si seule l’opération d’activation du compte échoue, le jeton reste enregistré, mais le compte n’est pas actif. +`signOut` et `signOutAll` ne lèvent pas d’exception lorsqu’un jeton stocké ne peut pas être lu ; ils le suppriment sans révocation. Ils lèvent en revanche une exception si la suppression du jeton échoue. + ## Nouvelles tentatives - La récupération des informations du serveur OAuth et l’appel à `/api/i` font jusqu’à trois tentatives au total en cas de délai dépassé, d’erreur de connexion, d’autre erreur de transport ou de réponse HTTP 429, 500, 502, 503 ou 504. - L’échange du jeton et l’API de vérification MiAuth ne font pas de nouvelle tentative. Un code d’autorisation et une session MiAuth ne peuvent être utilisés qu’une fois, et le serveur peut avoir traité la requête même si la réponse a été perdue. Recommencez l’authentification depuis le début. +- La révocation des jetons ne fait pas de nouvelle tentative. Consultez [Délai d’expiration et nouvelles tentatives](./token-storage.md#timeout-and-retries). ## Échec de connexion après l’authentification diff --git a/docs/i18n/fr/docusaurus-plugin-content-docs/current/token-storage.md b/docs/i18n/fr/docusaurus-plugin-content-docs/current/token-storage.md index 3c07537..789ebc4 100644 --- a/docs/i18n/fr/docusaurus-plugin-content-docs/current/token-storage.md +++ b/docs/i18n/fr/docusaurus-plugin-content-docs/current/token-storage.md @@ -23,15 +23,103 @@ final active = await auth.getActive(); await auth.clearActive(); // Déconnexion -await auth.signOut(key); // Supprime le jeton d’un compte -await auth.signOutAll(); // Supprime les jetons de tous les comptes +await auth.signOut(key); // Révoque et supprime le jeton d’un compte +await auth.signOutAll(); // Révoque et supprime les jetons de tous les comptes ``` -La déconnexion supprime uniquement le jeton de l’appareil. Elle ne révoque pas le jeton sur le serveur. +## Déconnexion {#signing-out} -## Délais d’expiration +La déconnexion révoque le jeton sur le serveur, puis le supprime de l’appareil. La révocation nécessite Misskey 2026.9.0 ou version ultérieure, qui permet à un jeton d’application de se révoquer lui-même via `/api/i/revoke-token`. Elle fonctionne pour les jetons MiAuth et OAuth, quelles que soient leurs autorisations. -`MisskeyAuthManager.defaultInstance()` utilise les délais par défaut : 10 secondes pour la connexion, et 20 secondes pour l’envoi et la réception. Pour les modifier, construisez vous-même `MisskeyAuthManager`. Ses délais ne s’appliquent qu’à sa propre requête `/api/i` ; transmettez-les donc également à chaque client : +```dart +final result = await auth.signOut(key); +final revocation = result.revocation; +if (revocation == null) { + // La révocation n’a pas été tentée. Consultez result.skipReason. +} else if (revocation.isInvalidated) { + // revoked ou alreadyInvalid : le jeton n’est plus utilisable sur le serveur. +} else if (revocation.status == TokenRevocationStatus.unsupported) { + // Le serveur est antérieur à 2026.9.0. Le jeton y reste valide. +} else { + // failed : erreur réseau, délai dépassé ou réponse inattendue. +} +``` + +### Modes + +Transmettez `mode` pour choisir ce qu’il advient du jeton sur l’appareil : + +| `SignOutMode` | Révocation | Suppression de l’appareil | +|---|---|---| +| `revokeAndDelete` (par défaut) | Oui | Toujours, quel que soit le résultat de la révocation | +| `revokeOrKeep` | Oui | Uniquement si le résultat est `revoked` ou `alreadyInvalid` | +| `localOnly` | Non | Toujours | + +Avec `revokeOrKeep`, un jeton qui n’a pas pu être révoqué reste enregistré, afin que l’utilisateur puisse réessayer plus tard. Un serveur qui ne prend pas en charge la révocation renvoie toujours `unsupported`, et un compte que le serveur refuse pour une autre raison, par exemple un compte suspendu, peut échouer à chaque fois. Pour retirer ces comptes de l’appareil, déconnectez-les à nouveau avec `SignOutMode.localOnly`. + +Si le jeton n’est pas stocké ou ne peut pas être lu, par exemple parce que les données stockées sont corrompues, il est supprimé sans révocation, quel que soit le mode. + +### Résultats + +`signOut` renvoie un `SignOutResult`, et `signOutAll` en renvoie un pour chaque compte, dans l’ordre de `listAccounts` : + +| Champ | Signification | +|---|---| +| `key` | Le compte | +| `revocation` | Le `TokenRevocationResult`, ou `null` si la révocation n’a pas été tentée | +| `skipReason` | La raison pour laquelle la révocation n’a pas été tentée : `localOnly`, `noStoredToken` ou `unreadableToken`. `null` si elle a été tentée | +| `deleted` | Indique si le jeton a été supprimé de l’appareil | + +`TokenRevocationResult` contient : + +| Champ | Signification | +|---|---| +| `status` | `revoked`, `alreadyInvalid`, `unsupported` ou `failed` | +| `isInvalidated` | `true` pour `revoked` et `alreadyInvalid` | +| `statusCode` | Le statut HTTP, ou `null` si aucune réponse n’a été reçue | +| `errorCode` | Le code d’erreur Misskey, comme `RATE_LIMIT_EXCEEDED`, le cas échéant | +| `error` | La cause pour `unsupported` et `failed` : en général `TokenRevocationException` pour une réponse d’erreur ou inattendue, et `NetworkException` pour une erreur réseau ou un délai dépassé | + +`alreadyInvalid` signifie que le serveur n’a pas reconnu le jeton : il avait déjà été révoqué, ou le compte a été supprimé. Ce résultat est traité comme `revoked`. + +Les échecs de révocation sont signalés dans le résultat et ne sont jamais levés. Les erreurs survenant lors de la suppression du jeton sur l’appareil sont levées comme auparavant ; `signOutAll` tente d’abord de supprimer tous les comptes, puis lève la première erreur. + +`deleted` vaut `false` dans deux cas : `revokeOrKeep` a conservé le jeton, ou un nouveau jeton a été enregistré pour le même compte pendant la révocation, par exemple parce que l’utilisateur s’est reconnecté. Le nouveau jeton n’est pas supprimé, car il n’a jamais été révoqué. + +### Délai d’expiration et nouvelles tentatives {#timeout-and-retries} + +La révocation ne fait pas de nouvelle tentative. Sans `timeout`, une requête qui ne répond pas attend l’expiration des délais de la requête (consultez [Délais d’expiration](#timeouts)). Transmettez `timeout` pour limiter cette attente : + +```dart +await auth.signOut(key, timeout: const Duration(seconds: 5)); +await auth.signOutAll(timeout: const Duration(seconds: 5)); +``` + +`signOutAll` révoque tous les comptes en parallèle, et toutes les requêtes partagent un même délai compté à partir de l’appel. La lecture et la suppression des jetons enregistrés ne sont pas interrompues par ce délai. Une requête qui dépasse le délai est signalée comme `failed`. Le serveur peut néanmoins avoir révoqué le jeton : si le jeton a été conservé, par exemple avec `revokeOrKeep`, une nouvelle révocation signale `alreadyInvalid`. + +### Révocation sans le gestionnaire + +Si vous stockez vous-même les jetons, utilisez directement `MisskeyTokenRevocationClient`. Il révoque le jeton sur le serveur sans toucher à aucun stockage : + +```dart +final revocation = MisskeyTokenRevocationClient(); +final result = await revocation.revoke( + host: 'misskey.io', + accessToken: token, + timeout: const Duration(seconds: 5), +); +if (result.isInvalidated) { + // Supprimez le jeton de votre propre stockage. +} +``` + +`revoke` ne lève jamais d’exception et renvoie le même `TokenRevocationResult`. Le client envoie le jeton dans le corps de la requête. Si vous transmettez votre propre `Dio`, ses intercepteurs peuvent voir le jeton ; ne journalisez donc pas le corps des requêtes. + +Transmettez un jeton délivré à une application via MiAuth ou OAuth. Le jeton de session qu’utilise le client web de Misskey n’est pas un jeton d’application : le serveur répond 204 sans le révoquer, si bien que le résultat est `revoked` alors que le jeton reste valide. + +## Délais d’expiration {#timeouts} + +`MisskeyAuthManager.defaultInstance()` utilise les délais par défaut : 10 secondes pour la connexion, et 20 secondes pour l’envoi et la réception. Pour les modifier, construisez vous-même `MisskeyAuthManager`. Ses délais s’appliquent à ses propres requêtes, `/api/i` et la révocation des jetons ; transmettez-les donc également à chaque client : ```dart const timeout = Duration(seconds: 30); @@ -43,7 +131,7 @@ final auth = MisskeyAuthManager( ); ``` -Les constructeurs acceptent `connectTimeout`, `sendTimeout` et `receiveTimeout`. Ils acceptent également un `dio`. Les clients appliquent aussi les arguments de délai à un `Dio` que vous leur transmettez, mais `MisskeyAuthManager` les ignore si `dio` est fourni ; configurez directement ce `Dio`. +Les constructeurs acceptent `connectTimeout`, `sendTimeout` et `receiveTimeout`. Ils acceptent également un `dio`. `MisskeyOAuthClient` et `MisskeyMiAuthClient` appliquent aussi les arguments de délai à un `Dio` que vous leur transmettez. `MisskeyTokenRevocationClient` ne les applique qu’à ses propres requêtes et laisse ce `Dio` inchangé. `MisskeyAuthManager` les ignore si `dio` est fourni ; configurez directement ce `Dio`. Pour utiliser un autre client de révocation, transmettez-le via `revocation`. ## Modèles diff --git a/docs/i18n/fr/docusaurus-plugin-content-docs/current/upgrading.md b/docs/i18n/fr/docusaurus-plugin-content-docs/current/upgrading.md index 22db3b0..43c8488 100644 --- a/docs/i18n/fr/docusaurus-plugin-content-docs/current/upgrading.md +++ b/docs/i18n/fr/docusaurus-plugin-content-docs/current/upgrading.md @@ -15,6 +15,34 @@ title: Mise à niveau Conservez `android.builtInKotlin=false` et `android.newDsl=false` tant que la version stable de `flutter_web_auth_2` applique le plugin Kotlin Android. Gardez ce plugin, mais remplacez `android.kotlinOptions` par `kotlin.compilerOptions` pour configurer sa cible JVM. Les futures versions de Flutter pourraient exiger la prise en charge de Kotlin intégré par les dépendances. +## Mise à niveau depuis 0.2.0-beta.2 + +### La déconnexion révoque le jeton + +`signOut` et `signOutAll` révoquent désormais le jeton sur le serveur avant de le supprimer de l’appareil. Comme ils effectuent une requête réseau, ils peuvent durer jusqu’à l’expiration des délais de la requête. Le jeton est tout de même supprimé de l’appareil si la révocation échoue ou si le serveur ne la prend pas en charge. + +- Pour conserver le comportement précédent, transmettez `mode: SignOutMode.localOnly`. +- Pour limiter l’attente, transmettez `timeout`. +- Les serveurs antérieurs à Misskey 2026.9.0 ne prennent pas en charge la révocation. Leurs jetons restent valides sur le serveur, comme auparavant. + +Consultez [Déconnexion](./token-storage.md#signing-out). + +### Nouveaux types de retour + +`signOut` renvoie désormais `Future`, et `signOutAll` renvoie `Future>`. Le code qui se contente de les attendre avec `await` n’a pas besoin d’être modifié. Les classes qui implémentent ou simulent `MisskeyAuthManager` doivent mettre à jour les signatures : + +```dart +Future signOut( + AccountKey key, { + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +Future> signOutAll({ + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +``` + ## Mise à niveau vers 0.2.0-beta.1 ### Les utilisateurs Android doivent se reconnecter diff --git a/docs/i18n/ja/docusaurus-plugin-content-docs/current/error-handling.md b/docs/i18n/ja/docusaurus-plugin-content-docs/current/error-handling.md index d79d883..0090942 100644 --- a/docs/i18n/ja/docusaurus-plugin-content-docs/current/error-handling.md +++ b/docs/i18n/ja/docusaurus-plugin-content-docs/current/error-handling.md @@ -64,6 +64,14 @@ try { | `MiAuthSessionInvalidException` | コールバックが別のセッションのものだった、またはチェック API が 404 か 410 を返した | | `MiAuthCheckFailedException` | チェック API がその他のエラーステータスを返した | +### トークンの失効 + +| 例外 | 返される条件 | +|---|---| +| `TokenRevocationException` | サーバーが失効のリクエストにエラーステータス、またはその他の想定外の応答を返した。`details` に HTTP ステータスと、ある場合はサーバーからのエラーが入る | + +失効の処理は例外を投げません。`signOut`、`signOutAll`、`MisskeyTokenRevocationClient.revoke` は、原因を `TokenRevocationResult.error` で返します。この値は `NetworkException` や `ResponseParseException` の場合もあります。リクエストに含まれるトークンが露出しないよう、これらの例外は `originalException` を持ちません。[サインアウト](./token-storage.md#signing-out)を参照してください。 + ### 現在のバージョンでは投げられない例外 `InvalidAuthConfigException`、`SecureStorageException`、`MiAuthNotSupportedException` は定義されていますが、現在のバージョンでは投げられません。 @@ -74,10 +82,13 @@ try { `loginWithOAuth` と `loginWithMiAuth` は、トークンを保存してからアカウントをアクティブにします。アカウントをアクティブにする処理だけが失敗した場合、トークンは保存されたままで、アカウントはアクティブになりません。 +`signOut` と `signOutAll` は、保存されたトークンを読み取れない場合は例外を投げず、失効させずに削除します。トークンの削除に失敗した場合は例外を投げます。 + ## 再試行 - OAuth のサーバー情報の取得と `/api/i` の呼び出しは、タイムアウト、接続エラー、その他の通信エラー、HTTP 429・500・502・503・504 のときに、合計3回まで試行します。 - トークンの交換と MiAuth のチェック API は再試行しません。認可コードと MiAuth のセッションは一度しか使えず、応答が失われてもサーバー側では処理が済んでいる可能性があるためです。最初から認証をやり直してください。 +- トークンの失効は再試行しません。[タイムアウトと再試行](./token-storage.md#timeout-and-retries)を参照してください。 ## 認証後にログインが失敗した場合 diff --git a/docs/i18n/ja/docusaurus-plugin-content-docs/current/token-storage.md b/docs/i18n/ja/docusaurus-plugin-content-docs/current/token-storage.md index 446c543..d5d3aba 100644 --- a/docs/i18n/ja/docusaurus-plugin-content-docs/current/token-storage.md +++ b/docs/i18n/ja/docusaurus-plugin-content-docs/current/token-storage.md @@ -23,15 +23,103 @@ final active = await auth.getActive(); await auth.clearActive(); // サインアウト -await auth.signOut(key); // 1つのアカウントのトークンを削除 -await auth.signOutAll(); // すべてのアカウントのトークンを削除 +await auth.signOut(key); // 1つのアカウントのトークンを失効させて削除 +await auth.signOutAll(); // すべてのアカウントのトークンを失効させて削除 ``` -サインアウトは端末上のトークンを削除するだけです。サーバー側でトークンを失効させることはありません。 +## サインアウト {#signing-out} -## タイムアウト +サインアウトすると、サーバー側でトークンを失効させてから、端末上のトークンを削除します。失効には Misskey 2026.9.0 以降が必要です。このバージョンから、アプリのトークンが `/api/i/revoke-token` で自分自身を失効させられるようになりました。MiAuth と OAuth のどちらのトークンでも、権限に関係なく失効させられます。 -`MisskeyAuthManager.defaultInstance()` は既定のタイムアウト(接続 10 秒、送信と受信は各 20 秒)を使います。変更する場合は `MisskeyAuthManager` を自分で組み立てます。`MisskeyAuthManager` のタイムアウトは、それ自身が行う `/api/i` のリクエストにだけ適用されるため、各クライアントにも渡してください。 +```dart +final result = await auth.signOut(key); +final revocation = result.revocation; +if (revocation == null) { + // 失効を試みなかった。result.skipReason を参照 +} else if (revocation.isInvalidated) { + // revoked または alreadyInvalid: サーバー側ではトークンをもう使えない +} else if (revocation.status == TokenRevocationStatus.unsupported) { + // サーバーが 2026.9.0 より古い。サーバー側ではトークンが有効なまま +} else { + // failed: ネットワークエラー、タイムアウト、または想定外の応答 +} +``` + +### モード + +`mode` を渡すと、端末上のトークンをどう扱うかを選べます。 + +| `SignOutMode` | 失効 | 端末からの削除 | +|---|---|---| +| `revokeAndDelete`(既定) | する | 常に削除(失効の結果を問わない) | +| `revokeOrKeep` | する | 結果が `revoked` または `alreadyInvalid` の場合のみ | +| `localOnly` | しない | 常に削除 | + +`revokeOrKeep` では、失効できなかったトークンが保存されたまま残るため、ユーザーは後で再試行できます。失効に対応していないサーバーは常に `unsupported` を返します。また、凍結されたアカウントなど、別の理由でサーバーに拒否されるアカウントは毎回失敗する可能性があります。こうしたアカウントを端末から削除するには、`SignOutMode.localOnly` で再度サインアウトしてください。 + +トークンが保存されていない場合や、保存データの破損などにより読み取れない場合は、どのモードでも失効を行わずに削除します。 + +### 結果 + +`signOut` は `SignOutResult` を返します。`signOutAll` はアカウントごとの `SignOutResult` を `listAccounts` の順で返します。 + +| フィールド | 意味 | +|---|---| +| `key` | 対象のアカウント | +| `revocation` | `TokenRevocationResult`。失効を試みなかった場合は `null` | +| `skipReason` | 失効を試みなかった理由(`localOnly`、`noStoredToken`、`unreadableToken` のいずれか)。試みた場合は `null` | +| `deleted` | 端末からトークンを削除したかどうか | + +`TokenRevocationResult` は次のフィールドを持ちます。 + +| フィールド | 意味 | +|---|---| +| `status` | `revoked`、`alreadyInvalid`、`unsupported`、`failed` のいずれか | +| `isInvalidated` | `revoked` と `alreadyInvalid` のとき `true` | +| `statusCode` | HTTP ステータス。応答を受け取れなかった場合は `null` | +| `errorCode` | Misskey のエラーコード(例: `RATE_LIMIT_EXCEEDED`)。ある場合のみ | +| `error` | `unsupported` と `failed` の原因。通常、エラー応答や想定外の応答の場合は `TokenRevocationException`、ネットワークエラーやタイムアウトの場合は `NetworkException` | + +`alreadyInvalid` は、サーバーがトークンを認識しなかったことを意味します。トークンがすでに失効しているか、アカウントが削除されています。`revoked` と同じように扱われます。 + +失効の失敗は結果として報告され、例外として投げられることはありません。端末上のトークンの削除で起きたエラーは、従来どおり投げられます。`signOutAll` は、まずすべてのアカウントの削除を試み、その後で最初のエラーを投げます。 + +`deleted` が `false` になるのは2つの場合です。`revokeOrKeep` によってトークンが残された場合と、失効の処理中に同じアカウントへ新しいトークンが保存された場合(例: ユーザーが再度サインインした)です。新しいトークンは失効させていないため、削除しません。 + +### タイムアウトと再試行 {#timeout-and-retries} + +失効は再試行しません。`timeout` を指定しない場合、応答のないリクエストはリクエストのタイムアウトまで待ちます([タイムアウト](#timeouts)を参照)。待ち時間を制限するには `timeout` を渡します。 + +```dart +await auth.signOut(key, timeout: const Duration(seconds: 5)); +await auth.signOutAll(timeout: const Duration(seconds: 5)); +``` + +`signOutAll` はすべてのアカウントを並行して失効させ、すべてのリクエストが呼び出し時点から数えた1つの期限を共有します。保存されたトークンの読み書きは、タイムアウトで打ち切られません。時間切れになったリクエストは `failed` として報告されます。それでもサーバー側ではトークンが失効している可能性があります。`revokeOrKeep` などでトークンが残っている場合は、再度失効させると `alreadyInvalid` が報告されます。 + +### マネージャーを使わない失効 + +トークンを自分で保存している場合は、`MisskeyTokenRevocationClient` を直接使います。このクラスはサーバー側でトークンを失効させるだけで、保存領域には一切触れません。 + +```dart +final revocation = MisskeyTokenRevocationClient(); +final result = await revocation.revoke( + host: 'misskey.io', + accessToken: token, + timeout: const Duration(seconds: 5), +); +if (result.isInvalidated) { + // 自分の保存領域からトークンを削除する +} +``` + +`revoke` は例外を投げず、同じ `TokenRevocationResult` を返します。クライアントはトークンをリクエストボディに入れて送信します。独自の `Dio` を渡した場合は、そのインターセプターからトークンが見えるため、リクエストボディをログに出力しないでください。 + +MiAuth または OAuth でアプリに発行されたトークンを渡してください。Misskey の Web クライアントが使うセッショントークンはアプリのトークンではありません。サーバーは失効させずに 204 を返すため、トークンは有効なままでも結果は `revoked` になります。 + +## タイムアウト {#timeouts} + +`MisskeyAuthManager.defaultInstance()` は既定のタイムアウト(接続 10 秒、送信と受信は各 20 秒)を使います。変更する場合は `MisskeyAuthManager` を自分で組み立てます。`MisskeyAuthManager` のタイムアウトは、それ自身が行うリクエスト(`/api/i` とトークンの失効)に適用されるため、各クライアントにも渡してください。 ```dart const timeout = Duration(seconds: 30); @@ -43,7 +131,7 @@ final auth = MisskeyAuthManager( ); ``` -各コンストラクタは `connectTimeout`、`sendTimeout`、`receiveTimeout` を受け取ります。`dio` も受け取ります。クライアントは渡された `Dio` にもタイムアウトの引数を適用しますが、`MisskeyAuthManager` は `dio` を渡された場合にタイムアウトの引数を無視します。その場合は `Dio` 側で直接設定してください。 +各コンストラクタは `connectTimeout`、`sendTimeout`、`receiveTimeout` を受け取ります。`dio` も受け取ります。`MisskeyOAuthClient` と `MisskeyMiAuthClient` は、渡された `Dio` にもタイムアウトの引数を適用します。`MisskeyTokenRevocationClient` はタイムアウトの引数を自身のリクエストにだけ適用し、渡された `Dio` は変更しません。`MisskeyAuthManager` は `dio` を渡された場合にタイムアウトの引数を無視します。その場合は `Dio` 側で直接設定してください。別の失効クライアントを使う場合は、`revocation` に渡します。 ## モデル diff --git a/docs/i18n/ja/docusaurus-plugin-content-docs/current/upgrading.md b/docs/i18n/ja/docusaurus-plugin-content-docs/current/upgrading.md index 60e822e..4d2898a 100644 --- a/docs/i18n/ja/docusaurus-plugin-content-docs/current/upgrading.md +++ b/docs/i18n/ja/docusaurus-plugin-content-docs/current/upgrading.md @@ -15,6 +15,34 @@ title: 更新時の注意 安定版の `flutter_web_auth_2` が Kotlin Android プラグインを適用する間は、`android.builtInKotlin=false` と `android.newDsl=false` を維持してください。プラグインの適用は残し、JVM ターゲットの設定を `android.kotlinOptions` から `kotlin.compilerOptions` へ変更します。将来の Flutter では、依存プラグイン側の内蔵 Kotlin 対応が必要になる可能性があります。 +## 0.2.0-beta.2 からの更新 + +### サインアウト時にトークンを失効 + +`signOut` と `signOutAll` は、端末からトークンを削除する前に、サーバー側でトークンを失効させるようになりました。ネットワークリクエストを行うため、リクエストのタイムアウトに達するまで時間がかかることがあります。失効に失敗した場合や、サーバーが失効に対応していない場合も、端末からはトークンが削除されます。 + +- 以前の動作を維持するには、`mode: SignOutMode.localOnly` を渡してください。 +- 待ち時間を制限するには、`timeout` を渡してください。 +- Misskey 2026.9.0 より前のサーバーは失効に対応していません。そうしたサーバーのトークンは、従来どおりサーバー側で有効なままです。 + +[サインアウト](./token-storage.md#signing-out)を参照してください。 + +### 新しい戻り値の型 + +`signOut` は `Future` を、`signOutAll` は `Future>` を返すようになりました。await するだけのコードは変更不要です。`MisskeyAuthManager` を実装またはモックするクラスは、シグネチャを更新する必要があります。 + +```dart +Future signOut( + AccountKey key, { + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +Future> signOutAll({ + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +``` + ## 0.2.0-beta.1 への更新 ### Android では再度のサインインが必要 diff --git a/docs/i18n/ko/docusaurus-plugin-content-docs/current/error-handling.md b/docs/i18n/ko/docusaurus-plugin-content-docs/current/error-handling.md index 23e0bc0..a9d0ad2 100644 --- a/docs/i18n/ko/docusaurus-plugin-content-docs/current/error-handling.md +++ b/docs/i18n/ko/docusaurus-plugin-content-docs/current/error-handling.md @@ -64,6 +64,14 @@ try { | `MiAuthSessionInvalidException` | 콜백이 다른 세션에 대한 것이거나 확인 API가 404 또는 410을 반환했습니다. | | `MiAuthCheckFailedException` | 확인 API가 그 밖의 오류 상태를 반환했습니다. | +### 토큰 폐기 + +| 예외 | 반환 조건 | +|---|---| +| `TokenRevocationException` | 서버가 폐기 요청에 오류 상태 또는 그 밖의 예상치 못한 응답을 반환했습니다. `details`에는 HTTP 상태와, 있는 경우 서버 오류가 포함됩니다. | + +폐기는 예외를 발생시키지 않습니다. `signOut`, `signOutAll`, `MisskeyTokenRevocationClient.revoke`는 원인을 `TokenRevocationResult.error`로 반환하며, 이 값은 `NetworkException`이나 `ResponseParseException`일 수도 있습니다. 요청에 포함된 토큰이 노출되지 않도록 이러한 예외에는 `originalException`이 없습니다. [로그아웃](./token-storage.md#signing-out)을 참조하세요. + ### 현재 버전에서 발생하지 않는 예외 `InvalidAuthConfigException`, `SecureStorageException`, `MiAuthNotSupportedException`은 정의되어 있지만 현재 버전에서는 발생하지 않습니다. @@ -74,10 +82,13 @@ try { `loginWithOAuth`와 `loginWithMiAuth`는 토큰을 저장한 다음 계정을 활성화합니다. 계정을 활성화하는 단계만 실패하면 토큰은 저장된 채로 남고 계정은 활성화되지 않습니다. +`signOut`과 `signOutAll`은 저장된 토큰을 읽을 수 없어도 예외를 발생시키지 않고, 폐기하지 않은 채 삭제합니다. 토큰 삭제에 실패하면 예외를 발생시킵니다. + ## 재시도 - OAuth 서버 정보 조회와 `/api/i` 호출은 시간 초과, 연결 오류, 기타 전송 오류, HTTP 429·500·502·503·504에서 최대 총 세 번 시도합니다. - 토큰 교환과 MiAuth 확인 API는 재시도하지 않습니다. 인가 코드와 MiAuth 세션은 한 번만 사용할 수 있으며, 응답을 받지 못했더라도 서버에서 요청 처리가 완료되었을 수 있습니다. 처음부터 인증을 다시 시작하세요. +- 토큰 폐기는 재시도하지 않습니다. [시간 초과와 재시도](./token-storage.md#timeout-and-retries)를 참조하세요. ## 인증 후 로그인에 실패하는 경우 diff --git a/docs/i18n/ko/docusaurus-plugin-content-docs/current/token-storage.md b/docs/i18n/ko/docusaurus-plugin-content-docs/current/token-storage.md index 5ada316..512913e 100644 --- a/docs/i18n/ko/docusaurus-plugin-content-docs/current/token-storage.md +++ b/docs/i18n/ko/docusaurus-plugin-content-docs/current/token-storage.md @@ -23,15 +23,103 @@ final active = await auth.getActive(); await auth.clearActive(); // 로그아웃 -await auth.signOut(key); // 한 계정의 토큰 삭제 -await auth.signOutAll(); // 모든 계정의 토큰 삭제 +await auth.signOut(key); // 한 계정의 토큰 폐기 및 삭제 +await auth.signOutAll(); // 모든 계정의 토큰 폐기 및 삭제 ``` -로그아웃은 기기에 저장된 토큰만 삭제합니다. 서버에서 토큰을 폐기하지는 않습니다. +## 로그아웃 {#signing-out} -## 시간 초과 +로그아웃하면 서버에서 토큰을 폐기한 다음 기기에서 삭제합니다. 폐기하려면 Misskey 2026.9.0 이상이 필요합니다. 이 버전부터 앱 토큰이 `/api/i/revoke-token`을 통해 스스로를 폐기할 수 있습니다. MiAuth 토큰과 OAuth 토큰 모두 권한과 관계없이 폐기할 수 있습니다. -`MisskeyAuthManager.defaultInstance()`는 기본 시간 초과(연결 10초, 전송 및 수신 각각 20초)를 사용합니다. 변경하려면 `MisskeyAuthManager`를 직접 구성하세요. `MisskeyAuthManager`의 시간 초과는 자체 `/api/i` 요청에만 적용되므로 각 클라이언트에도 전달해야 합니다. +```dart +final result = await auth.signOut(key); +final revocation = result.revocation; +if (revocation == null) { + // 폐기를 시도하지 않았습니다. result.skipReason을 확인하세요. +} else if (revocation.isInvalidated) { + // revoked 또는 alreadyInvalid: 서버에서 더 이상 토큰을 사용할 수 없습니다. +} else if (revocation.status == TokenRevocationStatus.unsupported) { + // 서버가 2026.9.0보다 오래된 버전입니다. 서버에서는 토큰이 계속 유효합니다. +} else { + // failed: 네트워크 오류, 시간 초과 또는 예상하지 못한 응답입니다. +} +``` + +### 모드 + +`mode`를 전달하면 기기의 토큰을 어떻게 처리할지 선택할 수 있습니다. + +| `SignOutMode` | 폐기 | 기기에서 삭제 | +|---|---|---| +| `revokeAndDelete`(기본값) | 예 | 항상(폐기 결과와 관계없이) | +| `revokeOrKeep` | 예 | 결과가 `revoked` 또는 `alreadyInvalid`인 경우에만 | +| `localOnly` | 아니요 | 항상 | + +`revokeOrKeep`을 사용하면 폐기하지 못한 토큰이 저장된 채로 남으므로 사용자가 나중에 다시 시도할 수 있습니다. 폐기를 지원하지 않는 서버는 항상 `unsupported`를 반환하며, 정지된 계정처럼 서버가 다른 이유로 거부하는 계정은 매번 실패할 수 있습니다. 이러한 계정을 기기에서 제거하려면 `SignOutMode.localOnly`로 다시 로그아웃하세요. + +토큰이 저장되어 있지 않거나 저장된 데이터가 손상되는 등의 이유로 읽을 수 없는 경우에는 모든 모드에서 폐기하지 않고 삭제합니다. + +### 결과 + +`signOut`은 `SignOutResult`를 반환하고, `signOutAll`은 `listAccounts` 순서대로 계정마다 하나씩 반환합니다. + +| 필드 | 의미 | +|---|---| +| `key` | 대상 계정 | +| `revocation` | `TokenRevocationResult`. 폐기를 시도하지 않았으면 `null` | +| `skipReason` | 폐기를 시도하지 않은 이유: `localOnly`, `noStoredToken`, `unreadableToken` 중 하나. 시도했으면 `null` | +| `deleted` | 기기에서 토큰을 삭제했는지 여부 | + +`TokenRevocationResult`에는 다음 필드가 있습니다. + +| 필드 | 의미 | +|---|---| +| `status` | `revoked`, `alreadyInvalid`, `unsupported`, `failed` 중 하나 | +| `isInvalidated` | `revoked`와 `alreadyInvalid`일 때 `true` | +| `statusCode` | HTTP 상태. 응답을 받지 못했으면 `null` | +| `errorCode` | `RATE_LIMIT_EXCEEDED`와 같은 Misskey 오류 코드(있는 경우) | +| `error` | `unsupported`와 `failed`의 원인. 일반적으로 오류 응답이나 예상치 못한 응답이면 `TokenRevocationException`, 네트워크 오류나 시간 초과면 `NetworkException` | + +`alreadyInvalid`는 서버가 토큰을 인식하지 못했다는 뜻입니다. 토큰이 이미 폐기되었거나 계정이 삭제된 경우입니다. `revoked`와 같이 취급됩니다. + +폐기 실패는 결과로 보고되며 예외로 발생하지 않습니다. 기기에서 토큰을 삭제할 때 발생한 오류는 이전과 마찬가지로 예외로 발생합니다. `signOutAll`은 먼저 모든 계정의 삭제를 시도한 다음 첫 번째 오류를 발생시킵니다. + +`deleted`가 `false`가 되는 경우는 두 가지입니다. `revokeOrKeep`이 토큰을 유지한 경우와, 폐기가 진행되는 동안 같은 계정에 새 토큰이 저장된 경우(예: 사용자가 다시 로그인함)입니다. 새 토큰은 폐기된 적이 없으므로 삭제하지 않습니다. + +### 시간 초과와 재시도 {#timeout-and-retries} + +폐기는 재시도하지 않습니다. `timeout`을 지정하지 않으면 응답하지 않는 요청은 요청 시간 초과까지 기다립니다([시간 초과](#timeouts) 참조). 대기 시간을 제한하려면 `timeout`을 전달하세요. + +```dart +await auth.signOut(key, timeout: const Duration(seconds: 5)); +await auth.signOutAll(timeout: const Duration(seconds: 5)); +``` + +`signOutAll`은 모든 계정을 병렬로 폐기하며, 모든 요청이 호출 시점부터 계산한 하나의 기한을 공유합니다. 저장된 토큰을 읽고 삭제하는 작업은 시간 초과로 중단되지 않습니다. 시간이 초과된 요청은 `failed`로 보고됩니다. 그래도 서버에서는 토큰이 폐기되었을 수 있습니다. `revokeOrKeep` 등으로 토큰이 남아 있다면 다시 폐기할 때 `alreadyInvalid`가 보고됩니다. + +### 매니저 없이 폐기하기 + +토큰을 직접 저장한다면 `MisskeyTokenRevocationClient`를 직접 사용하세요. 이 클라이언트는 서버에서 토큰을 폐기할 뿐 저장소에는 전혀 접근하지 않습니다. + +```dart +final revocation = MisskeyTokenRevocationClient(); +final result = await revocation.revoke( + host: 'misskey.io', + accessToken: token, + timeout: const Duration(seconds: 5), +); +if (result.isInvalidated) { + // 직접 관리하는 저장소에서 토큰을 삭제합니다. +} +``` + +`revoke`는 예외를 발생시키지 않으며 같은 `TokenRevocationResult`를 반환합니다. 클라이언트는 토큰을 요청 본문에 담아 전송합니다. 직접 만든 `Dio`를 전달하면 해당 인터셉터가 토큰을 볼 수 있으므로 요청 본문을 로그에 기록하지 마세요. + +MiAuth 또는 OAuth로 앱에 발급된 토큰을 전달하세요. Misskey 웹 클라이언트가 사용하는 세션 토큰은 앱 토큰이 아닙니다. 서버는 이를 폐기하지 않고 204를 반환하므로, 토큰이 계속 유효한데도 결과는 `revoked`가 됩니다. + +## 시간 초과 {#timeouts} + +`MisskeyAuthManager.defaultInstance()`는 기본 시간 초과(연결 10초, 전송 및 수신 각각 20초)를 사용합니다. 변경하려면 `MisskeyAuthManager`를 직접 구성하세요. `MisskeyAuthManager`의 시간 초과는 자체 요청인 `/api/i`와 토큰 폐기에 적용되므로 각 클라이언트에도 전달해야 합니다. ```dart const timeout = Duration(seconds: 30); @@ -43,7 +131,7 @@ final auth = MisskeyAuthManager( ); ``` -각 생성자는 `connectTimeout`, `sendTimeout`, `receiveTimeout`을 받습니다. `dio`도 전달할 수 있습니다. 클라이언트는 전달된 `Dio`에도 시간 초과 인수를 적용하지만, `MisskeyAuthManager`는 `dio`를 전달받으면 시간 초과 인수를 무시합니다. 이 경우 `Dio`에서 직접 설정하세요. +각 생성자는 `connectTimeout`, `sendTimeout`, `receiveTimeout`을 받습니다. `dio`도 전달할 수 있습니다. `MisskeyOAuthClient`와 `MisskeyMiAuthClient`는 전달된 `Dio`에도 시간 초과 인수를 적용합니다. `MisskeyTokenRevocationClient`는 시간 초과 인수를 자체 요청에만 적용하고 전달된 `Dio`는 변경하지 않습니다. `MisskeyAuthManager`는 `dio`를 전달받으면 시간 초과 인수를 무시합니다. 이 경우 `Dio`에서 직접 설정하세요. 다른 폐기 클라이언트를 사용하려면 `revocation`으로 전달하세요. ## 모델 diff --git a/docs/i18n/ko/docusaurus-plugin-content-docs/current/upgrading.md b/docs/i18n/ko/docusaurus-plugin-content-docs/current/upgrading.md index 182ac72..4ec2f1d 100644 --- a/docs/i18n/ko/docusaurus-plugin-content-docs/current/upgrading.md +++ b/docs/i18n/ko/docusaurus-plugin-content-docs/current/upgrading.md @@ -15,6 +15,34 @@ title: 업그레이드 안정 버전 `flutter_web_auth_2`가 Kotlin Android 플러그인을 적용하는 동안에는 `android.builtInKotlin=false`와 `android.newDsl=false`를 유지하세요. 플러그인 적용은 유지하되 JVM 대상을 설정하는 코드를 `android.kotlinOptions`에서 `kotlin.compilerOptions`로 변경합니다. 향후 Flutter 버전에서는 종속성의 내장 Kotlin 지원이 필요할 수 있습니다. +## 0.2.0-beta.2에서 업그레이드 + +### 로그아웃하면 토큰이 폐기됩니다 + +`signOut`과 `signOutAll`은 이제 기기에서 토큰을 삭제하기 전에 서버에서 토큰을 폐기합니다. 네트워크 요청을 보내므로 요청 시간 초과에 도달할 때까지 시간이 걸릴 수 있습니다. 폐기에 실패하거나 서버가 폐기를 지원하지 않아도 토큰은 기기에서 삭제됩니다. + +- 이전 동작을 유지하려면 `mode: SignOutMode.localOnly`를 전달하세요. +- 대기 시간을 제한하려면 `timeout`을 전달하세요. +- Misskey 2026.9.0 이전 서버는 폐기를 지원하지 않습니다. 이러한 서버의 토큰은 이전과 마찬가지로 서버에서 계속 유효합니다. + +[로그아웃](./token-storage.md#signing-out)을 참조하세요. + +### 새 반환 타입 + +`signOut`은 이제 `Future`를, `signOutAll`은 `Future>`를 반환합니다. 결과를 await하기만 하는 코드는 변경할 필요가 없습니다. `MisskeyAuthManager`를 구현하거나 모킹하는 클래스는 시그니처를 업데이트해야 합니다. + +```dart +Future signOut( + AccountKey key, { + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +Future> signOutAll({ + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +``` + ## 0.2.0-beta.1로 업그레이드 ### Android에서는 다시 로그인해야 합니다 diff --git a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/error-handling.md b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/error-handling.md index 066ae34..01ed333 100644 --- a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/error-handling.md +++ b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/error-handling.md @@ -64,6 +64,14 @@ try { | `MiAuthSessionInvalidException` | 回调属于另一个会话,或检查 API 返回了 404 或 410 | | `MiAuthCheckFailedException` | 检查 API 返回了其他错误状态 | +### 令牌撤销 + +| 异常 | 返回条件 | +|---|---| +| `TokenRevocationException` | 服务器对撤销请求返回了错误状态或其他意外响应。`details` 中包含 HTTP 状态以及服务器返回的错误(如有) | + +撤销绝不会抛出异常。`signOut`、`signOutAll` 和 `MisskeyTokenRevocationClient.revoke` 会在 `TokenRevocationResult.error` 中返回原因,该原因也可能是 `NetworkException` 或 `ResponseParseException`。这些异常不包含 `originalException`,以免暴露请求中的令牌。请参阅[退出登录](./token-storage.md#signing-out)。 + ### 当前版本不会抛出的异常 `InvalidAuthConfigException`、`SecureStorageException` 和 `MiAuthNotSupportedException` 已定义,但当前版本不会抛出。 @@ -74,10 +82,13 @@ try { `loginWithOAuth` 和 `loginWithMiAuth` 会先保存令牌,再将账号设为活动账号。如果仅将账号设为活动账号这一步失败,令牌仍会保存,但账号不会成为活动账号。 +无法读取已存储的令牌时,`signOut` 和 `signOutAll` 不会抛出异常,而是不经撤销直接将其删除。删除令牌失败时,它们会抛出异常。 + ## 重试 - 获取 OAuth 服务器信息和调用 `/api/i` 时,如果发生超时、连接错误、其他传输错误,或 HTTP 429、500、502、503、504 状态,会重试,总计最多尝试三次。 - 令牌交换和 MiAuth 检查 API 不会重试。授权码和 MiAuth 会话都只能使用一次,即使响应丢失,服务器也可能已完成请求。请从头重新进行身份验证。 +- 令牌撤销不会重试。请参阅[超时与重试](./token-storage.md#timeout-and-retries)。 ## 身份验证后登录失败时 diff --git a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/token-storage.md b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/token-storage.md index de26dc4..1f132f2 100644 --- a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/token-storage.md +++ b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/token-storage.md @@ -23,15 +23,103 @@ final active = await auth.getActive(); await auth.clearActive(); // 退出登录 -await auth.signOut(key); // 删除一个账号的令牌 -await auth.signOutAll(); // 删除所有账号的令牌 +await auth.signOut(key); // 撤销并删除一个账号的令牌 +await auth.signOutAll(); // 撤销并删除所有账号的令牌 ``` -退出登录只会删除设备上的令牌,不会在服务器上撤销令牌。 +## 退出登录 {#signing-out} -## 超时 +退出登录时,会先在服务器上撤销令牌,然后将其从设备上删除。撤销需要 Misskey 2026.9.0 或更高版本,该版本允许应用令牌通过 `/api/i/revoke-token` 撤销自身。无论权限如何,MiAuth 令牌和 OAuth 令牌都可以撤销。 -`MisskeyAuthManager.defaultInstance()` 使用默认超时:连接为 10 秒,发送和接收各为 20 秒。如需更改,请自行构建 `MisskeyAuthManager`。`MisskeyAuthManager` 的超时仅适用于它自身对 `/api/i` 的请求,因此也要将超时传递给每个客户端: +```dart +final result = await auth.signOut(key); +final revocation = result.revocation; +if (revocation == null) { + // 未尝试撤销。请参阅 result.skipReason。 +} else if (revocation.isInvalidated) { + // revoked 或 alreadyInvalid:该令牌已无法在服务器上使用。 +} else if (revocation.status == TokenRevocationStatus.unsupported) { + // 服务器版本低于 2026.9.0。令牌在服务器上仍然有效。 +} else { + // failed:网络错误、超时或意外的响应。 +} +``` + +### 模式 + +传入 `mode` 可选择如何处理设备上的令牌: + +| `SignOutMode` | 撤销 | 从设备删除 | +|---|---|---| +| `revokeAndDelete`(默认) | 是 | 始终删除,无论撤销结果如何 | +| `revokeOrKeep` | 是 | 仅当结果为 `revoked` 或 `alreadyInvalid` 时 | +| `localOnly` | 否 | 始终删除 | + +使用 `revokeOrKeep` 时,无法撤销的令牌会保留在存储中,以便用户稍后重试。不支持撤销的服务器始终返回 `unsupported`;因其他原因被服务器拒绝的账号(例如已被冻结的账号)可能每次都会失败。要从设备上移除此类账号,请使用 `SignOutMode.localOnly` 再次退出登录。 + +如果令牌未保存或无法读取(例如存储的数据已损坏),则无论使用哪种模式,都会直接删除,不进行撤销。 + +### 结果 + +`signOut` 返回一个 `SignOutResult`,`signOutAll` 按 `listAccounts` 的顺序为每个账号返回一个 `SignOutResult`: + +| 字段 | 含义 | +|---|---| +| `key` | 对应的账号 | +| `revocation` | `TokenRevocationResult`;如果未尝试撤销,则为 `null` | +| `skipReason` | 未尝试撤销的原因:`localOnly`、`noStoredToken` 或 `unreadableToken`。如果已尝试撤销,则为 `null` | +| `deleted` | 令牌是否已从设备上删除 | + +`TokenRevocationResult` 包含以下字段: + +| 字段 | 含义 | +|---|---| +| `status` | `revoked`、`alreadyInvalid`、`unsupported` 或 `failed` | +| `isInvalidated` | 结果为 `revoked` 和 `alreadyInvalid` 时为 `true` | +| `statusCode` | HTTP 状态;如果未收到响应,则为 `null` | +| `errorCode` | Misskey 错误代码(如果有),例如 `RATE_LIMIT_EXCEEDED` | +| `error` | `unsupported` 和 `failed` 的原因:通常错误响应或意外响应为 `TokenRevocationException`,网络错误或超时为 `NetworkException` | + +`alreadyInvalid` 表示服务器无法识别该令牌:令牌已被撤销,或账号已被删除。它与 `revoked` 同等对待。 + +撤销失败会在结果中报告,绝不会抛出异常。删除设备上的令牌时发生的错误仍会像以前一样抛出;`signOutAll` 会先尝试删除所有账号,然后抛出第一个错误。 + +`deleted` 在两种情况下为 `false`:`revokeOrKeep` 保留了令牌;或者在撤销过程中,同一账号保存了新令牌,例如用户再次登录。新令牌从未被撤销,因此不会被删除。 + +### 超时与重试 {#timeout-and-retries} + +撤销不会重试。如果未指定 `timeout`,无响应的请求会一直等待,直到达到请求超时(请参阅[超时](#timeouts))。传入 `timeout` 可限制等待时间: + +```dart +await auth.signOut(key, timeout: const Duration(seconds: 5)); +await auth.signOutAll(timeout: const Duration(seconds: 5)); +``` + +`signOutAll` 会并行撤销所有账号,所有请求共享一个从调用时开始计算的期限。读取和删除已保存的令牌不会因超时而中断。超时的请求会报告为 `failed`。服务器可能仍已撤销该令牌:如果令牌被保留(例如使用 `revokeOrKeep`),再次撤销会报告 `alreadyInvalid`。 + +### 不通过管理器撤销 + +如果自行存储令牌,请直接使用 `MisskeyTokenRevocationClient`。它只在服务器上撤销令牌,不会操作任何存储: + +```dart +final revocation = MisskeyTokenRevocationClient(); +final result = await revocation.revoke( + host: 'misskey.io', + accessToken: token, + timeout: const Duration(seconds: 5), +); +if (result.isInvalidated) { + // 从自己的存储中删除该令牌。 +} +``` + +`revoke` 绝不会抛出异常,并返回相同的 `TokenRevocationResult`。客户端会在请求体中发送令牌。如果传入自己的 `Dio`,其拦截器可以看到令牌,因此请勿记录请求体。 + +请传入通过 MiAuth 或 OAuth 颁发给应用的令牌。Misskey 网页客户端使用的会话令牌不是应用令牌:服务器不会撤销它,但仍返回 204,因此即使令牌依然有效,结果也会是 `revoked`。 + +## 超时 {#timeouts} + +`MisskeyAuthManager.defaultInstance()` 使用默认超时:连接为 10 秒,发送和接收各为 20 秒。如需更改,请自行构建 `MisskeyAuthManager`。`MisskeyAuthManager` 的超时适用于它自身的请求,即 `/api/i` 和令牌撤销,因此也要将超时传递给每个客户端: ```dart const timeout = Duration(seconds: 30); @@ -43,7 +131,7 @@ final auth = MisskeyAuthManager( ); ``` -各构造函数都接受 `connectTimeout`、`sendTimeout` 和 `receiveTimeout`。它们也接受 `dio`。客户端会将超时参数应用于传入的 `Dio`,但如果传入了 `dio`,`MisskeyAuthManager` 会忽略这些参数;此时请直接配置该 `Dio`。 +各构造函数都接受 `connectTimeout`、`sendTimeout` 和 `receiveTimeout`。它们也接受 `dio`。`MisskeyOAuthClient` 和 `MisskeyMiAuthClient` 会将超时参数应用于传入的 `Dio`。`MisskeyTokenRevocationClient` 仅将这些参数应用于自身的请求,不会修改传入的 `Dio`。如果传入了 `dio`,`MisskeyAuthManager` 会忽略这些参数;此时请直接配置该 `Dio`。如需使用其他撤销客户端,请通过 `revocation` 传入。 ## 模型 diff --git a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/upgrading.md b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/upgrading.md index 7f0f930..06b5545 100644 --- a/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/upgrading.md +++ b/docs/i18n/zh-Hans/docusaurus-plugin-content-docs/current/upgrading.md @@ -15,6 +15,34 @@ title: 升级说明 在稳定版 `flutter_web_auth_2` 仍应用 Kotlin Android 插件期间,请保留 `android.builtInKotlin=false` 和 `android.newDsl=false`。保留该插件,但将 `android.kotlinOptions` 替换为 `kotlin.compilerOptions` 来配置其 JVM 目标。未来的 Flutter 版本可能要求依赖项支持内置 Kotlin。 +## 从 0.2.0-beta.2 升级 + +### 退出登录会撤销令牌 + +`signOut` 和 `signOutAll` 现在会先在服务器上撤销令牌,再将其从设备上删除。它们会发出网络请求,因此耗时可能长达请求超时时间。即使撤销失败或服务器不支持撤销,令牌仍会从设备上删除。 + +- 如需保留以前的行为,请传入 `mode: SignOutMode.localOnly`。 +- 如需限制等待时间,请传入 `timeout`。 +- Misskey 2026.9.0 之前的服务器不支持撤销。与以前一样,这些服务器上的令牌仍然有效。 + +请参阅[退出登录](./token-storage.md#signing-out)。 + +### 新的返回类型 + +`signOut` 现在返回 `Future`,`signOutAll` 返回 `Future>`。仅对它们使用 await 的代码无需更改。实现或模拟 `MisskeyAuthManager` 的类必须更新方法签名: + +```dart +Future signOut( + AccountKey key, { + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +Future> signOutAll({ + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, +}); +``` + ## 升级到 0.2.0-beta.1 ### Android 用户必须重新登录 diff --git a/example/lib/i18n/de.i18n.json b/example/lib/i18n/de.i18n.json index 474b172..4821dd3 100644 --- a/example/lib/i18n/de.i18n.json +++ b/example/lib/i18n/de.i18n.json @@ -44,6 +44,8 @@ "empty": "Keine angemeldeten Konten", "savedAt": "Gespeichert: $date", "delete": "Dieses Konto entfernen", + "revokeUnsupported": "Von diesem Gerät entfernt. Dieser Server unterstützt das Widerrufen von Tokens nicht, daher bleibt das Token auf dem Server gültig", + "revokeFailed": "Von diesem Gerät entfernt, aber das Token konnte auf dem Server nicht widerrufen werden", "activeChanged": "Aktives Konto geändert: $account" }, "validation": { diff --git a/example/lib/i18n/en.i18n.json b/example/lib/i18n/en.i18n.json index 83ad905..1ba2aef 100644 --- a/example/lib/i18n/en.i18n.json +++ b/example/lib/i18n/en.i18n.json @@ -44,6 +44,8 @@ "empty": "No signed-in accounts", "savedAt": "Saved: $date", "delete": "Remove this account", + "revokeUnsupported": "Removed from this device. This server does not support token revocation, so the token stays valid on the server", + "revokeFailed": "Removed from this device, but the token could not be revoked on the server", "activeChanged": "Active account changed: $account" }, "validation": { diff --git a/example/lib/i18n/fr.i18n.json b/example/lib/i18n/fr.i18n.json index a13e9ee..9b9facc 100644 --- a/example/lib/i18n/fr.i18n.json +++ b/example/lib/i18n/fr.i18n.json @@ -44,6 +44,8 @@ "empty": "Aucun compte connecté", "savedAt": "Enregistré : $date", "delete": "Supprimer ce compte", + "revokeUnsupported": "Supprimé de cet appareil. Ce serveur ne prend pas en charge la révocation des jetons ; le jeton reste donc valide sur le serveur", + "revokeFailed": "Supprimé de cet appareil, mais le jeton n’a pas pu être révoqué sur le serveur", "activeChanged": "Compte actif modifié : $account" }, "validation": { diff --git a/example/lib/i18n/ja.i18n.json b/example/lib/i18n/ja.i18n.json index 1aabc2b..2999a9b 100644 --- a/example/lib/i18n/ja.i18n.json +++ b/example/lib/i18n/ja.i18n.json @@ -44,6 +44,8 @@ "empty": "ログイン済みのアカウントはありません", "savedAt": "保存: $date", "delete": "このアカウントを削除", + "revokeUnsupported": "この端末から削除しました。このサーバーはトークンの失効に対応していないため、サーバー上のトークンは有効なままです", + "revokeFailed": "この端末から削除しましたが、サーバー上のトークンを失効できませんでした", "activeChanged": "アクティブなアカウントを変更: $account" }, "validation": { diff --git a/example/lib/i18n/ko.i18n.json b/example/lib/i18n/ko.i18n.json index b42d826..6aebfdc 100644 --- a/example/lib/i18n/ko.i18n.json +++ b/example/lib/i18n/ko.i18n.json @@ -44,6 +44,8 @@ "empty": "로그인한 계정이 없습니다", "savedAt": "저장됨: $date", "delete": "이 계정 삭제", + "revokeUnsupported": "이 기기에서 삭제했습니다. 이 서버는 토큰 폐기를 지원하지 않으므로 서버의 토큰은 계속 유효합니다", + "revokeFailed": "이 기기에서 삭제했지만 서버의 토큰을 폐기하지 못했습니다", "activeChanged": "활성 계정을 변경했습니다: $account" }, "validation": { diff --git a/example/lib/i18n/zh-Hans.i18n.json b/example/lib/i18n/zh-Hans.i18n.json index f3dcbab..fa04110 100644 --- a/example/lib/i18n/zh-Hans.i18n.json +++ b/example/lib/i18n/zh-Hans.i18n.json @@ -44,6 +44,8 @@ "empty": "没有已登录的账号", "savedAt": "保存时间:$date", "delete": "删除此账号", + "revokeUnsupported": "已从此设备删除。此服务器不支持吊销令牌,服务器上的令牌仍然有效", + "revokeFailed": "已从此设备删除,但未能在服务器上吊销令牌", "activeChanged": "已更改活动账号:$account" }, "validation": { diff --git a/example/lib/main.dart b/example/lib/main.dart index 8912111..e102445 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -757,8 +757,20 @@ class _AuthExamplePageState extends State { trailing: IconButton( icon: const Icon(Icons.delete, color: Colors.red), onPressed: () async { - await _auth.signOut(key); + // サーバー上で失効させてから、端末上のトークンを削除する + final result = await _auth.signOut(key); if (mounted) setState(() {}); + final message = switch (result.revocation?.status) { + TokenRevocationStatus.unsupported => + t.accounts.revokeUnsupported, + TokenRevocationStatus.failed => + t.accounts.revokeFailed, + _ => null, + }; + if (message == null || !context.mounted) return; + ScaffoldMessenger.of(context) + ..hideCurrentSnackBar() + ..showSnackBar(SnackBar(content: Text(message))); }, tooltip: t.accounts.delete, ), diff --git a/lib/misskey_auth.dart b/lib/misskey_auth.dart index e254d5a..dd22e80 100644 --- a/lib/misskey_auth.dart +++ b/lib/misskey_auth.dart @@ -1,10 +1,13 @@ // Models export 'src/models/oauth_models.dart'; export 'src/models/miauth_models.dart'; +export 'src/models/token_revocation_models.dart'; +export 'src/models/sign_out_models.dart'; // API export 'src/api/misskey_oauth_client.dart'; export 'src/api/misskey_miauth_client.dart'; +export 'src/api/misskey_token_revocation_client.dart'; // Exceptions export 'src/exceptions/misskey_auth_exception.dart'; diff --git a/lib/src/api/misskey_token_revocation_client.dart b/lib/src/api/misskey_token_revocation_client.dart new file mode 100644 index 0000000..06ea75a --- /dev/null +++ b/lib/src/api/misskey_token_revocation_client.dart @@ -0,0 +1,207 @@ +import 'dart:async'; + +import 'package:dio/dio.dart'; + +import '../exceptions/misskey_auth_exception.dart'; +import '../models/token_revocation_models.dart'; +import '../net/response.dart'; + +/// アクセストークンをサーバー上で失効させるクライアント +/// +/// Misskey 2026.9.0 以降の `/api/i/revoke-token` を使い、渡したトークン自身を +/// 失効させる。MiAuth と OAuth のどちらのトークンにも使え、権限は問わない。 +/// 端末に保存したトークンは扱わない(`MisskeyAuthManager.signOut` を参照) +/// +/// MiAuth / OAuth でアプリに発行されたトークンを渡すこと。Web クライアントの +/// セッショントークンは、サーバーが失効させずに 204 を返すため、有効なまま +/// [TokenRevocationStatus.revoked] になる +class MisskeyTokenRevocationClient { + final Dio _dio; + final Duration? _connectTimeout; + final Duration? _sendTimeout; + final Duration? _receiveTimeout; + + /// 失効の通信で使用するHTTPクライアント + /// + /// [dio] を渡さない場合は、次のデフォルトタイムアウトで初期化 + /// - 接続: 10秒 + /// - 送信: 20秒 + /// - 受信: 20秒 + /// + /// [dio] を渡した場合、タイムアウトの引数はこのクライアントのリクエストにだけ + /// 適用し、渡された `Dio` の設定は変更しない。渡した `Dio` のインターセプターは + /// リクエストボディのトークンを参照できる点に注意 + MisskeyTokenRevocationClient({ + Dio? dio, + Duration? connectTimeout, + Duration? sendTimeout, + Duration? receiveTimeout, + }) : _dio = + dio ?? + Dio( + BaseOptions( + connectTimeout: connectTimeout ?? const Duration(seconds: 10), + sendTimeout: sendTimeout ?? const Duration(seconds: 20), + receiveTimeout: receiveTimeout ?? const Duration(seconds: 20), + ), + ), + _connectTimeout = connectTimeout, + _sendTimeout = sendTimeout, + _receiveTimeout = receiveTimeout; + + /// [host] のサーバー上で [accessToken] を失効させる + /// + /// 例外は投げず、結果を [TokenRevocationResult] で返す。自動で再送しない。 + /// [timeout] を渡すと、リクエスト全体をその時間で打ち切り + /// [TokenRevocationStatus.failed] を返す。打ち切った場合や応答を受け取れな + /// かった場合でも、サーバー側では失効している可能性がある。再度呼ぶと + /// [TokenRevocationStatus.alreadyInvalid] になる + Future revoke({ + required String host, + required String accessToken, + Duration? timeout, + }) async { + if (timeout != null && timeout <= Duration.zero) { + return _timedOut(timeout); + } + // サーバーやインターセプターの文言がトークンを含んでも、結果に載せない + String redact(String text) => + accessToken.isEmpty ? text : text.replaceAll(accessToken, '***'); + + final cancelToken = CancelToken(); + final request = _send(host, accessToken, cancelToken, redact); + if (timeout == null) return request; + + // キャンセル後にインターセプターが完了しない場合も、期限で結果を返す + final expired = Completer(); + final timer = Timer(timeout, () { + cancelToken.cancel(); + expired.complete(_timedOut(timeout)); + }); + try { + return await Future.any([request, expired.future]); + } finally { + timer.cancel(); + } + } + + /// 失効のリクエストを送り、結果に変換する。例外は投げない + Future _send( + String host, + String accessToken, + CancelToken cancelToken, + String Function(String) redact, + ) async { + try { + // 型を String にして Dio に JSON を解釈させない。不正な JSON でもステータスで分類する + final response = await _dio.post( + 'https://$host/api/i/revoke-token', + data: {'i': accessToken, 'token': accessToken}, + options: Options( + contentType: 'application/json', + connectTimeout: _connectTimeout, + sendTimeout: _sendTimeout, + receiveTimeout: _receiveTimeout, + // エラー応答も分類するため、ステータスでは例外にしない + validateStatus: (_) => true, + ), + cancelToken: cancelToken, + ); + return _classify(response.statusCode, response.data, redact); + } on DioException catch (e) { + final response = e.response; + // インターセプターがエラー応答として reject した場合 + if (e.type == DioExceptionType.badResponse && response != null) { + return _classify(response.statusCode, response.data, redact); + } + // キャンセルするのは期限のタイマーだけ(結果は revoke 側で返す) + if (e.type == DioExceptionType.cancel) { + return const TokenRevocationResult( + status: TokenRevocationStatus.failed, + error: NetworkException(details: 'The request was cancelled'), + ); + } + // DioException は送信データ(トークン)を持つため、原因に含めない + final cause = e.error; + if (cause is FormatException) { + return TokenRevocationResult( + status: TokenRevocationStatus.failed, + statusCode: response?.statusCode, + error: ResponseParseException(details: redact(cause.message)), + ); + } + return TokenRevocationResult( + status: TokenRevocationStatus.failed, + error: NetworkException( + details: redact(e.message ?? 'type=${e.type.name}'), + ), + ); + } catch (e) { + // インターセプターなどが投げた想定外の例外 + return TokenRevocationResult( + status: TokenRevocationStatus.failed, + error: MisskeyAuthException( + 'Token revocation failed unexpectedly.', + details: e.runtimeType.toString(), + ), + ); + } + } + + /// 応答をステータスとエラーコードで分類する + TokenRevocationResult _classify( + int? status, + Object? data, + String Function(String) redact, + ) { + if (status == 204) { + return TokenRevocationResult( + status: TokenRevocationStatus.revoked, + statusCode: status, + ); + } + Map? body; + try { + body = jsonObjectOf(data); + } on FormatException { + body = null; + } + final error = body?['error']; + final code = error is Map ? error['code'] : null; + // 分類は元のコードで行い、結果に載せる値だけ伏せる + final rawCode = code is String ? code : null; + final errorCode = rawCode == null ? null : redact(rawCode); + + // トークンが存在しない: 失効済み、またはアカウント削除済み + if (status == 401 && rawCode == 'AUTHENTICATION_FAILED') { + return TokenRevocationResult( + status: TokenRevocationStatus.alreadyInvalid, + statusCode: status, + errorCode: errorCode, + ); + } + // 2026.9.0 未満はアプリのトークンからの呼び出しを ACCESS_DENIED で拒否する + final unsupported = + (status == 400 && rawCode == 'ACCESS_DENIED') || status == 404; + final summary = body == null ? null : errorSummaryOf(body); + return TokenRevocationResult( + status: unsupported + ? TokenRevocationStatus.unsupported + : TokenRevocationStatus.failed, + statusCode: status, + errorCode: errorCode, + error: TokenRevocationException( + details: summary == null + ? 'status=$status' + : 'status=$status, ${redact(summary)}', + ), + ); + } + + TokenRevocationResult _timedOut(Duration timeout) => TokenRevocationResult( + status: TokenRevocationStatus.failed, + error: NetworkException( + details: 'Timed out after ${timeout.inMilliseconds} ms', + ), + ); +} diff --git a/lib/src/auth/misskey_auth_manager.dart b/lib/src/auth/misskey_auth_manager.dart index 35b17ea..03f8295 100644 --- a/lib/src/auth/misskey_auth_manager.dart +++ b/lib/src/auth/misskey_auth_manager.dart @@ -2,9 +2,12 @@ import 'package:dio/dio.dart'; import '../api/misskey_miauth_client.dart'; import '../api/misskey_oauth_client.dart'; +import '../api/misskey_token_revocation_client.dart'; import '../exceptions/misskey_auth_exception.dart'; import '../models/miauth_models.dart'; import '../models/oauth_models.dart'; +import '../models/sign_out_models.dart'; +import '../models/token_revocation_models.dart'; import '../store/account_key.dart'; import '../store/secure_token_store.dart'; import '../store/stored_token.dart'; @@ -23,23 +26,42 @@ class MisskeyAuthManager { final TokenStore store; final Dio dio; + /// サインアウト時にサーバー上のトークンを失効させるクライアント + final MisskeyTokenRevocationClient revocation; + + /// [revocation] を渡さない場合は、[dio] を使う失効クライアントを組み立てる。 + /// タイムアウトの引数は、[dio] を渡さない場合に `/api/i` と失効の通信に適用する MisskeyAuthManager({ - required this.miauth, - required this.oauth, - required this.store, + required MisskeyMiAuthClient miauth, + required MisskeyOAuthClient oauth, + required TokenStore store, + MisskeyTokenRevocationClient? revocation, Dio? dio, Duration? connectTimeout, Duration? sendTimeout, Duration? receiveTimeout, - }) : dio = - dio ?? - Dio( - BaseOptions( - connectTimeout: connectTimeout ?? const Duration(seconds: 10), - sendTimeout: sendTimeout ?? const Duration(seconds: 20), - receiveTimeout: receiveTimeout ?? const Duration(seconds: 20), + }) : this._( + miauth, + oauth, + store, + revocation, + dio ?? + Dio( + BaseOptions( + connectTimeout: connectTimeout ?? const Duration(seconds: 10), + sendTimeout: sendTimeout ?? const Duration(seconds: 20), + receiveTimeout: receiveTimeout ?? const Duration(seconds: 20), + ), ), - ); + ); + + MisskeyAuthManager._( + this.miauth, + this.oauth, + this.store, + MisskeyTokenRevocationClient? revocation, + this.dio, + ) : revocation = revocation ?? MisskeyTokenRevocationClient(dio: dio); /// 依存を既定実装で組み立てたインスタンスを返す factory MisskeyAuthManager.defaultInstance() => MisskeyAuthManager( @@ -159,9 +181,160 @@ class MisskeyAuthManager { /// 保存済みアカウントの一覧を取得 Future> listAccounts() => store.list(); - /// 指定アカウントのトークンを削除(サインアウト相当) - Future signOut(AccountKey key) => store.delete(key); + /// 指定アカウントをサインアウトする + /// + /// 既定([SignOutMode.revokeAndDelete])では、サーバー上のトークンの失効を + /// 試みてから、結果にかかわらず端末上のトークンを削除する。失効の結果は + /// 例外ではなく [SignOutResult.revocation] で返す。保存されたトークンが + /// 無い、または読み出せない場合は、失効を試みずに削除する。 + /// + /// [timeout] は失効のリクエスト全体の期限。省略時は通信のタイムアウトに従う。 + /// 端末上の削除に失敗した場合は、ストレージの例外をそのまま投げる + Future signOut( + AccountKey key, { + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, + }) async { + if (mode == SignOutMode.localOnly) { + await store.delete(key); + return SignOutResult( + key: key, + skipReason: RevocationSkipReason.localOnly, + deleted: true, + ); + } + final attempt = await _revokeStored(key, _remainingOf(timeout)); + return _deleteAfter(attempt, mode); + } + + /// 保存済みのすべてのアカウントをサインアウトする + /// + /// 各アカウントの扱いは [signOut] と同じ。失効は全アカウントで並列に試み、 + /// [timeout] は呼び出しの時点から数えた、すべての失効に共通の期限として扱う + /// (端末上の読み書きは打ち切らない)。結果は [listAccounts] の順に返す。 + /// 端末上の削除はすべて試み、失敗したものがあれば最初の例外を最後に投げる + Future> signOutAll({ + SignOutMode mode = SignOutMode.revokeAndDelete, + Duration? timeout, + }) async { + // 期限はアカウント一覧の読み出しも含め、呼び出しの時点から数える + final remaining = _remainingOf(timeout); + final entries = await store.list(); + if (mode == SignOutMode.localOnly) { + await store.clearAll(); + return [ + for (final entry in entries) + SignOutResult( + key: entry.key, + skipReason: RevocationSkipReason.localOnly, + deleted: true, + ), + ]; + } + final attempts = await Future.wait([ + for (final entry in entries) _revokeStored(entry.key, remaining), + ]); + // 失効を待つ間に追加されたアカウントを消さないよう、clearAll は使わない + final results = []; + Object? firstError; + StackTrace? firstStackTrace; + for (final attempt in attempts) { + try { + results.add(await _deleteAfter(attempt, mode)); + } catch (e, st) { + firstError ??= e; + firstStackTrace ??= st; + } + } + if (firstError != null) { + Error.throwWithStackTrace(firstError, firstStackTrace!); + } + return results; + } + + /// [timeout] を起点からの期限とみなし、呼ぶたびに残り時間を返す関数を作る + Duration? Function() _remainingOf(Duration? timeout) { + if (timeout == null) return () => null; + final stopwatch = Stopwatch()..start(); + return () => timeout - stopwatch.elapsed; + } + + /// 保存されたトークンを読み出し、サーバー上で失効を試みる + Future<_RevocationAttempt> _revokeStored( + AccountKey key, + Duration? Function() remaining, + ) async { + final StoredToken? token; + try { + token = await store.read(key); + } catch (_) { + return _RevocationAttempt.skipped( + key, + RevocationSkipReason.unreadableToken, + ); + } + if (token == null) { + return _RevocationAttempt.skipped( + key, + RevocationSkipReason.noStoredToken, + ); + } + final result = await revocation.revoke( + host: key.host, + accessToken: token.accessToken, + timeout: remaining(), + ); + return _RevocationAttempt(key, token.accessToken, result); + } + + /// 失効の結果と [mode] に従って、端末上のトークンを削除する + Future _deleteAfter( + _RevocationAttempt attempt, + SignOutMode mode, + ) async { + final key = attempt.key; + final result = attempt.result; + if (result == null) { + await store.delete(key); + return SignOutResult( + key: key, + skipReason: attempt.skipReason, + deleted: true, + ); + } + final keep = + (mode == SignOutMode.revokeOrKeep && !result.isInvalidated) || + await _replacedSince(key, attempt.accessToken!); + if (!keep) await store.delete(key); + return SignOutResult(key: key, revocation: result, deleted: !keep); + } + + /// 失効を待つ間に、同じアカウントへ別のトークンが保存されたか + /// + /// 再ログインで保存されたトークンを、失効させないまま削除しないために確認する + Future _replacedSince(AccountKey key, String accessToken) async { + try { + final current = await store.read(key); + return current != null && current.accessToken != accessToken; + } catch (_) { + return false; + } + } +} + +/// 1アカウント分の失効の試行結果 +class _RevocationAttempt { + final AccountKey key; + + /// 失効を試みたトークン。試みなかった場合は `null` + final String? accessToken; + final TokenRevocationResult? result; + final RevocationSkipReason? skipReason; + + const _RevocationAttempt(this.key, this.accessToken, this.result) + : skipReason = null; - /// すべてのトークンを削除(全サインアウト) - Future signOutAll() => store.clearAll(); + const _RevocationAttempt.skipped(this.key, this.skipReason) + : accessToken = null, + result = null; } diff --git a/lib/src/exceptions/misskey_auth_exception.dart b/lib/src/exceptions/misskey_auth_exception.dart index 369f923..1c675cf 100644 --- a/lib/src/exceptions/misskey_auth_exception.dart +++ b/lib/src/exceptions/misskey_auth_exception.dart @@ -124,6 +124,14 @@ class MiAuthSessionInvalidException extends MisskeyAuthException { : super('MiAuth session is invalid or expired.'); } +/// トークンの失効を求めたサーバーがエラー応答を返したことを表す +/// +/// `TokenRevocationResult.error` として返すだけで、投げない +class TokenRevocationException extends MisskeyAuthException { + const TokenRevocationException({super.details}) + : super('The server did not revoke the token.'); +} + /// サーバーが MiAuth に対応していない可能性がある場合の例外(必要に応じて使用) class MiAuthNotSupportedException extends MisskeyAuthException { const MiAuthNotSupportedException({super.details, super.originalException}) diff --git a/lib/src/models/sign_out_models.dart b/lib/src/models/sign_out_models.dart new file mode 100644 index 0000000..8968b51 --- /dev/null +++ b/lib/src/models/sign_out_models.dart @@ -0,0 +1,66 @@ +import '../store/account_key.dart'; +import 'token_revocation_models.dart'; + +/// サインアウト時に、サーバー上のトークンをどう扱うか +enum SignOutMode { + /// 失効させず、端末上のトークンだけを削除する + localOnly, + + /// 失効を試み、結果にかかわらず端末上のトークンを削除する + revokeAndDelete, + + /// 失効を試み、失効を確認できた場合だけ端末上のトークンを削除する + /// + /// [TokenRevocationStatus.unsupported] と [TokenRevocationStatus.failed] では + /// 削除しない。失効に対応していないサーバーのアカウントは、 + /// [SignOutMode.localOnly] で削除する + revokeOrKeep, +} + +/// 失効を試みなかった理由 +enum RevocationSkipReason { + /// [SignOutMode.localOnly] が指定された + localOnly, + + /// 端末にトークンが保存されていなかった + noStoredToken, + + /// 保存されたトークンを読み出せなかった(破損など) + unreadableToken, +} + +/// 1アカウント分のサインアウトの結果 +class SignOutResult { + /// 対象のアカウント + final AccountKey key; + + /// 失効の結果。失効を試みなかった場合は `null`(理由は [skipReason]) + final TokenRevocationResult? revocation; + + /// 失効を試みなかった理由。試みた場合は `null` + final RevocationSkipReason? skipReason; + + /// 端末上のトークンを削除したか + /// + /// `false` になるのは、[SignOutMode.revokeOrKeep] で失効を確認できなかった + /// 場合と、失効を待つ間に同じアカウントのトークンが保存し直された場合 + final bool deleted; + + const SignOutResult({ + required this.key, + this.revocation, + this.skipReason, + required this.deleted, + }); + + @override + String toString() { + final parts = [ + 'key=$key', + if (revocation != null) 'revocation=$revocation', + if (skipReason != null) 'skipReason=${skipReason!.name}', + 'deleted=$deleted', + ]; + return 'SignOutResult(${parts.join(', ')})'; + } +} diff --git a/lib/src/models/token_revocation_models.dart b/lib/src/models/token_revocation_models.dart new file mode 100644 index 0000000..0aa925f --- /dev/null +++ b/lib/src/models/token_revocation_models.dart @@ -0,0 +1,58 @@ +import '../exceptions/misskey_auth_exception.dart'; + +/// トークン失効の結果の種類 +enum TokenRevocationStatus { + /// サーバーがトークンを失効させた + revoked, + + /// サーバーがトークンを認識しなかった(失効済み、またはアカウント削除済み) + alreadyInvalid, + + /// サーバーがアプリのトークンによる失効に対応していない(Misskey 2026.9.0 未満など) + unsupported, + + /// 通信の失敗や想定外の応答により、失効できたか分からない + failed, +} + +/// `/api/i/revoke-token` による失効の結果 +class TokenRevocationResult { + /// 結果の種類 + final TokenRevocationStatus status; + + /// HTTP ステータス。応答を受け取れなかった場合は `null` + final int? statusCode; + + /// エラー応答の `error.code`(例: `RATE_LIMIT_EXCEEDED`)。無い場合は `null` + final String? errorCode; + + /// [status] が [TokenRevocationStatus.unsupported] または + /// [TokenRevocationStatus.failed] のときの原因 + /// + /// 返すだけで投げない。トークンを含めないため `originalException` は持たない + final MisskeyAuthException? error; + + const TokenRevocationResult({ + required this.status, + this.statusCode, + this.errorCode, + this.error, + }); + + /// サーバー上でトークンが使えない状態になっているか + /// + /// [TokenRevocationStatus.revoked] と [TokenRevocationStatus.alreadyInvalid] で `true` + bool get isInvalidated => + status == TokenRevocationStatus.revoked || + status == TokenRevocationStatus.alreadyInvalid; + + @override + String toString() { + final parts = [ + 'status=${status.name}', + if (statusCode != null) 'statusCode=$statusCode', + if (errorCode != null) 'errorCode=$errorCode', + ]; + return 'TokenRevocationResult(${parts.join(', ')})'; + } +} diff --git a/lib/src/store/secure_token_store.dart b/lib/src/store/secure_token_store.dart index 37006ae..823bf9c 100644 --- a/lib/src/store/secure_token_store.dart +++ b/lib/src/store/secure_token_store.dart @@ -53,20 +53,27 @@ class SecureTokenStore implements TokenStore { @override /// 保存済みアカウントの一覧を返す + /// + /// トークンを読み出せないアカウントも、メタ情報なしで一覧に含める Future> list() async { final keys = await _readIndex(); final List entries = []; for (final k in keys) { - final token = await read(k); String? userName; DateTime? createdAt; - if (token != null) { - final user = token.user; - if (user != null) { - userName = - (user['name'] ?? user['username'] ?? user['userName']) as String?; + try { + final token = await read(k); + if (token != null) { + final user = token.user; + if (user != null) { + userName = + (user['name'] ?? user['username'] ?? user['userName']) + as String?; + } + createdAt = token.createdAt; } - createdAt = token.createdAt; + } catch (_) { + // 1件の破損や読み出し失敗で、他のアカウントを辿れなくしない } entries.add(AccountEntry(k, userName: userName, createdAt: createdAt)); } diff --git a/test/secure_token_store_test.dart b/test/secure_token_store_test.dart index 59c8f00..255ceec 100644 --- a/test/secure_token_store_test.dart +++ b/test/secure_token_store_test.dart @@ -54,6 +54,29 @@ void main() { final failing = SecureTokenStore(storage: FailingStorage()); await expectLater(failing.read(key), throwsA(isA())); }); + test('lists accounts whose token cannot be read', () async { + FlutterSecureStorage.setMockInitialValues({ + 'misskey_token::example.test::user1': 'not json', + 'misskey_token::example.test::user2': + '{"accessToken":"synthetic","tokenType":"MiAuth","user":{"name":42}}', + 'misskey_accounts_index': '[{"host":"example.test","accountId":"user1"},{"host":"example.test","accountId":"user2"}]', + }); + final entries = await store.list(); + expect(entries.map((e) => e.key), [key, other]); + expect(entries.map((e) => e.userName), [null, null]); + }); + test('lists accounts when the native read fails', () async { + final failing = SecureTokenStore( + storage: ControlledStorage( + before: (operation, k) async { + if (operation == 'read' && k == key.storageKey()) { + throw PlatformException(code: 'StorageError'); + } + }, + ), + ); + expect((await failing.list()).single.key, key); + }); group('write operations', () { const token = StoredToken(accessToken: 'synthetic', tokenType: 'MiAuth'); diff --git a/test/sign_out_test.dart b/test/sign_out_test.dart new file mode 100644 index 0000000..cb113f4 --- /dev/null +++ b/test/sign_out_test.dart @@ -0,0 +1,348 @@ +import 'dart:async'; + +import 'package:dio/dio.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:misskey_auth/misskey_auth.dart'; + +import 'support/fakes.dart'; + +const _a = AccountKey(host: 'a.test', accountId: 'userA'); +const _b = AccountKey(host: 'a.test', accountId: 'userB'); +const _c = AccountKey(host: 'c.test', accountId: 'userC'); + +/// 各失効結果を返すサーバー応答 +final _responses = { + TokenRevocationStatus.revoked: () => ResponseBody.fromString('', 204), + TokenRevocationStatus.alreadyInvalid: () => + _apiError(401, 'AUTHENTICATION_FAILED'), + TokenRevocationStatus.unsupported: () => _apiError(400, 'ACCESS_DENIED'), + TokenRevocationStatus.failed: () => _apiError(500, 'INTERNAL_ERROR'), +}; + +ResponseBody _apiError(int status, String code) => jsonBody({ + 'error': {'message': 'm', 'code': code, 'id': 'x'}, +}, status); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late MemoryTokenStore store; + late Dio dio; + late MisskeyAuthManager auth; + late List requests; + + /// 失効リクエストへの応答。既定は 204 + late FutureOr Function(RequestOptions) respond; + + setUp(() { + store = MemoryTokenStore(); + requests = []; + respond = (_) => ResponseBody.fromString('', 204); + dio = Dio() + ..httpClientAdapter = StubAdapter((options) { + requests.add(options); + return respond(options); + }); + auth = MisskeyAuthManager( + miauth: MisskeyMiAuthClient(), + oauth: MisskeyOAuthClient(), + store: store, + dio: dio, + ); + }); + tearDown(() => dio.close(force: true)); + + /// 失効したトークン(リクエストの `token`) + List revokedTokens() => [for (final r in requests) r.data['token']]; + + group('signOut', () { + test('revokes and deletes by default', () async { + store.seed(_a, 'tokenA'); + final result = await auth.signOut(_a); + expect(revokedTokens(), ['tokenA']); + expect( + requests.single.uri.toString(), + 'https://a.test/api/i/revoke-token', + ); + expect(result.key, _a); + expect(result.revocation!.status, TokenRevocationStatus.revoked); + expect(result.skipReason, isNull); + expect(result.deleted, isTrue); + expect(store.tokens, isEmpty); + }); + + test('localOnly deletes without reading or revoking', () async { + store.seed(_a, 'tokenA'); + final result = await auth.signOut(_a, mode: SignOutMode.localOnly); + expect(requests, isEmpty); + expect(store.calls, ['delete:userA']); + expect(result.revocation, isNull); + expect(result.skipReason, RevocationSkipReason.localOnly); + expect(result.deleted, isTrue); + }); + + for (final status in TokenRevocationStatus.values) { + test('revokeAndDelete deletes after ${status.name}', () async { + store.seed(_a, 'tokenA'); + respond = (_) => _responses[status]!(); + final result = await auth.signOut(_a); + expect(result.revocation!.status, status); + expect(result.deleted, isTrue); + expect(store.tokens, isEmpty); + }); + + final deletes = + status == TokenRevocationStatus.revoked || + status == TokenRevocationStatus.alreadyInvalid; + test( + 'revokeOrKeep ${deletes ? 'deletes' : 'keeps'} after ${status.name}', + () async { + store.seed(_a, 'tokenA'); + respond = (_) => _responses[status]!(); + final result = await auth.signOut(_a, mode: SignOutMode.revokeOrKeep); + expect(result.revocation!.status, status); + expect(result.deleted, deletes); + expect(store.tokens.containsKey(_a), !deletes); + }, + ); + } + + for (final mode in [ + SignOutMode.revokeAndDelete, + SignOutMode.revokeOrKeep, + ]) { + test('${mode.name} deletes an account without a token', () async { + store.index.add(_a); + final result = await auth.signOut(_a, mode: mode); + expect(requests, isEmpty); + expect(result.skipReason, RevocationSkipReason.noStoredToken); + expect(result.deleted, isTrue); + expect(store.index, isEmpty); + }); + + test('${mode.name} deletes an unreadable token', () async { + store.seed(_a, 'tokenA'); + store.throwOnRead.add(_a); + final result = await auth.signOut(_a, mode: mode); + expect(requests, isEmpty); + expect(result.skipReason, RevocationSkipReason.unreadableToken); + expect(result.deleted, isTrue); + expect(store.tokens, isEmpty); + }); + } + + test('throws when the local delete fails', () async { + store.seed(_a, 'tokenA'); + store.throwOnDelete.add(_a); + await expectLater(auth.signOut(_a), throwsA(isA())); + }); + + test('clears the active account only when it is deleted', () async { + store.seed(_a, 'tokenA'); + store.active = _a; + respond = (_) => _responses[TokenRevocationStatus.failed]!(); + await auth.signOut(_a, mode: SignOutMode.revokeOrKeep); + expect(store.active, _a); + await auth.signOut(_a); + expect(store.active, isNull); + }); + + test('keeps a token saved again while revoking', () async { + store.seed(_a, 'tokenA'); + respond = (_) { + // 失効を待つ間に同じアカウントで再ログインした + store.seed(_a, 'tokenA2'); + return ResponseBody.fromString('', 204); + }; + final result = await auth.signOut(_a); + expect(revokedTokens(), ['tokenA']); + expect(result.revocation!.status, TokenRevocationStatus.revoked); + expect(result.deleted, isFalse); + expect(store.tokens[_a]!.accessToken, 'tokenA2'); + }); + + test('gives up revoking after the timeout and still deletes', () async { + store.seed(_a, 'tokenA'); + respond = (_) => Completer().future; + final result = await auth.signOut( + _a, + timeout: const Duration(milliseconds: 50), + ); + expect(result.revocation!.status, TokenRevocationStatus.failed); + expect(result.revocation!.error, isA()); + expect(result.deleted, isTrue); + }); + }); + + group('signOutAll', () { + void seedAll() { + store.seed(_a, 'tokenA'); + store.seed(_b, 'tokenB'); + store.seed(_c, 'tokenC'); + } + + /// トークンごとの失効結果 + void respondBy(Map statuses) { + respond = (options) => _responses[statuses[options.data['token']]]!(); + } + + test('returns results in list order', () async { + seedAll(); + respondBy({ + 'tokenA': TokenRevocationStatus.failed, + 'tokenB': TokenRevocationStatus.revoked, + 'tokenC': TokenRevocationStatus.unsupported, + }); + final results = await auth.signOutAll(); + expect(results.map((r) => r.key), [_a, _b, _c]); + expect(results.map((r) => r.revocation!.status), [ + TokenRevocationStatus.failed, + TokenRevocationStatus.revoked, + TokenRevocationStatus.unsupported, + ]); + expect(results.every((r) => r.deleted), isTrue); + expect(store.tokens, isEmpty); + expect(store.calls, isNot(contains('clearAll'))); + }); + + test('revokes every account in parallel', () async { + seedAll(); + final pending = >[]; + respond = (_) { + final completer = Completer(); + pending.add(completer); + return completer.future; + }; + final future = auth.signOutAll(); + await pumpEventQueue(); + // どの応答も返る前に、すべてのリクエストが送られている + expect(revokedTokens(), unorderedEquals(['tokenA', 'tokenB', 'tokenC'])); + for (final completer in pending) { + completer.complete(ResponseBody.fromString('', 204)); + } + final results = await future; + expect(results.map((r) => r.revocation!.status).toSet(), { + TokenRevocationStatus.revoked, + }); + }); + + test('revokeOrKeep keeps only accounts not invalidated', () async { + seedAll(); + store.active = _c; + respondBy({ + 'tokenA': TokenRevocationStatus.alreadyInvalid, + 'tokenB': TokenRevocationStatus.failed, + 'tokenC': TokenRevocationStatus.unsupported, + }); + final results = await auth.signOutAll(mode: SignOutMode.revokeOrKeep); + expect(results.map((r) => r.deleted), [true, false, false]); + expect(store.index, [_b, _c]); + expect(store.active, _c); + }); + + test('applies one deadline to the whole operation', () async { + seedAll(); + respond = (options) => options.uri.host == 'c.test' + ? Completer().future + : ResponseBody.fromString('', 204); + final stopwatch = Stopwatch()..start(); + final results = await auth.signOutAll( + timeout: const Duration(milliseconds: 100), + ); + expect(stopwatch.elapsed, lessThan(const Duration(seconds: 5))); + expect(results.map((r) => r.revocation!.status), [ + TokenRevocationStatus.revoked, + TokenRevocationStatus.revoked, + TokenRevocationStatus.failed, + ]); + expect(results.every((r) => r.deleted), isTrue); + }); + + test('counts the deadline from the call, including list', () async { + seedAll(); + store.beforeList = () => + Future.delayed(const Duration(milliseconds: 150)); + final results = await auth.signOutAll( + timeout: const Duration(milliseconds: 100), + ); + // 一覧を読む間に期限が過ぎたため、失効は送らない + expect(requests, isEmpty); + expect(results.map((r) => r.revocation!.status).toSet(), { + TokenRevocationStatus.failed, + }); + expect(results.every((r) => r.deleted), isTrue); + }); + + test('localOnly clears the store without reading or revoking', () async { + seedAll(); + final results = await auth.signOutAll(mode: SignOutMode.localOnly); + expect(requests, isEmpty); + expect(store.calls, ['list', 'clearAll']); + expect(results.map((r) => r.key), [_a, _b, _c]); + expect(results.map((r) => r.skipReason).toSet(), { + RevocationSkipReason.localOnly, + }); + }); + + test('deletes an unreadable token and revokes the others', () async { + seedAll(); + store.throwOnRead.add(_b); + final results = await auth.signOutAll(); + expect(revokedTokens(), unorderedEquals(['tokenA', 'tokenC'])); + expect(results[1].skipReason, RevocationSkipReason.unreadableToken); + expect(results.every((r) => r.deleted), isTrue); + expect(store.index, isEmpty); + }); + + test('propagates a failure to list the accounts', () async { + store.throwOnList = true; + await expectLater(auth.signOutAll(), throwsA(isA())); + expect(requests, isEmpty); + }); + + test('tries every delete before throwing the first error', () async { + seedAll(); + store.throwOnDelete.addAll([_a, _b]); + await expectLater(auth.signOutAll(), throwsA(isA())); + expect(store.calls.where((c) => c.startsWith('delete')), [ + 'delete:userA', + 'delete:userB', + 'delete:userC', + ]); + expect(store.index, [_a, _b]); + }); + + test('keeps an account added while revoking', () async { + store.seed(_a, 'tokenA'); + const added = AccountKey(host: 'a.test', accountId: 'added'); + respond = (_) { + store.seed(added, 'tokenAdded'); + return ResponseBody.fromString('', 204); + }; + final results = await auth.signOutAll(); + expect(results.map((r) => r.key), [_a]); + expect(store.index, [added]); + }); + }); + + test('uses an injected revocation client', () async { + final other = []; + final otherDio = Dio() + ..httpClientAdapter = StubAdapter((options) { + other.add(options); + return ResponseBody.fromString('', 204); + }); + addTearDown(() => otherDio.close(force: true)); + final manager = MisskeyAuthManager( + miauth: MisskeyMiAuthClient(), + oauth: MisskeyOAuthClient(), + store: store, + dio: dio, + revocation: MisskeyTokenRevocationClient(dio: otherDio), + ); + store.seed(_a, 'tokenA'); + await manager.signOut(_a); + expect(requests, isEmpty); + expect(other, hasLength(1)); + }); +} diff --git a/test/support/fakes.dart b/test/support/fakes.dart index 07a0db4..bbf476e 100644 --- a/test/support/fakes.dart +++ b/test/support/fakes.dart @@ -1,13 +1,15 @@ +import 'dart:async'; import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:misskey_auth/misskey_auth.dart'; /// 応答を関数で差し替える Dio アダプタ class StubAdapter implements HttpClientAdapter { StubAdapter(this.respond); - final ResponseBody Function(RequestOptions) respond; + final FutureOr Function(RequestOptions) respond; @override Future fetch( @@ -49,3 +51,79 @@ void resetWebAuth() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(_webAuthChannel, null); } + +/// メモリ上の [TokenStore](失敗・割り込みの注入用) +class MemoryTokenStore implements TokenStore { + final Map tokens = {}; + final List index = []; + AccountKey? active; + + /// 呼ばれた操作の記録(例: `read:user1`) + final List calls = []; + + /// 読み出しで例外を投げるアカウント + final Set throwOnRead = {}; + + /// 削除で例外を投げるアカウント + final Set throwOnDelete = {}; + + bool throwOnList = false; + + /// [list] の直前に呼ぶ(読み出しの遅延の再現用) + Future Function()? beforeList; + + /// トークンを保存した状態にする + void seed(AccountKey key, String accessToken) { + tokens[key] = StoredToken(accessToken: accessToken, tokenType: 'MiAuth'); + if (!index.contains(key)) index.add(key); + } + + @override + Future upsert(AccountKey key, StoredToken token) async { + calls.add('upsert:${key.accountId}'); + tokens[key] = token; + if (!index.contains(key)) index.add(key); + } + + @override + Future read(AccountKey key) async { + calls.add('read:${key.accountId}'); + if (throwOnRead.contains(key)) { + throw const FormatException('corrupted'); + } + return tokens[key]; + } + + @override + Future> list() async { + await beforeList?.call(); + calls.add('list'); + if (throwOnList) throw PlatformException(code: 'StorageError'); + return [for (final key in index) AccountEntry(key)]; + } + + @override + Future delete(AccountKey key) async { + calls.add('delete:${key.accountId}'); + if (throwOnDelete.contains(key)) { + throw PlatformException(code: 'StorageError'); + } + tokens.remove(key); + index.remove(key); + if (active == key) active = null; + } + + @override + Future clearAll() async { + calls.add('clearAll'); + tokens.clear(); + index.clear(); + active = null; + } + + @override + Future setActive(AccountKey? key) async => active = key; + + @override + Future getActive() async => active; +} diff --git a/test/token_revocation_client_test.dart b/test/token_revocation_client_test.dart new file mode 100644 index 0000000..49b9ad0 --- /dev/null +++ b/test/token_revocation_client_test.dart @@ -0,0 +1,321 @@ +import 'dart:async'; + +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:misskey_auth/misskey_auth.dart'; + +import 'support/fakes.dart'; + +const _token = 'synthetic-secret-token'; + +/// Misskey API 形式のエラー応答 +ResponseBody apiError(int status, String code) => jsonBody({ + 'error': {'message': 'm', 'code': code, 'id': 'x'}, +}, status); + +ResponseBody textBody(String body, int status, String contentType) { + return ResponseBody.fromString( + body, + status, + headers: { + Headers.contentTypeHeader: [contentType], + }, + ); +} + +void main() { + late List requests; + + /// [respond] を返す Dio で組み立てたクライアント + MisskeyTokenRevocationClient clientWith( + FutureOr Function(RequestOptions) respond, { + bool acceptAllStatuses = false, + }) { + final dio = Dio( + acceptAllStatuses ? BaseOptions(validateStatus: (_) => true) : null, + ); + dio.httpClientAdapter = StubAdapter((options) { + requests.add(options); + return respond(options); + }); + addTearDown(() => dio.close(force: true)); + return MisskeyTokenRevocationClient(dio: dio); + } + + Future revokeWith( + FutureOr Function(RequestOptions) respond, { + bool acceptAllStatuses = false, + Duration? timeout, + }) { + return clientWith( + respond, + acceptAllStatuses: acceptAllStatuses, + ).revoke(host: 'example.test', accessToken: _token, timeout: timeout); + } + + setUp(() => requests = []); + + test('posts the token to revoke-token once', () async { + final result = await revokeWith((_) => ResponseBody.fromString('', 204)); + expect(result.status, TokenRevocationStatus.revoked); + expect(result.isInvalidated, isTrue); + expect(result.error, isNull); + final request = requests.single; + expect(request.method, 'POST'); + expect(request.uri.toString(), 'https://example.test/api/i/revoke-token'); + expect(request.data, {'i': _token, 'token': _token}); + }); + + group('classification', () { + final cases = + { + '204': ( + () => ResponseBody.fromString('', 204), + TokenRevocationStatus.revoked, + null, + ), + '200 HTML': ( + () => textBody('', 200, 'text/html'), + TokenRevocationStatus.failed, + null, + ), + '401 AUTHENTICATION_FAILED': ( + () => apiError(401, 'AUTHENTICATION_FAILED'), + TokenRevocationStatus.alreadyInvalid, + 'AUTHENTICATION_FAILED', + ), + '401 CREDENTIAL_REQUIRED': ( + () => apiError(401, 'CREDENTIAL_REQUIRED'), + TokenRevocationStatus.failed, + 'CREDENTIAL_REQUIRED', + ), + '401 without body': ( + () => ResponseBody.fromString('', 401), + TokenRevocationStatus.failed, + null, + ), + '400 ACCESS_DENIED': ( + () => apiError(400, 'ACCESS_DENIED'), + TokenRevocationStatus.unsupported, + 'ACCESS_DENIED', + ), + '400 INVALID_PARAM': ( + () => apiError(400, 'INVALID_PARAM'), + TokenRevocationStatus.failed, + 'INVALID_PARAM', + ), + '403 PERMISSION_DENIED': ( + () => apiError(403, 'PERMISSION_DENIED'), + TokenRevocationStatus.failed, + 'PERMISSION_DENIED', + ), + '404': ( + () => textBody('Not Found', 404, 'text/plain'), + TokenRevocationStatus.unsupported, + null, + ), + '429': ( + () => apiError(429, 'RATE_LIMIT_EXCEEDED'), + TokenRevocationStatus.failed, + 'RATE_LIMIT_EXCEEDED', + ), + '500': ( + () => apiError(500, 'INTERNAL_ERROR'), + TokenRevocationStatus.failed, + 'INTERNAL_ERROR', + ), + '502 text body': ( + () => textBody('Bad Gateway', 502, 'text/plain'), + TokenRevocationStatus.failed, + null, + ), + }; + + for (final acceptAll in [false, true]) { + group( + acceptAll ? 'with validateStatus accepting all' : 'default Dio', + () { + cases.forEach((name, c) { + final (body, status, errorCode) = c; + test(name, () async { + final result = await revokeWith( + (_) => body(), + acceptAllStatuses: acceptAll, + ); + expect(result.status, status); + expect(result.errorCode, errorCode); + expect(result.statusCode, isNotNull); + expect(requests, hasLength(1)); + if (status == TokenRevocationStatus.unsupported || + status == TokenRevocationStatus.failed) { + expect(result.error, isA()); + } else { + expect(result.error, isNull); + } + }); + }); + }, + ); + } + }); + + test('classifies by the error code even for a short token', () async { + // トークンを伏せる処理がエラーコードの判定に影響しない + Future revokeShort(ResponseBody body) => + clientWith((_) => body).revoke(host: 'example.test', accessToken: 'A'); + final invalid = await revokeShort(apiError(401, 'AUTHENTICATION_FAILED')); + expect(invalid.status, TokenRevocationStatus.alreadyInvalid); + final unsupported = await revokeShort(apiError(400, 'ACCESS_DENIED')); + expect(unsupported.status, TokenRevocationStatus.unsupported); + }); + + test('does not retry after a server error', () async { + final result = await revokeWith( + (_) => apiError(503, 'SERVICE_UNAVAILABLE'), + ); + expect(result.status, TokenRevocationStatus.failed); + expect(requests, hasLength(1)); + }); + + test('reports a connection error as a network failure', () async { + final result = await revokeWith( + (options) => throw DioException.connectionError( + requestOptions: options, + reason: 'refused', + ), + ); + expect(result.status, TokenRevocationStatus.failed); + expect(result.statusCode, isNull); + expect(result.error, isA()); + expect(result.error!.originalException, isNull); + }); + + test('classifies a malformed JSON body by status', () async { + final failed = await revokeWith( + (_) => textBody('{not json', 500, 'application/json'), + ); + expect(failed.status, TokenRevocationStatus.failed); + expect(failed.statusCode, 500); + expect(failed.error, isA()); + final unsupported = await revokeWith( + (_) => textBody('{not json', 404, 'application/json'), + ); + expect(unsupported.status, TokenRevocationStatus.unsupported); + expect(unsupported.statusCode, 404); + }); + + test('reports an exception from an interceptor as a failure', () async { + final dio = Dio() + ..interceptors.add( + InterceptorsWrapper(onRequest: (_, _) => throw StateError('boom')), + ) + ..httpClientAdapter = StubAdapter( + (_) => ResponseBody.fromString('', 204), + ); + addTearDown(() => dio.close(force: true)); + final result = await MisskeyTokenRevocationClient(dio: dio) + .revoke(host: 'example.test', accessToken: _token); + expect(result.status, TokenRevocationStatus.failed); + expect(result.error, isA()); + }); + + test('never exposes the token in the result', () async { + final results = [ + await revokeWith((_) => apiError(500, 'INTERNAL_ERROR')), + await revokeWith( + (options) => throw DioException.connectionError( + requestOptions: options, + reason: 'refused', + ), + ), + await revokeWith((_) => textBody('{', 500, 'application/json')), + // サーバーやインターセプターがトークンを文言に含めた場合 + await revokeWith( + (_) => jsonBody({ + 'error': {'message': 'Invalid token: $_token', 'code': _token}, + }, 400), + ), + await revokeWith( + (options) => throw DioException.connectionError( + requestOptions: options, + reason: 'refused for $_token', + ), + ), + ]; + for (final result in results) { + expect(result.toString(), isNot(contains(_token))); + expect(result.errorCode ?? '', isNot(contains(_token))); + expect(result.error.toString(), isNot(contains(_token))); + expect(result.error!.details ?? '', isNot(contains(_token))); + expect(result.error!.originalException, isNull); + } + }); + + group('timeout', () { + test('gives up on a request that never completes', () async { + final never = Completer(); + final stopwatch = Stopwatch()..start(); + final result = await revokeWith( + (_) => never.future, + timeout: const Duration(milliseconds: 50), + ); + expect(stopwatch.elapsed, lessThan(const Duration(seconds: 5))); + expect(result.status, TokenRevocationStatus.failed); + expect(result.error, isA()); + }); + + test('returns even if an interceptor never handles the cancel', () async { + final dio = Dio() + ..interceptors.add( + // エラーを受け取っても handler を呼ばない + InterceptorsWrapper(onError: (_, _) {}), + ) + ..httpClientAdapter = StubAdapter( + (_) => Completer().future, + ); + addTearDown(() => dio.close(force: true)); + final result = await MisskeyTokenRevocationClient(dio: dio) + .revoke( + host: 'example.test', + accessToken: _token, + timeout: const Duration(milliseconds: 50), + ) + .timeout(const Duration(seconds: 5)); + expect(result.status, TokenRevocationStatus.failed); + expect(result.error, isA()); + }); + + test('does not send a request when no time is left', () async { + final result = await revokeWith( + (_) => ResponseBody.fromString('', 204), + timeout: Duration.zero, + ); + expect(result.status, TokenRevocationStatus.failed); + expect(requests, isEmpty); + }); + + test('a completed request is not affected by the timeout', () async { + final result = await revokeWith( + (_) => ResponseBody.fromString('', 204), + timeout: const Duration(seconds: 5), + ); + expect(result.status, TokenRevocationStatus.revoked); + }); + }); + + test('applies timeout arguments without changing the injected Dio', () async { + final dio = Dio(BaseOptions(receiveTimeout: const Duration(seconds: 3))); + RequestOptions? sent; + dio.httpClientAdapter = StubAdapter((options) { + sent = options; + return ResponseBody.fromString('', 204); + }); + addTearDown(() => dio.close(force: true)); + await MisskeyTokenRevocationClient( + dio: dio, + receiveTimeout: const Duration(seconds: 7), + ).revoke(host: 'example.test', accessToken: _token); + expect(sent!.receiveTimeout, const Duration(seconds: 7)); + expect(dio.options.receiveTimeout, const Duration(seconds: 3)); + }); +}