Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
13 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<SignOutResult>` and `signOutAll` returns `Future<List<SignOutResult>>`, 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

Expand Down
1 change: 1 addition & 0 deletions README.de.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions README.fr.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- カスタム URL スキームによるアプリへのコールバック
- `flutter_secure_storage` を使用した安全なトークン保存
- 複数アカウントのトークン保存と、アクティブなアカウントの切り替え
- サインアウト時のサーバー側でのトークン失効(Misskey 2026.9.0 以降)
- 認証の実行とトークンの保存を仲介する高レベル API `MisskeyAuthManager`
- iOS、Android、macOS

Expand Down
1 change: 1 addition & 0 deletions README.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- 사용자 지정 URL 스킴을 통한 앱 콜백
- `flutter_secure_storage`를 사용한 안전한 토큰 저장
- 여러 계정의 토큰 저장 및 활성 계정 전환
- 로그아웃 시 서버에서 토큰 폐기(Misskey 2026.9.0 이상)
- 인증 흐름 실행과 토큰 저장을 중개하는 고수준 API `MisskeyAuthManager`
- iOS, Android 및 macOS

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions README.zh-Hans.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- 通过自定义 URL scheme 回调到应用
- 使用 `flutter_secure_storage` 安全保存令牌
- 保存多个账户的令牌并切换当前账户
- 退出登录时在服务器上撤销令牌(Misskey 2026.9.0 及更高版本)
- `MisskeyAuthManager`:高层 API,负责执行身份验证流程并保存令牌
- iOS、Android 和 macOS

Expand Down
11 changes: 11 additions & 0 deletions docs/docs/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

Expand Down
98 changes: 93 additions & 5 deletions docs/docs/token-storage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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

Expand Down
28 changes: 28 additions & 0 deletions docs/docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<SignOutResult>`, and `signOutAll` returns `Future<List<SignOutResult>>`. Code that only awaits them does not need changes. Classes that implement or mock `MisskeyAuthManager` must update the signatures:

```dart
Future<SignOutResult> signOut(
AccountKey key, {
SignOutMode mode = SignOutMode.revokeAndDelete,
Duration? timeout,
});
Future<List<SignOutResult>> signOutAll({
SignOutMode mode = SignOutMode.revokeAndDelete,
Duration? timeout,
});
```

## Upgrading to 0.2.0-beta.1

### Android Users Must Sign In Again
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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

Expand Down
Loading
Loading