From 7cad21b63fe65b928b575341d22b5bb8db7fe876 Mon Sep 17 00:00:00 2001 From: Eric Charles Date: Tue, 17 Nov 2026 12:27:12 +0100 Subject: [PATCH 1/2] 0.37.1: fixes from the review of 0.37.0 A bound refresh token keeps its sign-in at a Bearer-only MCP server (the refresh proves with the refresh token's key whenever the issuer lists ES256; the company gives such a server Bearer tokens); open_link reads the link's own record and leaves the callback state to complete; effectiveContext defines own properties (a __proto__ field stays a field); an empty SSE event name is a message; the PAR conformance check requires an explicit OAuth refusal. Tests in both SDKs. --- CHANGELOG.md | 25 +++++ docs/docs/protocol/conformance-report.mdx | 2 +- .../coverage/operational-guidance.mdx | 2 +- docs/docs/releases/compatibility.mdx | 3 +- package.json | 2 +- .../__tests__/test_published_10.py | 105 +++++++++++++++++- personal_agent_protocol/__version__.py | 2 +- personal_agent_protocol/accounts.py | 16 ++- personal_agent_protocol/auth.py | 27 +++-- personal_agent_protocol/company/__init__.py | 2 +- personal_agent_protocol/company/service.py | 13 +++ personal_agent_protocol/conformance.py | 22 ++-- personal_agent_protocol/conversations.py | 3 +- personal_agent_protocol/reactor.py | 2 +- protocol/fixtures/conformance/dpop.json | 8 +- protocol/requirements.yaml | 1 + src/__tests__/published-10.test.mjs | 78 ++++++++++++- src/__tests__/support/conformance.mjs | 22 ++-- src/accounts.ts | 16 ++- src/auth.ts | 23 ++-- src/company/index.ts | 2 +- src/company/service.ts | 17 ++- src/conversations.ts | 3 +- src/models.ts | 4 +- src/reactor.ts | 2 +- 25 files changed, 343 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c92656..cf7dad0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,31 @@ # Changelog +## 0.37.1 (2026-11-17) + +Fixes from the review of 0.37.0, in both SDKs. No API change. + +- **A bound refresh token keeps its sign-in at a Bearer-only MCP server** (spec 4.4, 4.5, 7). + `token_for_mcp` (`tokenForMcp`) replaced the issuer's DPoP algorithms with the server's, so + for a server that takes only Bearer the refresh went without a proof; a company that binds + refresh tokens answered `invalid_grant` and the refresh token was deleted. The refresh now + proves with the refresh token's key whenever the issuer lists ES256, and the reference + companies give a server whose metadata lists no DPoP algorithm a Bearer token even after a + proof. The conformance case `dpop.mcp-server-decides-the-proof` checks the token type the + server takes. +- **`open_link` no longer takes the callback state** (spec 4.2). The link has its own record, a + copy of the request, so a link reopened while the redirect is being completed can't make + `complete` fail; `complete` alone consumes the state, and drops the link with it. +- **`effectiveContext`** (TypeScript) defines each field as an own property: a context field + named `__proto__` is a field, never the object's prototype. Python's dict had no such issue. +- **An empty SSE `event:` name** is the default `message` event, never skipped as unknown + (spec 8.6). +- **Conformance**: `dpop.pushed-authorization-request` requires an explicit OAuth refusal (an + error response, or a redirect with `error`) for a request that wasn't pushed; a redirect to a + login page no longer passes. +- Python 3.10: the RSA key-size check reads the modulus with an explicit byte order (fixed + before the 0.37.0 tag; the 3.10 CI job runs the PS384 tests). + ## 0.37.0 (2026-11-17) Version 1.0 **as published** (upstream `8c02b42`, frozen 2026-11-14; reviewed through diff --git a/docs/docs/protocol/conformance-report.mdx b/docs/docs/protocol/conformance-report.mdx index dec235f..11e06e9 100644 --- a/docs/docs/protocol/conformance-report.mdx +++ b/docs/docs/protocol/conformance-report.mdx @@ -6,7 +6,7 @@ title: Compatibility and conformance report # Compatibility and conformance report -SDK version **0.37.0**, PAP profile **0.4** (as published 2026-11-10), Operations extension **v3**; the pairings run at protocol version **1.0**, the default (1.0 as published 2026-11-14); the suite also runs at 0.4 in every pairing. Each pairing runs every positive, negative and recovery fixture case over real TCP and TLS, the personal agent in one language and the reference company (Manzanita) in the other. A case is skipped, never passed, when a side lacks what it needs; the reason is listed below. +SDK version **0.37.1**, PAP profile **0.4** (as published 2026-11-10), Operations extension **v3**; the pairings run at protocol version **1.0**, the default (1.0 as published 2026-11-14); the suite also runs at 0.4 in every pairing. Each pairing runs every positive, negative and recovery fixture case over real TCP and TLS, the personal agent in one language and the reference company (Manzanita) in the other. A case is skipped, never passed, when a side lacks what it needs; the reason is listed below. ## Pairings diff --git a/docs/docs/protocol/coverage/operational-guidance.mdx b/docs/docs/protocol/coverage/operational-guidance.mdx index 3188371..5a9df58 100644 --- a/docs/docs/protocol/coverage/operational-guidance.mdx +++ b/docs/docs/protocol/coverage/operational-guidance.mdx @@ -126,7 +126,7 @@ The Guides' recommendations (SHOULD), kept apart from the specification. Upstrea | `GUIDE-co-session-05` | Verifying the Session header | SHOULD | company | Rejecting a reused jti is optional, as it is for DPoP proofs. | [`verify_session_jwt`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/verify.py)
[`CompanyService._caller`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py)
[`StoreReplayCache`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/points.py) | [`test_delegated_keys.py::test_a_session_jwt_has_the_specs_header_and_claims`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_delegated_keys.py)
[`test_security_review.py::test_a_copied_access_token_is_worth_nothing_without_the_agents_session_jwt`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_security_review.py)
[`test_conformance.py::test_python_agent_python_company_over_tls`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_conformance.py)
[`test_company_refusals.py::test_a_replayed_token_request_is_refused`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_company_refusals.py)
`security.session-jwt-replay` | implemented | | `GUIDE-co-session-06` | Verifying the Session header | SHOULD | company | Binding access tokens with DPoP is your choice (4.5). If you do, verify the proof as RFC 9449 describes, separately from the Session JWT. | [`verify_dpop_proof`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/verify.py)
[`CompanyConfig`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py)
[`CompanyService._caller`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py) | [`test_dpop.py::test_optional_binds_with_a_proof_and_issues_bearer_without`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_dpop.py)
[`test_dpop.py::test_a_refused_proof_spends_no_device_code`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_dpop.py)
[`test_conformance.py::test_python_agent_python_company_binding_with_dpop_over_tls`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_conformance.py)
`dpop.metadata-lists-es256`
`dpop.token-bound-and-used`
`dpop.token-request-needs-a-proof`
`dpop.token-proof-for-another-url`
`dpop.token-proof-with-ath`
`dpop.token-proof-outside-the-window`
`dpop.token-proof-wrong-typ`
`dpop.nonce-at-the-token-endpoint`
`dpop.nonce-at-a-resource`
`dpop.bound-token-without-a-proof`
`dpop.bound-token-as-bearer`
`dpop.proof-of-another-key`
`dpop.proof-replayed`
`dpop.proof-wrong-ath`
`dpop.proof-wrong-htm`
`dpop.proof-wrong-htu`
`dpop.proof-outside-the-window`
`dpop.session-header-still-checked`
`dpop.conversation-and-stream`
`dpop.feedback`
`dpop.browser-join`
`dpop.mcp-token-bound`
`dpop.mcp-challenge-keeps-resource-metadata`
`dpop.mcp-challenges-bearer-then-dpop` | implemented | | `GUIDE-co-session-07` | Verifying the Session header | SHOULD | company | Session records need not be durable; conversations are separate records that can outlast the session that started them. Behind a load balancer, share session state across the servers that handle it, as with server-side cookie sessions, so requests reach the same state whichever server handles them. | [`CompanyStore`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/store.py) | [`test_company_store.py::test_a_company_restarted_over_its_store_continues_every_flow`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_company_store.py)
[`test_security_review.py::test_finding_4_a_session_jwt_replayed_at_another_replica_is_refused`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_security_review.py) | implemented | -| `GUIDE-mcp-01` | MCP and UCP interoperability | SHOULD | both | Use Bearer tokens for ordinary MCP authorization. Use DPoP only with a server that advertises it and a client that supports it (section 7): the issuer that requires a proof still lets ordinary MCP clients get a Bearer token for an MCP resource. | [`RefreshTokenClient.token_for_mcp`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/accounts.py)
[`ServiceTokens.token_for`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/accounts.py)
[`CompanyService.protected_resource_metadata`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py)
[`CompanyService._token_binding`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py)
[`CompanyConfig.mcp_token_schemes`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py) | [`test_fixtures.py::test_local_fixture_case`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_fixtures.py)
[`test_conformance.py::test_python_agent_python_company_binding_with_dpop_over_tls`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_conformance.py)
`dpop.mcp-proof-from-the-servers-metadata`
`dpop.mcp-metadata-lists-es256`
`dpop.mcp-challenges-bearer-then-dpop`
`dpop.mcp-bearer-without-a-proof`
`dpop.mcp-server-decides-the-proof` | implemented | +| `GUIDE-mcp-01` | MCP and UCP interoperability | SHOULD | both | Use Bearer tokens for ordinary MCP authorization. Use DPoP only with a server that advertises it and a client that supports it (section 7): the issuer that requires a proof still lets ordinary MCP clients get a Bearer token for an MCP resource. | [`RefreshTokenClient.token_for_mcp`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/accounts.py)
[`ServiceTokens.token_for`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/accounts.py)
[`CompanyService.protected_resource_metadata`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py)
[`CompanyService._token_binding`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py)
[`CompanyConfig.mcp_token_schemes`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py)
[`CompanyService._takes_dpop`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/company/service.py) | [`test_fixtures.py::test_local_fixture_case`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_fixtures.py)
[`test_conformance.py::test_python_agent_python_company_binding_with_dpop_over_tls`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_conformance.py)
`dpop.mcp-proof-from-the-servers-metadata`
`dpop.mcp-metadata-lists-es256`
`dpop.mcp-challenges-bearer-then-dpop`
`dpop.mcp-bearer-without-a-proof`
`dpop.mcp-server-decides-the-proof` | implemented | | `GUIDE-pa-ids-05` | User IDs | SHOULD | personal-agent | When adding or changing an issuer changes the Company's identifier, use new user IDs, agent IDs, delegated keys, and sessions. Do not fall back to the domain because issuer discovery failed. | [`DiscoveredCompany.identifier`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/models.py)
[`DiscoveryClient.discover`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/discovery.py) | [`test_issuerless.py::test_a_known_issuer_is_never_lost_to_an_error`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_issuerless.py) | implemented | | `GUIDE-pa-access-01` | Planning account access | SHOULD | personal-agent | A conversation entry's access: signed_in hints that it needs account access from the start; without that hint, start signed out and respond to challenges or authorization events. | [`AgentProtocol.account_access`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/models.py) | [`test_fixtures.py::test_local_fixture_case`](https://github.com/datalayer/personal-agent-protocol/blob/main/personal_agent_protocol/__tests__/test_fixtures.py) | **partial**: The SDK reads the hint (account_access); when to sign in is the host's. | | `GUIDE-co-web-cookie-01` | Browser sessions | SHOULD | company | Use a cookie for the session that's separate from your login cookie, and check it first. After a signed-out join, keep the browser's login cookie. After a signed-in join, clear it, so the browser is signed out when the session's sign-in ends. | — | — | **not-applicable**: The reference companies have no website login beyond the Session's cookie, which a later join replaces. | diff --git a/docs/docs/releases/compatibility.mdx b/docs/docs/releases/compatibility.mdx index 6424333..274db08 100644 --- a/docs/docs/releases/compatibility.mdx +++ b/docs/docs/releases/compatibility.mdx @@ -4,7 +4,7 @@ title: Compatibility # Compatibility -This page is versioned with the SDK: it describes **SDK 0.37.0**. +This page is versioned with the SDK: it describes **SDK 0.37.1**. ## The PAP version implemented @@ -35,6 +35,7 @@ profile, never picked up from an unattended fetch. | SDK (PyPI and npm) | PAP profile | Specification revision | Operations | Breaking changes | | --- | --- | --- | --- | --- | +| `0.37.1` | `0.4` | 2026-11-10 | v3 | none: a bound refresh token keeps its sign-in at a Bearer-only MCP server, `open_link` leaves the callback state to `complete`, an empty SSE event name is a message, and `effectiveContext` keeps a `__proto__` field as a field | | `0.37.0` | `0.4` | 2026-11-10 | v3 | [0.36 → 0.37](/releases/migration/#036--037): 1.0 as published (`8c02b42`): required conversation protocol descriptions (`agent_description`), Pushed Authorization Requests, `prompt=consent`, refresh tokens bound to their DPoP key, ports in `organization.domain`, one sign-in for every resource, and unknown values read safely | | `0.36.1` | `0.4` | 2026-11-10 | v3 | none: a Session persisted without its version (before 0.36) restores at 0.4 in TypeScript too, as in Python | | `0.36.0` | `0.4` | 2026-11-10 | v3 | [0.35 → 0.36](/releases/migration/#035--036): the 1.0 draft is the default in both SDKs and both reference companies; 0.4 is used only when named (`protocol_versions`) | diff --git a/package.json b/package.json index 9cdb6ea..369edbe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@datalayer/personal-agent-protocol", - "version": "0.37.0", + "version": "0.37.1", "description": "TypeScript SDK for Personal Agent Protocol 0.4 (2026-11-10) and its Operations extension v3", "repository": { "type": "git", diff --git a/personal_agent_protocol/__tests__/test_published_10.py b/personal_agent_protocol/__tests__/test_published_10.py index cb3c136..e1a9fac 100644 --- a/personal_agent_protocol/__tests__/test_published_10.py +++ b/personal_agent_protocol/__tests__/test_published_10.py @@ -60,6 +60,7 @@ from personal_agent_protocol.demo.manzanita import CONFIG, manzanita from personal_agent_protocol.device import verification_host_allowed from personal_agent_protocol.errors import DiscoveryError, SessionError +from personal_agent_protocol.mcp import fetch_mcp_server_metadata from personal_agent_protocol.models import ( Author, ConversationEvent, @@ -69,7 +70,7 @@ Organization, split_domain, ) -from personal_agent_protocol.reactor import first_contribution +from personal_agent_protocol.reactor import AUTHORIZATION_STATE_STORES, first_contribution from personal_agent_protocol.sessions import build_client_assertion_claims from personal_agent_protocol.transport import SessionHttpClient @@ -892,3 +893,105 @@ def test_an_unknown_authorization_error_signs_in_again_for_its_scopes() -> None: def test_mediated_sign_in_is_retired_on_17_march_2027() -> None: assert MEDIATED_RETIREMENT_DATE == "2027-03-17" assert CompanyRequest is not None + + +# 0.37.1 ----------------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_a_bound_refresh_gets_a_bearer_token_for_a_bearer_only_mcp_server( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The refresh proves with the refresh token's key whatever token it asks for (§4.4), and + a server that takes only Bearer gets Bearer (§4.5): the sign-in is kept.""" + + world = _binding(monkeypatch, dpop_binding="required", bind_refresh_tokens=True) + ctx = world.context() + signed = await _signed_in(ctx) + plain = world.service.protected_resource_metadata() + plain.pop("dpop_signing_alg_values_supported") + monkeypatch.setattr(world.service, "protected_resource_metadata", lambda: plain) + metadata = await ctx.metadata() + server = await fetch_mcp_server_metadata( + ctx.http, world.service.config.mcp_url, issuer=metadata.issuer + ) + assert server.dpop_signing_alg_values_supported is None + context = await ctx.account_context(signed.session.sub) + result = await ctx.agent.accounts.token_for_mcp( + signed.reference, context=context, server=server + ) + assert result.status == "signed_in" and result.token is not None + assert result.token.token_type == "Bearer" + # The refresh token was kept: the next refresh, by the same key, works. + assert (await ctx.agent.accounts.refresh(signed.reference, context=context)).status == ( + "signed_in" + ) + + +@pytest.mark.asyncio +async def test_opening_a_link_never_takes_the_callback_state( + monkeypatch: pytest.MonkeyPatch, +) -> None: + world, browser = _recording_world(replace(CONFIG, pushed_authorization_requests="required")) + await world.signed_out_session() + metadata = world.company.oauth_metadata + assert metadata is not None + client = DirectSignInClient(reactor=world.reactor, http_client=world.http) + await client.begin( + **_direct_arguments( + world, + pushed_authorization_request_endpoint=metadata.pushed_authorization_request_endpoint, + require_pushed_authorization_requests=True, + link_page="https://atlas.example/sign-in/{link}", + ) + ) + link = browser.urls[-1].rsplit("/", 1)[1] + store = first_contribution(world.reactor, AUTHORIZATION_STATE_STORES, "state store") + taken: list[str] = [] + take = store.take + + async def recording(reference: str) -> object: + taken.append(reference) + return await take(reference) + + monkeypatch.setattr(store, "take", recording) + await browser.open(await client.open_link(link)) + assert taken and all(not reference.startswith("direct:") for reference in taken) + # Opened twice, then completed: complete() alone consumes the state, once. + await client.open_link(link) + callback = await world.shop.approve_authorization(browser.request_id, account_id="acct_ada") # type: ignore[arg-type] + assert (await client.complete(callback)).token is not None + with pytest.raises(AuthorizationError): + await client.open_link(link) + + +def test_a_context_field_named_proto_is_a_field() -> None: + messages = [Message(author=Author(type="agent"), context={"__proto__": {"x": 1}})] + assert effective_context(messages) == {"__proto__": {"x": 1}} + + +@pytest.mark.asyncio +async def test_an_empty_event_name_is_the_default_message_event() -> None: + state = { + "id": "evt_1", + "type": "state", + "created_at": "2026-11-17T09:00:00Z", + "handoff": "none", + "responder": "agent", + "closed": True, + } + lines = f"event:\nid: evt_1\ndata: {json.dumps(state)}\n\n" + + async def company(_: httpx.Request) -> httpx.Response: + return httpx.Response( + 200, headers={"content-type": "text/event-stream"}, content=lines.encode() + ) + + async with httpx.AsyncClient(transport=httpx.MockTransport(company)) as http: + reactor, _ = build_pap_reactor(http_client=http) + reactor.register_plugin(PluginManifest(name="stream-test", version="1"), Plugin()) + client = ConversationClient(transport=SessionHttpClient(reactor=reactor, http_client=http)) + session = conversation_session() + items = [item async for item in client.stream(f"{SHOP}/poppy", "cnv_1", session=session)] + reactor.stop() + assert [type(item).__name__ for item in items] == ["ConversationEvent"] diff --git a/personal_agent_protocol/__version__.py b/personal_agent_protocol/__version__.py index 10af0c0..8a42ab2 100644 --- a/personal_agent_protocol/__version__.py +++ b/personal_agent_protocol/__version__.py @@ -7,4 +7,4 @@ """Personal Agent Protocol.""" -__version__ = "0.37.0" +__version__ = "0.37.1" diff --git a/personal_agent_protocol/accounts.py b/personal_agent_protocol/accounts.py index 6ce7efd..43de2fc 100644 --- a/personal_agent_protocol/accounts.py +++ b/personal_agent_protocol/accounts.py @@ -38,6 +38,7 @@ from reactor import PluginPlatform # type: ignore[import-untyped] from .auth import _https_url, _scopes +from .crypto import DPOP_ALGORITHM from .errors import AuthorizationError, PersonalAgentProtocolError, ProtocolValidationError from .json import loads_strict from .models import DiscoveredCompany, ProtectedResourceMetadata, ProtocolModel @@ -216,13 +217,22 @@ async def token_for_mcp( """An access token for one MCP server: `resource` is its `url` from poppy.json (§7). `server` is its protected resource metadata, as `fetch_mcp_server_metadata` returns - it. MCP's baseline is Bearer: a proof goes only when `server` lists ES256, whatever - the issuer lists, so a server that doesn't gets a Bearer token. + it. The proof is the refresh token's: whenever the issuer lists ES256 the refresh + proves with its DPoP key (§4.4), and the company gives a server that takes only + Bearer a Bearer token (§4.5). With an issuer that lists none, MCP's baseline is + Bearer: a proof goes only when `server` lists ES256. """ + # The refresh proves with the refresh token's own DPoP key whenever the issuer binds + # tokens (§4.4): a company may bind refresh tokens to it whatever token type is asked + # for, and gives a Bearer-only server Bearer tokens all the same (§4.5). Only when the + # issuer lists no algorithm does the server's metadata decide. + issuer_proves = DPOP_ALGORITHM in (context.dpop_signing_algs or ()) return await self.refresh( reference, - context=replace(context, dpop_signing_algs=server.dpop_signing_alg_values_supported), + context=context + if issuer_proves + else replace(context, dpop_signing_algs=server.dpop_signing_alg_values_supported), scopes=scopes, resource=server.resource, ) diff --git a/personal_agent_protocol/auth.py b/personal_agent_protocol/auth.py index 50af480..9dbe224 100644 --- a/personal_agent_protocol/auth.py +++ b/personal_agent_protocol/auth.py @@ -12,7 +12,7 @@ import re import secrets from collections.abc import Callable, Iterable, Sequence -from dataclasses import dataclass +from dataclasses import dataclass, replace from datetime import datetime, timedelta from typing import cast from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit @@ -292,6 +292,9 @@ class _PendingDirectSignIn: pairwise_user_id: str | None = None #: Where the request is pushed (RFC 9126), when it is: each opening pushes it again. pushed_authorization_request_endpoint: str | None = None + #: The link the agent's own page opens it by (`begin(link_page=...)`), dropped with the + #: state when the sign-in completes. + link: str | None = None def _link_reference(link: str) -> str: @@ -450,12 +453,14 @@ async def begin( else _https_url(pushed_authorization_request_endpoint, "PAR endpoint") ), ) + link = None if link_page is None else _base64url(_entropy(16, random_source.bytes)) + pending = replace(pending, link=link) await store.put(reference, pending, expires_at=expires_at) - link: str | None = None try: - if link_page is not None: - link = _base64url(_entropy(16, random_source.bytes)) - await store.put(_link_reference(link), reference, expires_at=expires_at) + if link_page is not None and link is not None: + # The link's own record, a copy of the request: opening the link never takes + # the callback state `complete` consumes (§4.2). + await store.put(_link_reference(link), pending, expires_at=expires_at) await browser.open(SecretStr(link_page.replace("{link}", link))) else: await browser.open(await self._authorization_url(pending)) @@ -484,15 +489,16 @@ async def open_link(self, link: str) -> SecretStr: ), ) clock = cast(Clock, first_contribution(self.reactor, CLOCKS, "clock")) + # Only the link's own record is read (taken and put back): the callback state, which + # `complete` consumes once, is never touched, so an opening and a completing callback + # can interleave. link_reference = _link_reference(link) - reference = await store.take(link_reference) - pending = await store.take(reference) if isinstance(reference, str) else None + pending = await store.take(link_reference) if not isinstance(pending, _PendingDirectSignIn) or clock.now() > pending.expires_at: raise AuthorizationError( "invalid_or_expired_state", "the sign-in link is unknown or has expired" ) - await store.put(cast(str, reference), pending, expires_at=pending.expires_at) - await store.put(link_reference, cast(str, reference), expires_at=pending.expires_at) + await store.put(link_reference, pending, expires_at=pending.expires_at) return await self._authorization_url(pending) async def _authorization_url(self, pending: _PendingDirectSignIn) -> SecretStr: @@ -598,6 +604,9 @@ async def complete( "invalid_or_expired_state", "authorization state is unknown, expired, or already used", ) + if pending.link is not None: + # The sign-in is used up: its link opens nothing more. + await store.take(_link_reference(pending.link)) clock = cast(Clock, first_contribution(self.reactor, CLOCKS, "clock")) if clock.now() > pending.expires_at: raise AuthorizationError("invalid_or_expired_state", "authorization state has expired") diff --git a/personal_agent_protocol/company/__init__.py b/personal_agent_protocol/company/__init__.py index ccad5ab..6dfeaff 100644 --- a/personal_agent_protocol/company/__init__.py +++ b/personal_agent_protocol/company/__init__.py @@ -182,7 +182,7 @@ def build_company( reactor.register_plugin( PluginManifest( name="personal-agent-protocol.company", - version="0.37.0", + version="0.37.1", contribution_points=[ COMPANY_STORES.id, COMPANY_ACCOUNTS.id, diff --git a/personal_agent_protocol/company/service.py b/personal_agent_protocol/company/service.py index 4c6eca8..bc89cc5 100644 --- a/personal_agent_protocol/company/service.py +++ b/personal_agent_protocol/company/service.py @@ -2538,6 +2538,10 @@ async def _issue( follows RFC 6749: left out when it grants exactly the scopes requested. """ + if resource is not None and not self._takes_dpop(resource): + # A server that takes only Bearer gets a Bearer token, even after a proof that a + # bound refresh token needed (§4.4, §4.5). + jkt = None access_token = self._id("at") digest = _digest(access_token) expires_at = self._now() + self.config.access_token_lifetime @@ -2569,6 +2573,15 @@ async def _issue( body["refresh_token"] = refresh_token return CompanyResponse(200, body, {"Cache-Control": "no-store"}) + def _takes_dpop(self, resource: str) -> bool: + """Whether the service at `resource` takes DPoP tokens: the MCP server when its + protected resource metadata lists ES256 (§7), any other service of this company.""" + + if self._mcp() is not None and resource == self.config.mcp_url: + listed = self.protected_resource_metadata().get("dpop_signing_alg_values_supported") + return DPOP_ALGORITHM in (listed or ()) + return True + async def _access_token(self, token: str) -> IssuedAccessToken | None: """The access token's record while it works: issued here, unexpired, sign-in not ended.""" diff --git a/personal_agent_protocol/conformance.py b/personal_agent_protocol/conformance.py index b65ba32..06043d6 100644 --- a/personal_agent_protocol/conformance.py +++ b/personal_agent_protocol/conformance.py @@ -3752,11 +3752,13 @@ async def _dpop_pushed(ctx: ConformanceContext, _: FixtureCase) -> None: scopes=ctx.scenario.scopes, ) unpushed = await ctx.send("GET", request.authorization_url.get_secret_value()) - location = unpushed.headers.get("location", "") - check( - unpushed.status_code >= 400 or "code=" not in location, - f"a request that wasn't pushed is refused, got {unpushed.status_code}", + # An explicit OAuth refusal: an error response, or a redirect carrying `error` (RFC 6749 + # §4.1.2.1). A redirect to a login or consent page, which has no `code` yet, is no refusal. + redirected = dict(parse_qsl(urlsplit(unpushed.headers.get("location", "")).query)) + refused = 400 <= unpushed.status_code < 600 or ( + 300 <= unpushed.status_code < 400 and "error" in redirected and "code" not in redirected ) + check(refused, f"a request that wasn't pushed is refused, got {unpushed.status_code}") check("request_id" not in unpushed.text, "no consent page for it") @@ -3891,19 +3893,23 @@ async def _dpop_mcp_bearer(ctx: ConformanceContext, fixture: FixtureCase) -> Non @case("dpop.mcp-server-decides-the-proof") async def _dpop_mcp_decides(ctx: ConformanceContext, _: FixtureCase) -> None: - """The issuer lists ES256; a server that doesn't gets Bearer, with no proof (§7).""" + """The issuer lists ES256: the refresh for the MCP server's token proves with the refresh + token's key (§4.4), and the token is the type the server takes, Bearer for a server whose + metadata lists no DPoP algorithm (§4.5, §7); the agent uses it as its type names.""" url = await _mcp_url(ctx) metadata = await ctx.metadata() check(metadata.dpop_signing_alg_values_supported, "the issuer lists DPoP") _user, signed = await _signed_in_user(ctx) served = await fetch_mcp_server_metadata(ctx.http, url, issuer=metadata.issuer) - plain = served.model_copy(update={"dpop_signing_alg_values_supported": None}) result = await ctx.agent.accounts.token_for_mcp( - signed.reference, context=await ctx.account_context(signed.session.sub), server=plain + signed.reference, context=await ctx.account_context(signed.session.sub), server=served ) + check(result.status == "signed_in", "the refresh, with the refresh token's proof, works") token = cast(AccessToken, result.token) - check(token.token_type == "Bearer", "a server without the field gets Bearer") # noqa: S105 + takes_dpop = DPOP_ALGORITHM in (served.dpop_signing_alg_values_supported or ()) + wanted = "DPoP" if takes_dpop else "Bearer" + check(token.token_type == wanted, f"a token the server takes, {wanted}") listed = await (await _mcp_client(ctx, signed.session, token, url)).call_tool( _tool(ctx.scenario.mcp_read_tool) ) diff --git a/personal_agent_protocol/conversations.py b/personal_agent_protocol/conversations.py index 088d165..221f2d7 100644 --- a/personal_agent_protocol/conversations.py +++ b/personal_agent_protocol/conversations.py @@ -778,7 +778,8 @@ async def _sse_frames( if size > max_event_bytes: raise ConversationError("response_too_large", "conversation event exceeded limit") if field == "event": - name = value + # An empty name is the default `message` event (HTML SSE): never skipped as unknown. + name = value or "message" elif field == "data": data.append(value) elif field == "id": diff --git a/personal_agent_protocol/reactor.py b/personal_agent_protocol/reactor.py index 050966e..3ac1f9b 100644 --- a/personal_agent_protocol/reactor.py +++ b/personal_agent_protocol/reactor.py @@ -1081,7 +1081,7 @@ def build_pap_reactor( platform.register_plugin( PluginManifest( name="personal-agent-protocol.core", - version="0.37.0", + version="0.37.1", contribution_points=[ DISCOVERY_TRANSPORTS.id, URL_SAFETY_POLICIES.id, diff --git a/protocol/fixtures/conformance/dpop.json b/protocol/fixtures/conformance/dpop.json index 15f5f52..4a854ab 100644 --- a/protocol/fixtures/conformance/dpop.json +++ b/protocol/fixtures/conformance/dpop.json @@ -141,7 +141,7 @@ "requirements": [ "GUIDE-mcp-01" ], - "description": "A token for an MCP server carries a proof only when that server's protected resource metadata lists ES256: the issuer's list doesn't decide it, and the same refresh for any other token follows the issuer's.", + "description": "A token for an MCP server is asked for with the refresh token's proof whenever the issuer lists ES256 (§4.4: a company may bind refresh tokens to that key), and the company returns the type the server takes, Bearer for one whose metadata lists no ES256; with an issuer that lists none, a proof goes only when the server's protected resource metadata lists ES256.", "check": "dpop_mcp_token", "input": [ { @@ -187,10 +187,10 @@ "proof": true }, { - "proof": false + "proof": true }, { - "proof": false + "proof": true }, { "proof": true @@ -526,7 +526,7 @@ "GUIDE-mcp-01" ], "world": "dpop-binding", - "description": "At an issuer that lists DPoP, a server whose metadata doesn't gets a Bearer token and no proof, and accepts it." + "description": "The issuer lists ES256: the refresh for the MCP server's token proves with the refresh token's DPoP key (§4.4), and the company returns the type the server takes, Bearer for a server whose metadata lists no DPoP algorithm (§4.5, §7); the agent uses the token as its token_type names." }, { "id": "dpop.refresh-bound-to-its-key", diff --git a/protocol/requirements.yaml b/protocol/requirements.yaml index 40e0bad..fd47a12 100644 --- a/protocol/requirements.yaml +++ b/protocol/requirements.yaml @@ -5821,6 +5821,7 @@ guide: - personal_agent_protocol.company.service:CompanyService.protected_resource_metadata - personal_agent_protocol.company.service:CompanyService._token_binding - personal_agent_protocol.company.service:CompanyConfig.mcp_token_schemes + - personal_agent_protocol.company.service:CompanyService._takes_dpop tests: - personal_agent_protocol/__tests__/test_fixtures.py::test_local_fixture_case - personal_agent_protocol/__tests__/test_conformance.py::test_python_agent_python_company_binding_with_dpop_over_tls diff --git a/src/__tests__/published-10.test.mjs b/src/__tests__/published-10.test.mjs index 1c61830..989c49b 100644 --- a/src/__tests__/published-10.test.mjs +++ b/src/__tests__/published-10.test.mjs @@ -21,6 +21,7 @@ import test from "node:test"; import { exportJWK, generateKeyPair } from "jose"; import { + AuthorizationStateStores, AuthorizationError, ConversationClient, ConversationError, @@ -40,6 +41,7 @@ import { delegationClaims, discoverCompany, effectiveContext, + fetchMcpServerMetadata, firstContribution, knownConversationError, pageCarriesSession, @@ -138,7 +140,9 @@ async function binding(config) { clock.advance(seconds); }, }; - return new Context({ baseUrl: SHOP, identity: atlas, fetch, scenario, clock, driver }); + const ctx = new Context({ baseUrl: SHOP, identity: atlas, fetch, scenario, clock, driver }); + ctx.service = service; + return ctx; } async function signedInUser(ctx) { @@ -727,3 +731,75 @@ test("an unknown authorization error signs in again for its scopes", () => { test("Mediated Sign-In is retired on 17 March 2027", () => { assert.equal(MEDIATED_RETIREMENT_DATE, "2027-03-17"); }); + +// 0.37.1 ----------------------------------------------------------------------------------- + +test("a bound refresh gets a Bearer token for a Bearer-only MCP server", async () => { + // The refresh proves with the refresh token's key whatever token it asks for (§4.4), and a + // server that takes only Bearer gets Bearer (§4.5): the sign-in is kept. + const ctx = await binding({ dpopBinding: "required", bindRefreshTokens: true }); + const signed = await signedInUser(ctx); + const plain = { ...ctx.service.protectedResourceMetadata() }; + delete plain.dpop_signing_alg_values_supported; + ctx.service.protectedResourceMetadata = () => plain; + const metadata = await ctx.metadata(); + const server = await fetchMcpServerMetadata(ctx.service.config.mcpUrl, { issuer: metadata.issuer, fetch: ctx.fetch }); + assert.equal(server.dpop_signing_alg_values_supported, undefined); + const context = await ctx.accountContext(signed.session.sub); + const result = await ctx.agent.accounts.tokenForMcp(signed.reference, { context, server }); + assert.equal(result.status, "signed_in"); + assert.equal(result.token.tokenType, "Bearer"); + // The refresh token was kept: the next refresh, by the same key, works. + assert.equal((await ctx.agent.accounts.refresh(signed.reference, { context })).status, "signed_in"); +}); + +test("opening a link never takes the callback state", async () => { + const { w, browser } = await recordingWorld({ pushedAuthorizationRequests: "required" }); + const client = new DirectSignInClient({ reactor: w.reactor, fetch: w.fetch }); + await client.begin( + directArguments(w, { + pushedAuthorizationRequestEndpoint: w.metadata.pushed_authorization_request_endpoint, + requirePushedAuthorizationRequests: true, + linkPage: "https://atlas.example/sign-in/{link}", + }), + ); + const link = browser.urls.at(-1).split("/").at(-1); + const store = firstContribution(w.reactor, AuthorizationStateStores, "authorization state store"); + const taken = []; + const take = store.take.bind(store); + store.take = async (reference) => { + taken.push(reference); + return take(reference); + }; + await browser.open(await client.openLink(link)); + assert.ok(taken.length > 0 && taken.every((reference) => !reference.startsWith("direct:"))); + // Opened twice, then completed: complete() alone consumes the state, once. + await client.openLink(link); + const callbackUrl = await w.shop.approveAuthorization(browser.requestId, { accountId: "acct_ada" }); + assert.ok((await client.complete({ callbackUrl })).token !== undefined); + await assert.rejects(client.openLink(link), AuthorizationError); +}); + +test("a context field named __proto__ is a field, never the prototype", () => { + const context = JSON.parse('{"__proto__": {"polluted": true}, "locale": "fr"}'); + const shared = effectiveContext([{ context }]); + assert.deepEqual(Object.keys(shared).sort(), ["__proto__", "locale"]); + assert.deepEqual(shared.__proto__, { polluted: true }); + assert.equal(shared.polluted, undefined); + assert.equal({}.polluted, undefined); +}); + +test("an empty event name is the default message event", async () => { + const w = await shopWorld(); + const session = await w.start(); + const state = { id: "evt_1", type: "state", created_at: "2026-11-17T09:00:00Z", handoff: "none", responder: "agent", closed: true }; + const lines = `event:\nid: evt_1\ndata: ${JSON.stringify(state)}\n\n`; + const transport = mockTransport(w, async () => new Response(lines, { status: 200, headers: { "content-type": "text/event-stream" } })); + const conversations = new ConversationClient({ reactor: w.reactor, transport }); + const items = []; + for await (const item of conversations.stream(`${SHOP}/poppy`, "cnv_1", { session })) items.push(item); + assert.deepEqual( + items.map((item) => item.kind ?? item.type), + ["state"], + ); +}); diff --git a/src/__tests__/support/conformance.mjs b/src/__tests__/support/conformance.mjs index 3984dc0..01fee8b 100644 --- a/src/__tests__/support/conformance.mjs +++ b/src/__tests__/support/conformance.mjs @@ -2740,11 +2740,14 @@ caseFor("dpop.pushed-authorization-request")(async (ctx) => { scopes: ctx.scenario.scopes, }); const unpushed = await ctx.send("GET", request.authorizationUrl.reveal()); + // An explicit OAuth refusal: an error response, or a redirect carrying `error` (RFC 6749 + // §4.1.2.1). A redirect to a login or consent page, which has no `code` yet, is no refusal. const location = unpushed.headers.get("location") ?? ""; - check( - unpushed.status >= 400 || !location.includes("code="), - `a request that wasn't pushed is refused, got ${unpushed.status}`, - ); + const redirected = location ? new URL(location, "https://invalid.example").searchParams : new URLSearchParams(); + const refused = + (unpushed.status >= 400 && unpushed.status < 600) || + (unpushed.status >= 300 && unpushed.status < 400 && redirected.has("error") && !redirected.has("code")); + check(refused, `a request that wasn't pushed is refused, got ${unpushed.status}`); check(!(await textOf(unpushed)).includes("request_id"), "no consent page for it"); }); @@ -2845,18 +2848,21 @@ caseFor("dpop.mcp-bearer-without-a-proof")(async (ctx, fixture) => { }); caseFor("dpop.mcp-server-decides-the-proof")(async (ctx) => { - // The issuer lists ES256; a server that doesn't gets Bearer, with no proof (§7). + // The issuer lists ES256: the refresh for the MCP server's token proves with the refresh + // token's key (§4.4), and the token is the type the server takes, Bearer for a server whose + // metadata lists no DPoP algorithm (§4.5, §7); the agent uses it as its type names. const url = await mcpUrl(ctx); const metadata = await ctx.metadata(); check(metadata.dpop_signing_alg_values_supported?.length, "the issuer lists DPoP"); const [, signed] = await signedInUser(ctx); const served = await fetchMcpServerMetadata(url, { issuer: metadata.issuer, fetch: ctx.fetch }); - const { dpop_signing_alg_values_supported: _listed, ...plain } = served; const result = await ctx.agent.accounts.tokenForMcp(signed.reference, { context: await ctx.accountContext(signed.session.sub), - server: plain, + server: served, }); - check(result.token.tokenType === "Bearer", "a server without the field gets Bearer"); + check(result.status === "signed_in", "the refresh, with the refresh token's proof, works"); + const wanted = (served.dpop_signing_alg_values_supported ?? []).includes("ES256") ? "DPoP" : "Bearer"; + check(result.token.tokenType === wanted, `a token the server takes, ${wanted}`); const listed = await mcpClient(ctx, signed.session, result.token, url).callTool(tool(ctx.scenario.mcp_read_tool)); check(!listed.isError, "and takes it"); }); diff --git a/src/accounts.ts b/src/accounts.ts index eece288..8ce8478 100644 --- a/src/accounts.ts +++ b/src/accounts.ts @@ -30,6 +30,7 @@ import type { ReactorPlatformView } from "@datalayer/reactor"; +import { DPOP_ALGORITHM } from "./crypto.js"; import { AuthorizationError, ProtocolValidationError, type PersonalAgentProtocolError } from "./errors.js"; import { parseJsonStrict } from "./json.js"; import { serviceMetadata, serviceResource, type DiscoveryOptions } from "./discovery.js"; @@ -236,18 +237,25 @@ export class RefreshTokenClient { /** * An access token for one MCP server: `resource` is its `url` from poppy.json (§7). * - * `server` is its protected resource metadata, as `fetchMcpServerMetadata` returns it. MCP's - * baseline is Bearer: a proof goes only when `server` lists ES256, whatever the issuer lists, - * so a server that doesn't gets a Bearer token. + * `server` is its protected resource metadata, as `fetchMcpServerMetadata` returns it. The + * proof is the refresh token's: whenever the issuer lists ES256 the refresh proves with its + * DPoP key (§4.4), and the company gives a server that takes only Bearer a Bearer token + * (§4.5). With an issuer that lists none, MCP's baseline is Bearer: a proof goes only when + * `server` lists ES256. */ tokenForMcp( reference: string, options: Omit & { readonly server: ProtectedResourceMetadata }, ): Promise { const { server, context, ...rest } = options; + // The refresh proves with the refresh token's own DPoP key whenever the issuer binds tokens + // (§4.4): a company may bind refresh tokens to it whatever token type is asked for, and + // gives a Bearer-only server Bearer tokens all the same (§4.5). Only when the issuer lists + // no algorithm does the server's metadata decide. + const issuerProves = context.dpopSigningAlgs?.includes(DPOP_ALGORITHM) ?? false; return this.refresh(reference, { ...rest, - context: { ...context, dpopSigningAlgs: server.dpop_signing_alg_values_supported }, + context: issuerProves ? context : { ...context, dpopSigningAlgs: server.dpop_signing_alg_values_supported }, resource: server.resource, }); } diff --git a/src/auth.ts b/src/auth.ts index 5f1f6be..320a0ac 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -301,6 +301,8 @@ interface PendingDirectSignIn { readonly pairwiseUserId: string | undefined; /** Where the request is pushed (RFC 9126), when it is: each opening pushes it again. */ readonly pushedAuthorizationRequestEndpoint: string | undefined; + /** The link the agent's own page opens it by (`begin({ linkPage })`), dropped with the state. */ + readonly link?: string; } export interface DirectSignInStart { @@ -537,6 +539,7 @@ export class DirectSignInClient { const tokenEndpoint = httpsUrl(options.tokenEndpoint, "tokenEndpoint").toString(); const expiresAt = new Date(clock.now().getTime() + lifetimeSeconds * 1000); const reference = await stateReference(request.state.reveal()); + const link = linkPage === undefined ? undefined : base64Url(entropy(16, (length) => random.bytes(length))); const pending: PendingDirectSignIn = { kind: "pap.direct-sign-in.v1", request, @@ -546,14 +549,15 @@ export class DirectSignInClient { dpopSigningAlgs: options.dpopSigningAlgs, pairwiseUserId: options.pairwiseUserId, pushedAuthorizationRequestEndpoint: pushedEndpoint, + ...(link === undefined ? {} : { link }), }; await store.put(reference, pending, { expiresAt }); - let link: string | undefined; let opened: SecretValue; try { - if (linkPage !== undefined) { - link = base64Url(entropy(16, (length) => random.bytes(length))); - await store.put(await linkReference(link), reference, { expiresAt }); + if (linkPage !== undefined && link !== undefined) { + // The link's own record, a copy of the request: opening the link never takes the + // callback state `complete` consumes (§4.2). + await store.put(await linkReference(link), pending, { expiresAt }); opened = new SecretValue(linkPage.replaceAll("{link}", link)); } else { opened = await this.#authorizationUrl(pending); @@ -583,14 +587,15 @@ export class DirectSignInClient { async openLink(link: string): Promise { const store = firstContribution(this.#reactor, AuthorizationStateStores, "authorization state store"); const clock = firstContribution(this.#reactor, Clocks, "clock"); + // Only the link's own record is read (taken and put back): the callback state, which + // `complete` consumes once, is never touched, so an opening and a completing callback can + // interleave. const linkKey = await linkReference(link); - const reference = await store.take(linkKey); - const pending = typeof reference === "string" ? await store.take(reference) : undefined; + const pending = await store.take(linkKey); if (!isPendingDirectSignIn(pending) || clock.now().getTime() > pending.expiresAt.getTime()) { throw new AuthorizationError("invalid_or_expired_state", "The sign-in link is unknown or has expired"); } - await store.put(reference as string, pending, { expiresAt: pending.expiresAt }); - await store.put(linkKey, reference, { expiresAt: pending.expiresAt }); + await store.put(linkKey, pending, { expiresAt: pending.expiresAt }); return this.#authorizationUrl(pending); } @@ -704,6 +709,8 @@ export class DirectSignInClient { "Authorization state is unknown, expired, or already used", ); } + // The sign-in is used up: its link opens nothing more. + if (pending.link !== undefined) await store.take(await linkReference(pending.link)); const clock = firstContribution(this.#reactor, Clocks, "clock"); if (clock.now().getTime() > pending.expiresAt.getTime()) { throw new AuthorizationError("invalid_or_expired_state", "Authorization state has expired"); diff --git a/src/company/index.ts b/src/company/index.ts index 01b1866..404ada6 100644 --- a/src/company/index.ts +++ b/src/company/index.ts @@ -127,7 +127,7 @@ export function createCompanyDefaultsPlugin( ) { return definePlugin({ name: "personal-agent-protocol.company", - version: "0.37.0", + version: "0.37.1", contributionPoints: [ CompanyStores, CompanyAccounts, diff --git a/src/company/service.ts b/src/company/service.ts index ddb8e3e..957c88d 100644 --- a/src/company/service.ts +++ b/src/company/service.ts @@ -2731,6 +2731,18 @@ export class CompanyService { * with `bindRefreshTokens` (§4.4), recorded with its grant. `scope` follows RFC 6749: left out * when it grants exactly the scopes requested. */ + /** + * Whether the service at `resource` takes DPoP tokens: the MCP server when its protected + * resource metadata lists ES256 (§7), any other service of this company. + */ + #takesDpop(resource: string): boolean { + if (this.#mcp() !== undefined && resource === this.config.mcpUrl) { + const listed = this.protectedResourceMetadata().dpop_signing_alg_values_supported; + return Array.isArray(listed) && listed.includes(DPOP_ALGORITHM); + } + return true; + } + async #issue(options: { readonly clientId: string; readonly accountId: string; @@ -2741,7 +2753,10 @@ export class CompanyService { readonly requested: readonly string[]; readonly jkt: string | undefined; }): Promise { - const { clientId, accountId, scopes, family, resource, refreshToken, requested, jkt } = options; + const { clientId, accountId, scopes, family, resource, refreshToken, requested } = options; + // A server that takes only Bearer gets a Bearer token, even after a proof that a bound + // refresh token needed (§4.4, §4.5). + const jkt = resource !== undefined && !this.#takesDpop(resource) ? undefined : options.jkt; const accessToken = this.#id("at"); const key = digest(accessToken); const expiresAt = this.#later(this.config.accessTokenLifetimeSeconds); diff --git a/src/conversations.ts b/src/conversations.ts index aca0d4d..d1f2e65 100644 --- a/src/conversations.ts +++ b/src/conversations.ts @@ -955,7 +955,8 @@ async function* sseFrames( if (size > maxEventBytes) { throw new ConversationError("response_too_large", "conversation event exceeded limit"); } - if (field === "event") event = content; + // An empty name is the default `message` event (HTML SSE): never skipped as unknown. + if (field === "event") event = content || "message"; else if (field === "data") data.push(content); else if (field === "id") id = content || undefined; } diff --git a/src/models.ts b/src/models.ts index 6588f89..c0078f7 100644 --- a/src/models.ts +++ b/src/models.ts @@ -816,11 +816,13 @@ export function signInScopes(event: ConversationEvent): readonly string[] { * shared (from 1.0). */ export function effectiveContext(messages: Iterable>): Record { + // Own data properties, defined, never assigned: a field named `__proto__` is a field, never + // the object's prototype, as in json.ts. const shared: Record = {}; for (const message of messages) { for (const [name, value] of Object.entries(message.context ?? {})) { if (value === null) delete shared[name]; - else shared[name] = value; + else Object.defineProperty(shared, name, { value, enumerable: true, writable: true, configurable: true }); } } return shared; diff --git a/src/reactor.ts b/src/reactor.ts index fed9fd1..acd4f71 100644 --- a/src/reactor.ts +++ b/src/reactor.ts @@ -364,7 +364,7 @@ export function createPapCorePlugin(options: PapCoreOptions = {}) { } return definePlugin({ name: "@datalayer/personal-agent-protocol-core", - version: "0.37.0", + version: "0.37.1", contributionPoints: [ DiscoveryTransports, UrlSafetyPolicies, From 9893ce08126516abf24a4897c3efa0e4b6f7e921 Mon Sep 17 00:00:00 2001 From: Eric Charles Date: Tue, 17 Nov 2026 12:36:52 +0100 Subject: [PATCH 2/2] CI: the Examples job tests the released Agent Runtimes again (1.6.83 accepts 0.37): AGENT_RUNTIMES_REF emptied --- .github/workflows/examples.yaml | 6 +++--- CHANGELOG.md | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/examples.yaml b/.github/workflows/examples.yaml index e82ce80..25d136c 100644 --- a/.github/workflows/examples.yaml +++ b/.github/workflows/examples.yaml @@ -59,9 +59,9 @@ jobs: # to have no upper bound. The ref is the Agent Runtimes branch that adopts the new # SDK. # - # 0.37 breaks the API: Agent Runtimes adopts it on feat/scenes (pin >=0.37.0,<0.38), so - # the job installs Agent Runtimes from that branch until a release accepts 0.37. - AGENT_RUNTIMES_REF: feat/scenes + # Empty: Agent Runtimes 1.6.83 accepts 0.37 (personal-agent-protocol >=0.37.0,<0.38), + # so the job tests the released package. + AGENT_RUNTIMES_REF: '' steps: - uses: actions/checkout@v6 - uses: astral-sh/setup-uv@v7 diff --git a/CHANGELOG.md b/CHANGELOG.md index cf7dad0..6b5ca0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,8 @@ Fixes from the review of 0.37.0, in both SDKs. No API change. - **Conformance**: `dpop.pushed-authorization-request` requires an explicit OAuth refusal (an error response, or a redirect with `error`) for a request that wasn't pushed; a redirect to a login page no longer passes. +- CI: the Examples job tests the released Agent Runtimes again (1.6.83 accepts 0.37): + `AGENT_RUNTIMES_REF` emptied. - Python 3.10: the RSA key-size check reads the modulus with an explicit byte order (fixed before the 0.37.0 tag; the 3.10 CI job runs the PS384 tests).