> ## Documentation Index
> Fetch the complete documentation index at: https://developers.authlete.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> ### Authlete versions
> Authlete 3.0 is the current version. Unless the user says they use another version, answer for Authlete 3.0 using the 3.x documentation.
> Documentation for Authlete 2.x (pages under `/v2/` and `/ja/v2/`) is for the legacy version. Refer to it only when the user is on Authlete 2.x.
>
> ### Authlete architecture
> Authlete is a backend engine for OAuth 2.0 and OpenID Connect processing. End users and client applications do not call it directly; the service provider's authorization server and API server call Authlete's APIs. Authlete handles protocol processing and token, client, and service management, while the service provider owns the OAuth/OIDC endpoints and user authentication.
> See [Architecture](https://developers.authlete.com/get-started/introduction-to-authlete/architecture.md).
>
> ### Concepts
> If the user is new to Authlete, read these pages first:
> - [Request and Response](https://developers.authlete.com/get-started/concepts/request-and-response.md): Core API requests pass the client's request parameters as-is, and responses return `resultCode`, `action`, and `responseContent`.
> - [Action Handling](https://developers.authlete.com/get-started/concepts/action-handling.md): Branch on `action`, never on `resultCode`, and map each action to the HTTP response your server returns.
> - [Two-Step API Calls](https://developers.authlete.com/get-started/concepts/two-step-api-calls.md): Actions such as `INTERACTION` are completed with a second call (`/auth/authorization/issue` or `/auth/authorization/fail`) linked by a `ticket`.
> - [Management API Overview](https://developers.authlete.com/get-started/concepts/overview.md): The Management API configures services, manages clients, and operates issued tokens, separately from the protocol flows handled by the Core API.
> - [API Authentication](https://developers.authlete.com/get-started/concepts/authentication.md): Authlete APIs use bearer tokens: a Service Access Token (one service) or an Organization Token (the whole organization).

# Authlete で Poppy を実装する

> Authlete を認可サーバーとして使い、自社の Company を Personal Agent Protocol（Poppy）の Personal Agent と連携できるようにします。

Poppy の Company は、ディスカバリーファイルを公開し、自社のページで User をサインインさせ、すべてのリクエストで二つのものを確認します。`Poppy-Session` ヘッダと、User がサインインした後はアクセストークンです。

OAuth に関わる部分は Authlete が処理します。Authlete は Personal Agent を URL で識別し（CIMD）、署名付きのクライアントアサーションを検証し（`private_key_jwt`）、トークンをエージェントの鍵に紐付け（DPoP）、トークンを発行して検証します。サーバーは、ほかのクライアントと同じ Authlete API を呼び出すだけです。

このガイドでは、Poppy 用に Authlete サービスを設定し、Company が構築する各要素を 1 ステップにつき 1 つの Authlete API 呼び出しでたどります。例には、Authlete のリファレンス用 Company である Stays を使います。Poppy の概要と Company のテスト方法は、[Poppy の概要](https://developers.authlete.com/ja/protocols-and-flows/protocol-extensions/personal-agent-protocol-poppy.md)をご覧ください。

## Poppy を使う場面

* **顧客が自分のエージェントを使う場合。** Meta の Muse などのパーソナルエージェントは、訪問するサイトで Poppy を探します。Poppy に対応すると、これらのエージェントが顧客をサインインさせ、自社が定めた範囲で顧客の代わりに操作できます。
* **すべてのエージェントに共通の入口を用意したい場合。** エージェントごとに個別の連携を作る代わりに、`poppy.json` を一つ公開すれば、Poppy に対応したどのエージェントとも連携できます。
* **すでに Authlete を使っている場合。** Poppy のサインインは OAuth です。いくつかの設定を変更するだけで、既存の Authlete サービスで処理できます。

## フローの概要

1. エージェントが `poppy.json` と OAuth のメタデータを読み、認可サーバーを見つけます。
2. エージェントが、自身の URL を `client_id` とする認可リクエストを送ります。Authlete がエージェントのメタデータを取得して登録します。
3. User が自社のページでサインインしてスコープを承認し、認可サーバーが認可コードを発行します。
4. エージェントが認可コードをアクセストークンに交換します。このとき、署名付きのアサーションと、必要に応じて DPoP プルーフで自身を証明します。
5. API が、すべてのリクエストで `Poppy-Session` ヘッダとアクセストークンを確認します。

ディスカバリーpoppy.json とメタデータ

エージェントの識別クライアント ID は URL

サインインUser がスコープを承認

アクセストークンエージェントの鍵に紐付け

API 呼び出しSession ヘッダとトークン

## 始める前に

* Authlete 3.0.40 以降のサービスと、その **サービスアクセストークン**。作成するには [API を使ってみる](https://developers.authlete.com/ja/get-started/quickstarts/getting-started.md)に従ってください。設定を変更するため、テスト用のサービスを使ってください。
* HTTPS で公開された二つのホスト。Company のドメイン（例: `stays.poppysandbox.dev`）と、認可サーバー（例: `auth.stays.poppysandbox.dev`）です。
* cURL コマンドを実行する場合: `curl`、`jq`、`openssl`

以下のコマンドでは、`SERVICE_ID` と `SERVICE_ACCESS_TOKEN` を実際の値に、`us.authlete.com` をサービスのクラスターに置き換えてください。

### SDK を準備する

TypeScript、Go、Ruby のタブに沿って進める場合は、SDK をインストールしてクライアントを作成します。各ステップでこのクライアントを使います。

> [tab] TypeScript
>
> ```bash wrap theme={null}
> npm add @authlete/typescript-sdk
> ```
>
> ```typescript wrap theme={null}
> import { Authlete } from "@authlete/typescript-sdk";
>
> const authlete = new Authlete({
>   serverURL: "https://us.authlete.com",
>   bearer: "SERVICE_ACCESS_TOKEN",
> });
> const serviceId = "SERVICE_ID";
> // Each call returns { headers, result }; the steps use `result`.
> ```

> [tab] Go
>
> ```bash wrap theme={null}
> go get github.com/authlete/authlete-go-sdk
> ```
>
> ```go wrap theme={null}
> import (
> 	"context"
> 	"log"
>
> 	authlete "github.com/authlete/authlete-go-sdk"
> 	"github.com/authlete/authlete-go-sdk/models/components"
> 	"github.com/authlete/authlete-go-sdk/models/operations"
> )
>
> ctx := context.Background()
> s := authlete.New(
> 	authlete.WithServerURL("https://us.authlete.com"),
> 	authlete.WithServiceID("SERVICE_ID"),
> 	authlete.WithSecurity("SERVICE_ACCESS_TOKEN"),
> )
> ```

> [tab] Ruby
>
> ```bash wrap theme={null}
> gem install authlete_ruby_sdk
> ```
>
> ```ruby wrap theme={null}
> require "authlete_ruby_sdk"
>
> Models = ::Authlete::Models
> authlete = ::Authlete::Client.new(
>   bearer:     "SERVICE_ACCESS_TOKEN",
>   server_url: "https://us.authlete.com"
> )
> SERVICE_ID = "SERVICE_ID"
> ```

### エージェント ID を用意する

Personal Agent のクライアント ID は、そのメタデータドキュメントの URL です。このガイドでは、公開テスト用エージェントの [Poppy Agent Playground](https://poppy-playground.authlete.app) を使います。URL を開くと、Authlete が取得するドキュメントを確認できます。

```sh wrap theme={null}
curl -s https://poppy-playground.authlete.app/agent.json
```

```json wrap theme={null}
{
  "client_id": "https://poppy-playground.authlete.app/agent.json",
  "client_name": "Poppy Agent Playground",
  "jwks_uri": "https://poppy-playground.authlete.app/jwks.json",
  "redirect_uris": ["https://poppy-playground.authlete.app/callback"],
  "token_endpoint_auth_method": "private_key_jwt",
  "grant_types": [
    "authorization_code",
    "refresh_token",
    "urn:ietf:params:oauth:grant-type:device_code"
  ],
  "response_types": ["code"]
}
```

多くの CIMD クライアントと異なり、Personal Agent はパブリッククライアントではありません。`jwks_uri` で鍵を公開し、その鍵でクライアントアサーションに署名します（`private_key_jwt`）。このエージェントは署名アルゴリズム（`token_endpoint_auth_signing_alg`）を記載していませんが、Poppy では必須ではありません。Authlete は、エージェントが公開している鍵のいずれかで検証できれば、そのアサーションを受け入れます。また、このエージェントはデバイスグラントも記載しています。これは下記のメタデータポリシーで扱います。

### サービスを設定する

コンソールの **Service Settings**、または [Update Service API](https://developers.authlete.com/api-reference/service-management/update-service.md) で次の項目を設定します。この API はサービス全体を置き換えるため、まずサービスを取得し、これらの項目を変更して送り返してください。

| 設定 | 値 | 理由 |
| :- | :- | :- |
| `clientIdMetadataDocumentSupported` | `true` | URL を `client_id` として受け付けます。 |
| `cimdAllowlistEnabled`、`cimdAllowlist` | `true`、`https://poppy-playground.authlete.app/agent.json` | 構築中はテスト用エージェントだけを受け付けます。[本番運用の前に](#本番運用の前に)をご覧ください。 |
| `supportedTokenAuthMethods` | `PRIVATE_KEY_JWT` を含める | Personal Agent は署名付きアサーションで認証します。含めないと `[A505306]` になります。 |
| `clientAssertionAudRestrictedToIssuer` | `true` | `aud` が自社の発行者ではないクライアントアサーションを拒否します。Poppy が要求する動作です。デフォルトでは無効で、無効のままだとトークンエンドポイント宛てのアサーションも受け付けます。拒否されたアサーションは `[A157356]` になります。 |
| `supportedGrantTypes` | `AUTHORIZATION_CODE`、`REFRESH_TOKEN` | Direct Sign-In と、Poppy が必須とするリフレッシュトークンのためです。 |
| `cimdMetadataPolicyEnabled`、`cimdMetadataPolicy` | `true`、提供しないグラントタイプを取り除くポリシー | サービスは、エージェントのメタデータに記載されたすべてのグラントタイプをサポートしている必要があり、そうでないとリクエストは `[A505307]` で失敗します。Playground はデバイスグラントを記載しているため、[メタデータポリシー](https://developers.authlete.com/ja/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md)で取り除きます。 |
| `pkceRequired`、`pkceS256Required` | `true` | Direct Sign-In では `S256` の PKCE を使います。 |
| `supportedScopes` | 自社のスコープ（例: `stays:read`、`stays:write`） | `poppy.json` に記載するスコープです。 |
| `protectedResources` | Company の URL（例: `https://stays.poppysandbox.dev`） | Poppy では、認可サーバーのメタデータの `protected_resources` に Company を含める必要があります。コンソールでは **Metadata** の **Protected Resources** で設定します。 |
| `accessTokenDuration` | `3600` | デフォルトの `0` では、発行時点で期限切れのトークンが発行されます。 |
| `issuer`、`authorizationEndpoint`、`tokenEndpoint` | 認可サーバーの URL | エージェントはメタデータからエンドポイントを見つけます。Poppy では必須なので、失効エンドポイントも設定してください。 |

エージェントが記載しているという理由だけで `DEVICE_CODE` を追加しないでください。メタデータに記載すると、Device Sign-In を提供していることをエージェントに伝えることになり、デバイス認可エンドポイントと検証ページ（`deviceVerificationUri`）も必要になります。`DEVICE_CODE` は Device Sign-In を構築するときにだけ追加してください。そうしないと、すべての試行が `[A222101]` で失敗します。

Pushed Authorization Request（PAR）に対応するには、Authlete の `/pushed_auth_req` API にリクエストを転送する `POST /oauth/par` エンドポイントを追加し、その URL をサービスに設定します。メタデータにこのエンドポイントが記載されている場合、Poppy のエージェントは PAR を使うべきです。このガイドの残りの部分は、PAR の有無にかかわらず同じです。

## 構築するもの

Company には二つのホストがあります。認可サーバーの各エンドポイントは、Authlete API を 1 つ呼び出すだけの薄いラッパーです。

| ホスト | エンドポイント | Authlete API | ステップ |
| :- | :- | :- | :- |
| Company のドメイン | `GET /.well-known/poppy.json` | なし | 1 |
| Company のドメイン | `GET /.well-known/oauth-protected-resource` | なし | 2 |
| 認可サーバー | `GET /.well-known/oauth-authorization-server` | `GET /api/{serviceId}/service/configuration` | 3 |
| 認可サーバー | `GET /oauth/authorize` | `POST /api/{serviceId}/auth/authorization` | 4 |
| 認可サーバー | サインインと同意のページ | `POST /api/{serviceId}/auth/authorization/issue` または `/fail` | 5 |
| 認可サーバー | `POST /oauth/token` | `POST /api/{serviceId}/auth/token` | 6 |
| Company のドメイン | 自社の API | `POST /api/{serviceId}/auth/introspection` | 7 |
| 認可サーバー | `POST /oauth/revoke` | `POST /api/{serviceId}/auth/revocation` | 8 |

## 使用するエンドポイント

| ステップ | Authlete API | 役割 | リファレンス |
| :- | :- | :- | :- |
| 3 | `GET /api/{serviceId}/service/configuration` | 認可サーバーのメタデータを返します | [Get Service Configuration](https://developers.authlete.com/api-reference/service-management/get-service-configuration.md) |
| 4 | `POST /api/{serviceId}/auth/authorization` | 認可リクエストを処理し、エージェントのメタデータを取得します | [Process Authorization Request](https://developers.authlete.com/api-reference/authorization-endpoint/process-authorization-request.md) |
| 5 | `POST /api/{serviceId}/auth/authorization/issue` | 承認後に認可コードを発行します | [Issue Authorization Response](https://developers.authlete.com/api-reference/authorization-endpoint/issue-authorization-response.md) |
| 6 | `POST /api/{serviceId}/auth/token` | エージェントのアサーションと DPoP プルーフを検証し、トークンを発行します | [Process Token Request](https://developers.authlete.com/api-reference/token-endpoint/process-token-request.md) |
| 7 | `POST /api/{serviceId}/auth/introspection` | アクセストークンとその DPoP プルーフを検証します | [Process Introspection Request](https://developers.authlete.com/api-reference/introspection-endpoint/process-introspection-request.md) |
| 8 | `POST /api/{serviceId}/auth/revocation` | User のサインアウト時にトークンを失効させます | [Process Revocation Request](https://developers.authlete.com/api-reference/revocation-endpoint/process-revocation-request.md) |

## 構築する

### 1. poppy.json を公開する

すべてのエージェントは `https://{自社のドメイン}/.well-known/poppy.json` から始めます。このファイルは、Company 自身のドメインで、HTTPS により、サインインなしで提供します。Company と認可サーバーの名前、User に表示する言葉で書いた各スコープの説明、API の一覧を記載します。

次は Stays のファイルの抜粋です。

```json poppy.json wrap theme={null}
{
  "protocol_version": "1.0",
  "organization": { "name": "Stays", "domain": "stays.poppysandbox.dev" },
  "auth": {
    "issuer": "https://auth.stays.poppysandbox.dev",
    "scopes": {
      "stays:read": "See your Stays bookings.",
      "stays:write": "Book a room on your account. Each booking needs your approval."
    },
    "scope_hints": {
      "stays:read": { "changes": "none", "personal_data": true },
      "stays:write": { "changes": "irreversible", "personal_data": true }
    }
  },
  "apis": [
    { "type": "openapi", "url": "https://stays.poppysandbox.dev/openapi.json", "description": "Stays API" }
  ]
}
```

* `organization.domain` は、ファイルを提供するホストと一致する必要があります。
* `auth.issuer` は、Authlete サービスの `issuer` と一致する必要があります。
* ヒントは任意です。記載するヒントには、`changes`（`none`、`reversible`、`irreversible` のいずれか）と `personal_data` の両方が必要です。
* 古いバージョンも提供する場合は、`supported_versions` にはそれらだけを記載し、自身の `protocol_version` は含めません。

```sh wrap theme={null}
curl -s https://stays.poppysandbox.dev/.well-known/poppy.json | jq '.organization, .auth.issuer'
```

> [!TIP]
>
> ファイルが HTTPS で読み込まれ、`organization.domain` がホストと一致しています。

### 2. 保護リソースメタデータを公開する

エージェントは、`poppy.json` の発行者を保護リソースメタデータ（[RFC 9728](https://www.rfc-editor.org/rfc/rfc9728.html)）と照合します。このファイルは、Company のドメインで `poppy.json` と並べて提供します。Poppy では保護リソースはドメイン全体なので、パスを付けずにルートに配置します。

```json /.well-known/oauth-protected-resource wrap theme={null}
{
  "resource": "https://stays.poppysandbox.dev",
  "authorization_servers": ["https://auth.stays.poppysandbox.dev"]
}
```

`resource` は、`https://` に自社のドメインを続けたものと完全に一致する必要があります。

```sh wrap theme={null}
curl -s https://stays.poppysandbox.dev/.well-known/oauth-protected-resource
```

> [!TIP]
>
> `authorization_servers` に、Authlete サービスの `issuer` が含まれています。

### 3. 認可サーバーのメタデータを提供する

次に、エージェントは認可サーバーの `/.well-known/oauth-authorization-server` を読みます。このドキュメントは認可サーバーが作成するのではなく、Authlete がサービス設定から生成したものを返します。

Poppy では、`protected_resources` に Company を含めることも求められます。これで双方向の確認が完了します。[サービスを設定する](#サービスを設定する)で `protectedResources` を設定すると、Authlete がこれを含めます。

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/service/configuration \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN"
```

```typescript TypeScript wrap theme={null}
const { result: config } = await authlete.service.getConfiguration({ serviceId });
// Return `config` as the JSON body of /.well-known/oauth-authorization-server.
```

```go Go wrap theme={null}
config, err := s.Service.GetConfiguration(ctx, operations.ServiceConfigurationAPIRequest{})
if err != nil {
	log.Fatal(err)
}
// Return config.Object as the JSON body of /.well-known/oauth-authorization-server.
```

```ruby Ruby wrap theme={null}
config = authlete.services.configuration(service_id: SERVICE_ID).object
# Return `config` as the JSON body of /.well-known/oauth-authorization-server.
```

```json wrap theme={null}
{
  "issuer": "https://auth.stays.poppysandbox.dev",
  "authorization_endpoint": "https://auth.stays.poppysandbox.dev/oauth/authorize",
  "token_endpoint": "https://auth.stays.poppysandbox.dev/oauth/token",
  "revocation_endpoint": "https://auth.stays.poppysandbox.dev/oauth/revoke",
  "grant_types_supported": ["authorization_code", "refresh_token"],
  "token_endpoint_auth_methods_supported": ["private_key_jwt"],
  "client_id_metadata_document_supported": true,
  "protected_resources": ["https://stays.poppysandbox.dev"]
}
```

> [!TIP]
>
> `issuer` が `poppy.json` と一致し、`client_id_metadata_document_supported` が `true`、`grant_types_supported` に `refresh_token` が含まれ、`protected_resources` に自社のドメインが含まれています。

API リファレンス: [Get Service Configuration](https://developers.authlete.com/api-reference/service-management/get-service-configuration.md)

### 4. 認可リクエストを処理する

アカウントが必要な処理になると、エージェントは User のブラウザを認可エンドポイントに送ります。Poppy ではこれを Direct Sign-In と呼びます。リクエストには、`client_id` としてのエージェントの URL、要求するスコープ、PKCE のチャレンジ、そして `prompt=consent` が含まれます。Poppy は User が毎回エージェントを承認するよう `prompt=consent` を必須としています。エージェントが先にリクエストをプッシュした場合（PAR）、クエリ文字列には `client_id` と `request_uri` だけが含まれます。いずれの場合も、認可サーバーはクエリ文字列をそのまま Authlete に渡します。

Authlete は未知の URL を受け取ると、エージェントのドキュメントを取得して確認し、エージェントを登録したうえで、リクエストの残りを確認します。

試すには、エージェントと同じように PKCE のペアを作成します。

```sh wrap theme={null}
VERIFIER=$(openssl rand -base64 48 | tr '+/' '-_' | tr -d '=')
CHALLENGE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 -A | tr '+/' '-_' | tr -d '=')
```

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/auth/authorization \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"parameters": "response_type=code&client_id=https%3A%2F%2Fpoppy-playground.authlete.app%2Fagent.json&redirect_uri=https%3A%2F%2Fpoppy-playground.authlete.app%2Fcallback&scope=stays%3Aread%20stays%3Awrite&prompt=consent&code_challenge='"$CHALLENGE"'&code_challenge_method=S256&state=xyz"}'
```

```typescript TypeScript wrap theme={null}
// `parameters` is the query string of GET /oauth/authorize, as received.
const { result: r } = await authlete.authorization.processRequest({
  serviceId,
  authorizationRequest: { parameters },
});
// INTERACTION: show the sign-in and consent page. BAD_REQUEST: return 400 with r.responseContent.
```

```go Go wrap theme={null}
// `parameters` is the query string of GET /oauth/authorize, as received.
res, err := s.Authorization.ProcessRequest(ctx, operations.AuthAuthorizationAPIRequest{
	Body: components.AuthorizationRequest{Parameters: parameters},
})
if err != nil {
	log.Fatal(err)
}
r := res.AuthorizationResponse
// INTERACTION: show the sign-in and consent page. BAD_REQUEST: return 400 with *r.ResponseContent.
```

```ruby Ruby wrap theme={null}
# `parameters` is the query string of GET /oauth/authorize, as received.
r = authlete.authorization.process_request(
  service_id: SERVICE_ID,
  authorization_request: Models::Components::AuthorizationRequest.new(parameters: parameters)
).authorization_response
# INTERACTION: show the sign-in and consent page. BAD_REQUEST: return 400 with r.response_content.
```

```json wrap theme={null}
{
  "action": "INTERACTION",
  "ticket": "ArHyOxV-8WF7kEShwwYXpNB3DUb8e14Bw3xFaSSZEBg",
  "metadataDocumentUsed": true,
  "client": {
    "clientName": "Poppy Agent Playground",
    "clientSource": "METADATA_DOCUMENT",
    "metadataDocumentLocation": "https://poppy-playground.authlete.app/agent.json"
  },
  "scopes": [{ "name": "stays:read" }, { "name": "stays:write" }]
}
```

> [!TIP]
>
> `action` が `INTERACTION` で、`client.clientSource` が `METADATA_DOCUMENT` です。エージェントがサービスの **Clients** ページに表示されます。

API リファレンス: [Process Authorization Request](https://developers.authlete.com/api-reference/authorization-endpoint/process-authorization-request.md)

### 5. 同意ページを表示して認可コードを発行する

`INTERACTION` は、リクエストが有効で、User に確認する段階であることを示します。認可サーバーは自社のドメインで User をサインインさせ、同意ページを表示します。User がエージェントを見分けられるように、エージェント名（`client.clientName`）と、メタデータの `logo_uri` にあるロゴを表示してください。付与するすべてのスコープを `poppy.json` の説明を使って一覧表示します。Poppy は同意ページにすべてのスコープを表示することを求めています。たとえば Stays は、`stays:write` ではなく「Book a room on your account. Each booking needs your approval.」と表示します。また、エージェントのドメインと「このエージェントに今依頼した場合のみ続行してください」のような注意を表示し、ページが開かれただけで承認しないでください。Poppy は RFC 10027（BCP 247）セクション 2 のクロスデバイスのベストプラクティスに従うことを求めています。

User が承認したら、ステップ 4 の `ticket` と User の ID を送ります。Authlete は認可コード付きのリダイレクト URL を返します。

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/auth/authorization/issue \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"ticket": "TICKET", "subject": "demo-user"}'
```

```typescript TypeScript wrap theme={null}
const { result: issued } = await authlete.authorization.issue({
  serviceId,
  authorizationIssueRequest: { ticket: r.ticket!, subject: user.id },
});
// LOCATION: redirect the browser (302) to issued.responseContent.
// If the User declines, call authlete.authorization.fail with reason "DENIED".
```

```go Go wrap theme={null}
res, err := s.Authorization.Issue(ctx, operations.AuthAuthorizationIssueAPIRequest{
	Body: components.AuthorizationIssueRequest{Ticket: *r.Ticket, Subject: userID},
})
if err != nil {
	log.Fatal(err)
}
issued := res.AuthorizationIssueResponse
// LOCATION: redirect the browser (302) to *issued.ResponseContent.
// If the User declines, call s.Authorization.Fail with reason Denied.
```

```ruby Ruby wrap theme={null}
issued = authlete.authorization.issue_response(
  service_id: SERVICE_ID,
  authorization_issue_request: Models::Components::AuthorizationIssueRequest.new(
    ticket: r.ticket, subject: user_id
  )
).authorization_issue_response
# LOCATION: redirect the browser (302) to issued.response_content.
# If the User declines, call authlete.authorization.fail_request with reason DENIED.
```

```json wrap theme={null}
{
  "action": "LOCATION",
  "responseContent": "https://poppy-playground.authlete.app/callback?state=xyz&code=p8UaUBD2o1xkTmqbpTNbl1Av8lUoFaDXQrbE7unaIvM&iss=https%3A%2F%2Fauth.stays.poppysandbox.dev"
}
```

> [!TIP]
>
> `action` が `LOCATION` で、`responseContent` に `code` と、発行者と一致する `iss` が含まれています。

API リファレンス: [Issue Authorization Response](https://developers.authlete.com/api-reference/authorization-endpoint/issue-authorization-response.md) · [Fail Authorization Request](https://developers.authlete.com/api-reference/authorization-endpoint/fail-authorization-request.md)

### 6. トークンリクエストを処理する

エージェントは認可コードをトークンエンドポイントに送ります。パブリッククライアントと異なり、エージェントはクライアントアサーションで自身を証明します。これは `jwks_uri` にある鍵のいずれかで署名した JWT です（`private_key_jwt`）。Poppy では、アサーションの `aud` は認可サーバーの発行者でなければならず、`exp` は `iat` から 5 分以内でなければなりません。さらに `DPoP` ヘッダを送ることもあります。これはエージェントが持つ鍵で署名したプルーフで、アクセストークンをその鍵に紐付けます。

認可サーバーはフォームボディをそのまま Authlete に渡します。リクエストに `DPoP` ヘッダがある場合は、HTTP メソッドとトークンエンドポイントの正確な公開 URL も一緒に渡します。Authlete は、認可コード、PKCE のベリファイア、公開鍵によるアサーション、DPoP プルーフを確認します。

> [!NOTE]
>
> アサーションと DPoP プルーフの鍵はエージェントだけが持っているため、このリクエストを cURL で自分で送ることはできません。最後まで実行するには、[テストする](#テストする)のとおり Poppy Agent Playground を使ってください。

```typescript TypeScript wrap theme={null}
// `parameters` is the form body of POST /oauth/token, as received.
const dpop = req.headers.get("DPoP") ?? undefined;
const { result: t } = await authlete.token.process({
  serviceId,
  tokenRequest: {
    parameters,
    ...(dpop && { dpop, htm: "POST", htu: "https://auth.stays.poppysandbox.dev/oauth/token" }),
  },
});
// If t.dpopNonce is set, return it in a DPoP-Nonce header.
// OK: return 200 with t.responseContent. BAD_REQUEST: 400. INVALID_CLIENT: 401.
```

```go Go wrap theme={null}
// `parameters` is the form body of POST /oauth/token, as received.
body := components.TokenRequest{Parameters: parameters}
if d := r.Header.Get("DPoP"); d != "" {
	body.Dpop = &d
	body.Htm = authlete.Pointer("POST")
	body.Htu = authlete.Pointer("https://auth.stays.poppysandbox.dev/oauth/token")
}
res, err := s.Token.Process(ctx, operations.AuthTokenAPIRequest{Body: body})
if err != nil {
	log.Fatal(err)
}
t := res.TokenResponse
// If t.DpopNonce is set, return it in a DPoP-Nonce header.
// OK: return 200 with *t.ResponseContent. BAD_REQUEST: 400. INVALID_CLIENT: 401.
```

```ruby Ruby wrap theme={null}
# `parameters` is the form body of POST /oauth/token, as received.
dpop = request.env["HTTP_DPOP"]
t = authlete.tokens.process_request(
  service_id: SERVICE_ID,
  token_request: Models::Components::TokenRequest.new(
    parameters: parameters,
    dpop: dpop,
    htm: (dpop ? "POST" : nil),
    htu: (dpop ? "https://auth.stays.poppysandbox.dev/oauth/token" : nil)
  )
).token_response
# If t.dpop_nonce is set, return it in a DPoP-Nonce header.
# OK: return 200 with t.response_content. BAD_REQUEST: 400. INVALID_CLIENT: 401.
```

エージェントが送るフォームボディは次のようになります。そのまま Authlete に渡してください。

```text wrap theme={null}
grant_type=authorization_code
&code=p8UaUBD2o1xkTmqbpTNbl1Av8lUoFaDXQrbE7unaIvM
&redirect_uri=https%3A%2F%2Fpoppy-playground.authlete.app%2Fcallback
&client_id=https%3A%2F%2Fpoppy-playground.authlete.app%2Fagent.json
&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9...
```

`responseContent` は、認可サーバーがエージェントに返す JSON です。

```json wrap theme={null}
{
  "action": "OK",
  "responseContent": "{\"access_token\":\"lhdjpcs1V...\",\"token_type\":\"DPoP\",\"expires_in\":3600,\"scope\":\"stays:read stays:write\",\"refresh_token\":\"bV1jMYeH7cA5...\"}"
}
```

> [!TIP]
>
> `action` が `OK` です。エージェントが DPoP プルーフを送った場合、`token_type` は `DPoP`、それ以外は `Bearer` です。

API リファレンス: [Process Token Request](https://developers.authlete.com/api-reference/token-endpoint/process-token-request.md)

### 7. API へのリクエストを確認する

エージェントが API に送るすべてのリクエストには、`Poppy-Session` ヘッダが付きます。サインイン後のリクエストには、アクセストークンと、DPoP に紐付いたトークンの場合は新しい DPoP プルーフも付きます。API はまず Session ヘッダを、次にトークンを確認します。

**Session ヘッダ。** このヘッダは Authlete ではなく API が確認します。これは短期間有効な鍵で署名された JWT で、その `poppy_dlg` ヘッダには、エージェントが公開している鍵のいずれかが保証する委任が入っています。[Poppy の仕様](https://personalagentprotocol.org/docs/1.0/spec)のセクション 5.3 に従って、次のように確認します。

1. `Poppy-Version` が `1.0` であることを確認します。ない場合や、サポートしていないバージョンの場合は、`{"error": "version_unsupported"}` とともに `400` を返します。
2. エージェントの `jwks_uri` にある鍵で委任を検証し、次に委任の `cnf.jwk` にある鍵で Session ヘッダを検証します。`poppy_dlg` の委任がない Session ヘッダは、`jwks_uri` の鍵で直接署名されたものも含めて拒否します。`ES256` と `PS384` で署名された委任を受け付けます。委任された鍵はリクエストごとに変わることがあるため、新しい鍵をエラーとして扱わないでください。エージェントのメタデータと鍵を取得するときは、ループバック、プライベート、リンクローカルのアドレスに接続しないでください。
3. `typ` が `poppy-session+jwt` であること、`aud` が自社の発行者であること、`htm` と `htu` がこのリクエストのメソッドと公開 URL に一致すること、`iat` が新しいことを確認します。
4. リクエストにアクセストークンがある場合は、`ath` がそのハッシュであることを確認します。
5. エージェントの `client_id`、`sid`、`sub` の User ID で Session を検索します。

手順 2 から 5 のいずれかの確認に失敗した場合は、`{"error": "invalid_session"}` とともに `400` を返します。

**アクセストークン。** トークン、この操作に必要なスコープ、DPoP に紐付いたトークンの場合は DPoP プルーフとメソッドと URL を渡します。Authlete は、トークンが有効で、スコープを持ち、プルーフに署名した鍵に紐付いていることを確認します。

```sh cURL wrap theme={null}
curl -s https://us.authlete.com/api/SERVICE_ID/auth/introspection \
  -H "Authorization: Bearer SERVICE_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"token": "ACCESS_TOKEN", "scopes": ["stays:write"]}'
```

```typescript TypeScript wrap theme={null}
// From the request: Authorization: DPoP <token>, and the DPoP header.
const { result: i } = await authlete.introspection.process({
  serviceId,
  introspectionRequest: {
    token,
    scopes: ["stays:write"],
    dpop: req.headers.get("DPoP") ?? undefined,
    htm: "POST",
    htu: "https://stays.poppysandbox.dev/stays",
  },
});
// OK: check that i.metadataDocumentLocation equals the Session header's iss (the same agent), then serve the request.
// UNAUTHORIZED: 401. FORBIDDEN: 403.
// On 401 and 403, return i.responseContent in a WWW-Authenticate header.
```

```go Go wrap theme={null}
// From the request: Authorization: DPoP <token>, and the DPoP header.
d := r.Header.Get("DPoP")
res, err := s.Introspection.Process(ctx, operations.AuthIntrospectionAPIRequest{
	Body: components.IntrospectionRequest{
		Token:  token,
		Scopes: []string{"stays:write"},
		Dpop:   &d,
		Htm:    authlete.Pointer("POST"),
		Htu:    authlete.Pointer("https://stays.poppysandbox.dev/stays"),
	},
})
if err != nil {
	log.Fatal(err)
}
i := res.IntrospectionResponse
// OK: check that *i.MetadataDocumentLocation equals the Session header's iss (the same agent), then serve the request.
// UNAUTHORIZED: 401. FORBIDDEN: 403.
// On 401 and 403, return *i.ResponseContent in a WWW-Authenticate header.
```

```ruby Ruby wrap theme={null}
# From the request: Authorization: DPoP <token>, and the DPoP header.
i = authlete.introspection.process_request(
  service_id: SERVICE_ID,
  introspection_request: Models::Components::IntrospectionRequest.new(
    token: token,
    scopes: ["stays:write"],
    dpop: request.env["HTTP_DPOP"],
    htm: "POST",
    htu: "https://stays.poppysandbox.dev/stays"
  )
).introspection_response
# OK: check that i.metadata_document_location equals the Session header's iss (the same agent), then serve the request.
# UNAUTHORIZED: 401. FORBIDDEN: 403.
# On 401 and 403, return i.response_content in a WWW-Authenticate header.
```

```json wrap theme={null}
{
  "action": "OK",
  "subject": "demo-user",
  "scopes": ["stays:read", "stays:write"],
  "metadataDocumentUsed": true,
  "metadataDocumentLocation": "https://poppy-playground.authlete.app/agent.json"
}
```

> [!TIP]
>
> `action` が `OK` で、`subject` がエージェントが代理で動作する User、`metadataDocumentLocation` がエージェントの URL です。

アカウントが必要な操作へのアクセストークンのないリクエストには、エラーコードなしで `401` を返し、`WWW-Authenticate` チャレンジで必要なスコープを示します。スコープが不足しているトークンには、`insufficient_scope` とともに `403` を返します。

API リファレンス: [Process Introspection Request](https://developers.authlete.com/api-reference/introspection-endpoint/process-introspection-request.md)

### 8. サインアウト時にトークンを失効させる

User がサインアウトすると、エージェントは自社の Company について保持しているすべてのリフレッシュトークンを失効エンドポイントで失効させます。エージェントはトークンエンドポイントと同じく、クライアントアサーションで認証します。フォームボディをそのまま Authlete に渡してください。

```typescript TypeScript wrap theme={null}
// `parameters` is the form body of POST /oauth/revoke, as received.
const { result: v } = await authlete.revocation.process({
  serviceId,
  revocationRequest: { parameters },
});
// OK: return 200. INVALID_CLIENT: 401. BAD_REQUEST: 400.
```

```go Go wrap theme={null}
// `parameters` is the form body of POST /oauth/revoke, as received.
res, err := s.Revocation.Process(ctx, operations.AuthRevocationAPIRequest{
	Body: components.RevocationRequest{Parameters: parameters},
})
if err != nil {
	log.Fatal(err)
}
v := res.RevocationResponse
// OK: return 200. INVALID_CLIENT: 401. BAD_REQUEST: 400.
```

```ruby Ruby wrap theme={null}
# `parameters` is the form body of POST /oauth/revoke, as received.
v = authlete.revocation.process_request(
  service_id: SERVICE_ID,
  revocation_request: Models::Components::RevocationRequest.new(parameters: parameters)
).revocation_response
# OK: return 200. INVALID_CLIENT: 401. BAD_REQUEST: 400.
```

> [!TIP]
>
> `action` が `OK` です。RFC 7009 のとおり、Authlete は未知のトークンに対しても `OK` を返します。

API リファレンス: [Process Revocation Request](https://developers.authlete.com/api-reference/revocation-endpoint/process-revocation-request.md)

## テストする

[Poppy Agent Playground](https://poppy-playground.authlete.app) を自社の Company のドメインに向けてください。Playground はこのページのすべてのステップをサーバーに対して実行し、自身の鍵でクライアントアサーションに署名し、各リクエストを **Wire** にデコードして表示します。

1. 上部の入力欄にドメインを入力し、**Discover** をクリックします。ステップ 1 から 3 を確認できます。
2. **Call an API** でアカウントが必要な操作を選び、**Send** をクリックします。API は `401` を返し、エージェントは必要なスコープを示すはずです。
3. Company の **Sign in to** ボタンをクリックし、自社のページでサインインして承認します。ステップ 4 から 6 を確認できます。
4. 同じ操作をもう一度送信すると、今度は成功するはずです。ステップ 7 を確認できます。

続いて、Poppy Simulator など自分で作成していないエージェントでも同じテストを行ってください。各ツールで確認すべき項目のチェックリストを含め、概要ページの[Poppy の動作を見る](https://developers.authlete.com/ja/protocols-and-flows/protocol-extensions/personal-agent-protocol-poppy.md#poppy-の動作を見る)をご覧ください。

## トラブルシューティング

| エラー | 原因 | 対処 |
| :- | :- | :- |
| `[A505301]` | Authlete がエージェントのメタデータを取得できなかった。 | エージェントの `client_id` の URL を `https` で公開し、外部からアクセスできるようにする必要があります。 |
| `[A505306]` | エージェントの `token_endpoint_auth_method` をサービスがサポートしていない。 | `supportedTokenAuthMethods` に `PRIVATE_KEY_JWT` を追加します。 |
| `[A505307]` | エージェントのメタデータの値（多くの場合グラントタイプ）をサービスがサポートしていない。 | [CIMD の概要](https://developers.authlete.com/ja/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md)の「メタデータポリシー」で取り除きます。サービスに追加するのは、そのグラントを提供する場合だけです。 |
| `[A011317]` | `redirect_uri` がエージェントのメタデータに記載されていない。 | エージェントは記載したリダイレクト URI を使う必要があります。 |
| `[A157306]` | サービスがサポートしていないアルゴリズム、またはメタデータに記載したものとは異なるアルゴリズムでアサーションが署名された。 | Poppy が必須とする `ES256` と `PS384` をサービスがサポートしていることを確認します。 |
| `[A157356]` | エージェントのアサーションの `aud` クレームが自社の発行者ではない。 | エージェントはトークンエンドポイントではなく、発行者宛てにアサーションを作成する必要があります。Authlete は `clientAssertionAudRestrictedToIssuer` が有効なときにこれを確認します。 |
| `[A222101]` | Device Sign-In が試行されたが、`deviceVerificationUri` が設定されていない。 | 設定するか、`supportedGrantTypes` から `DEVICE_CODE` を削除します。 |
| `[A057302]` | アクセストークンが存在しない。 | `401` を返します。 |
| `[A065308]` | アクセストークンは DPoP 鍵に紐付いているが、リクエストに DPoP プルーフがない。 | `401` を返します。DPoP に紐付いたトークンを使うリクエストでは、エージェントは毎回新しい DPoP プルーフを送る必要があります。 |
| `[A286301]` | アクセストークンに、この操作に必要なスコープが含まれていない。 | `insufficient_scope` とともに `403` を返します。エージェントはそのスコープで User に再度サインインしてもらえます。 |
| API が `invalid_session` を返す | Session ヘッダの確認で正当なエージェントが拒否された。 | `aud` を発行者と、`htu` を内部 URL ではなくリクエストの公開 URL と比較しているか確認します。 |

## 本番運用の前に

* **受け入れるエージェントを決める。** Poppy はこの判断を Company に任せています。許可リストを使うと登録したエージェントだけを受け入れられ、最も安全ですが、確認していないエージェントは拒否されます。許可リストを使わない場合はどのエージェントも登録でき、メタデータポリシーで宣言できる内容を制限します。いずれの場合も、テスト用の許可リストは自社の方針に置き換えてください。[CIMD の概要](https://developers.authlete.com/ja/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md)をご覧ください。
* **自社のドメインで User をサインインさせる。** 認可サーバーとサインインページは、自社ドメイン配下の `auth.` や `account.` など、User が見分けられるホストで運用します。
* **アサーションの audience を発行者に限定する。** `clientAssertionAudRestrictedToIssuer` を有効にし、それ以外を宛先とするクライアントアサーションを Authlete が拒否するようにします。
* **動作するものだけを公開する。** メタデータに記載したすべてのグラントタイプが動作し、`poppy.json` のすべてのスコープに説明が必要です。ヒントは任意ですが、記載する場合は `changes` と `personal_data` の両方が必要です。
* **キャッシュを有効にし、開発用の設定は無効にしておく。** `cimdAlwaysRetrieved`、`cimdHttpPermitted`、`cimdQueryPermitted` は無効のままにし、`httpAliasProhibited` を有効にします。
* **すべてのリクエストで Session ヘッダを確認する。** サインアウト状態のリクエストも含みます。

> [!NOTE]
>
> **既知の制限（§4.1）:** Poppy の §4.1 では、`redirect_uris` の各エントリが `client_id` と同じドメイン（またはループバック）にあることが求められます。仕様はこのルールを「OAuth より厳しい」ものとして位置付けています。Authlete は CIMD を取得して検証する際、`redirect_uri` について RFC 9700 の完全一致による確認は行いますが、§4.1 の同一ドメインの確認は行いません。そのため現時点では、`client_id` と `redirect_uris` が異なるドメインにある CIMD も受け入れられます。完全に準拠した Company であれば、このような CIMD は拒否します。Authlete では、「Poppy プロファイル」の導入の一環として、この確認の追加を検討します。

## 次のステップ

* [Poppy の概要](https://developers.authlete.com/ja/protocols-and-flows/protocol-extensions/personal-agent-protocol-poppy.md): Poppy の仕組み、Authlete が担う部分、Company のテスト方法を説明します。
* [CIMD の概要](https://developers.authlete.com/ja/protocols-and-flows/protocol-extensions/oauth-client-id-metadata-document-cimd.md): 許可リストやメタデータポリシーを含む、CIMD のすべての設定を説明します。
* [Personal Agent Protocol 仕様](https://personalagentprotocol.org/docs/1.0/spec)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.