diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b5ca0a..115974b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,32 @@ # Changelog +## 0.37.2 (2026-11-17) + +Fixes from the review of 0.37.1, and what a host needs to push a Direct Sign-In whose redirect +lands in another service. In both SDKs; additive API only. + +- **Opening a sign-in link consumes nothing** (spec 4.2). `open_link` (`openLink`) took the + link's record and put it back; an opening paused between the two while `complete` consumed + the sign-in restored a link whose callbacks could no longer succeed. It now reads the record + with the state store's `get`, a new optional method of `AuthorizationStateStore` (a SHOULD: + `get(reference)` returns the record without consuming it, `None`/`undefined` when unknown or + expired). `take` stays the callback's alone. A store without `get` is still accepted and read + by `take` then `put`, which keeps the old race: add `get` to it. The SDKs' own in-memory + stores have it. +- **A link begun by 0.37.0 still opens after an upgrade.** 0.37.0 kept the callback state's + reference under the link's key; 0.37.1 rejected such a link and dropped it. The reader now + follows the reference to the pending sign-in, without consuming it; a store without `get`, + which takes the record to read it, gets it back with the sign-in's expiry, so the link opens + again until the sign-in completes. + *Mixed versions:* a 0.37.0 replica cannot read a link begun by 0.37.1 or later (it takes the + record and rejects it); when replicas share a state store, finish rolling every replica that + serves link pages to 0.37.2 before links are begun on the new version, or route link pages to + upgraded replicas. +- **`DirectSignInStart.state`**: the request's `state`, as a secret (never in `repr`), for a + host whose redirect URI is served by another service that keys the callback by it. With PAR + or a `link_page` the URL the browser opens does not carry it. + ## 0.37.1 (2026-11-17) Fixes from the review of 0.37.0, in both SDKs. No API change. diff --git a/docs/docs/concepts/contribution-points.mdx b/docs/docs/concepts/contribution-points.mdx index 1df2bb0..161c850 100644 --- a/docs/docs/concepts/contribution-points.mdx +++ b/docs/docs/concepts/contribution-points.mdx @@ -44,7 +44,7 @@ other fails CI. | `pap.signer` | `SIGNERS` | `Signers` | The agent's client assertions and delegations (keys stay in custody) | — (host contributes) | | | `pap.tokenStore` | `TOKEN_STORES` | `TokenStores` | Refresh tokens behind opaque references | — (host contributes) | | | `pap.pairwiseUserIdStore` | `PAIRWISE_USER_ID_STORES` | `PairwiseUserIdStores` | Stable pairwise user IDs by tenant, local user, and issuer | — (host contributes) | yes | -| `pap.authorizationStateStore` | `AUTHORIZATION_STATE_STORES` | `AuthorizationStateStores` | Expiring one-use sign-in state (put, take) | — (host contributes) | | +| `pap.authorizationStateStore` | `AUTHORIZATION_STATE_STORES` | `AuthorizationStateStores` | Expiring one-use sign-in state (put, take; get SHOULD, read without consuming, since 0.37.2) | — (host contributes) | | | `pap.cache` | `CACHES` | `Caches` | Bounded cache of public metadata | `memory` | | | `pap.browserHandoff` | `BROWSER_HANDOFFS` | `BrowserHandoffs` | Opens a sign-in page on a trusted surface | — (host contributes) | | | `pap.browserJoin` | `BROWSER_JOINS` | `BrowserJoins` | The agent's own browser: loads the join form's one-time code and submits the form | — (host contributes) | | diff --git a/docs/docs/guides/direct-sign-in.mdx b/docs/docs/guides/direct-sign-in.mdx index b589322..9f8e05a 100644 --- a/docs/docs/guides/direct-sign-in.mdx +++ b/docs/docs/guides/direct-sign-in.mdx @@ -123,6 +123,15 @@ on their phone, goes to a page of your own: pass `link_page="https://agent.example/sign-in/{link}"` (`linkPage`) and the browser handoff gets that page; when it is opened, it calls `open_link(link)` (`openLink`), which pushes the request then, and redirects to the URL it returns. +Opening a link reads its record without consuming it, through the state store's +`get`; give your store one (a store with only `put` and `take` is read by taking +and putting back, which a completing callback can race). A link may be opened +again until its sign-in completes; then it opens nothing. + +With PAR or a link page, the URL the browser opens carries no `state`. When your +redirect URI is served by another service than the one that called `begin`, key +the callback there by `started.state` (`DirectSignInStart.state`, a secret), the +value the company sends back with the code. A sign-in names no `resource`: it covers every service the company offers, those it adds later too, and each token request names one (§4.5, see diff --git a/docs/docs/protocol/conformance-report.mdx b/docs/docs/protocol/conformance-report.mdx index 11e06e9..4cbb2e0 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.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. +SDK version **0.37.2**, 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/releases/compatibility.mdx b/docs/docs/releases/compatibility.mdx index 274db08..7eb76a2 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.1**. +This page is versioned with the SDK: it describes **SDK 0.37.2**. ## 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.2` | `0.4` | 2026-11-10 | v3 | none: opening a sign-in link reads its record without consuming it (the state store's optional `get`), a link begun by 0.37.0 still opens after an upgrade, and the Direct Sign-In start names its `state` for hosts whose redirect lands elsewhere | | `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 | diff --git a/package.json b/package.json index 369edbe..58f799f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@datalayer/personal-agent-protocol", - "version": "0.37.1", + "version": "0.37.2", "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 e1a9fac..c836c24 100644 --- a/personal_agent_protocol/__tests__/test_published_10.py +++ b/personal_agent_protocol/__tests__/test_published_10.py @@ -956,7 +956,8 @@ async def recording(reference: str) -> object: 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) + # Read with the store's `get`: an opening consumes nothing, the link's record included. + assert 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] @@ -995,3 +996,121 @@ async def company(_: httpx.Request) -> httpx.Response: 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"] + + +async def _pushed_link(world: World, browser: Any) -> tuple[DirectSignInClient, str, Any]: + await world.signed_out_session() + metadata = world.company.oauth_metadata + assert metadata is not None + client = DirectSignInClient(reactor=world.reactor, http_client=world.http) + start = 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}", + ) + ) + return client, browser.urls[-1].rsplit("/", 1)[1], start + + +@pytest.mark.asyncio +async def test_an_opening_paused_while_the_callback_completes_never_restores_the_link() -> None: + """Copilot's review of 0.37.1: an opening paused between reading the link and writing it + back, while `complete` consumed the sign-in, restored a link whose callbacks could not + succeed. An opening reads only (`get`), so the completed sign-in's link stays gone.""" + import asyncio + + world, browser = _recording_world(replace(CONFIG, pushed_authorization_requests="required")) + client, link, _ = await _pushed_link(world, browser) + await browser.open(await client.open_link(link)) + callback = await world.shop.approve_authorization(browser.request_id, account_id="acct_ada") # type: ignore[arg-type] + store = first_contribution(world.reactor, AUTHORIZATION_STATE_STORES, "state store") + read, resume = asyncio.Event(), asyncio.Event() + get = store.get + + async def pausing(reference: str) -> object: + value = await get(reference) + read.set() + await resume.wait() + return value + + store.get = pausing # type: ignore[method-assign] + opening = asyncio.create_task(client.open_link(link)) + await read.wait() + store.get = get # type: ignore[method-assign] + assert (await client.complete(callback)).token is not None + resume.set() + await opening # it read before the sign-in completed + with pytest.raises(AuthorizationError): + await client.open_link(link) + + +@pytest.mark.asyncio +async def test_a_link_begun_by_0_37_0_opens_after_an_upgrade_without_consuming_its_state() -> None: + """0.37.0 kept the callback state's reference under the link's key: the reader follows it, + never consuming the state, so the sign-in still completes.""" + from personal_agent_protocol.auth import _link_reference, _state_reference + + world, browser = _recording_world(replace(CONFIG, pushed_authorization_requests="required")) + client, link, start = await _pushed_link(world, browser) + store = first_contribution(world.reactor, AUTHORIZATION_STATE_STORES, "state store") + reference = _state_reference(start.state.get_secret_value()) + until = world.clock.now() + timedelta(minutes=5) + await store.put(_link_reference(link), reference, expires_at=until) + await browser.open(await client.open_link(link)) + assert await store.get(reference) is not None # the state is still there + 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) + + +@pytest.mark.asyncio +async def test_a_store_without_get_is_read_by_taking_and_putting_back( + monkeypatch: pytest.MonkeyPatch, +) -> None: + world, browser = _recording_world(replace(CONFIG, pushed_authorization_requests="offered")) + client, link, _ = await _pushed_link(world, browser) + store = first_contribution(world.reactor, AUTHORIZATION_STATE_STORES, "state store") + # A store written before 0.37.2: `put` and `take` only. + monkeypatch.setattr(store, "get", None) + first = await client.open_link(link) + again = await client.open_link(link) + assert "request_uri=" in first.get_secret_value() and "request_uri=" in again.get_secret_value() + + +@pytest.mark.asyncio +async def test_the_start_names_the_state_the_callback_carries() -> None: + """A host whose redirect lands in another service keys the callback by `state`, which a + pushed request's URL does not carry (PAR): the start names it.""" + world, browser = _recording_world() + await world.signed_out_session() + client = DirectSignInClient(reactor=world.reactor, http_client=world.http) + start = await client.begin(**_direct_arguments(world)) + assert start.state is not None + assert parse_qs(urlsplit(browser.urls[-1]).query)["state"] == [start.state.get_secret_value()] + assert start.state.get_secret_value() not in repr(start) + + +@pytest.mark.asyncio +async def test_a_0_37_0_link_in_a_store_without_get_opens_again_until_the_sign_in_completes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Copilot's review of #20: a store without `get` took the 0.37.0 string record to read it, + and nothing put it back, so the link opened once only.""" + from personal_agent_protocol.auth import _link_reference, _state_reference + + world, browser = _recording_world(replace(CONFIG, pushed_authorization_requests="required")) + client, link, start = await _pushed_link(world, browser) + store = first_contribution(world.reactor, AUTHORIZATION_STATE_STORES, "state store") + reference = _state_reference(start.state.get_secret_value()) + until = world.clock.now() + timedelta(minutes=5) + await store.put(_link_reference(link), reference, expires_at=until) + monkeypatch.setattr(store, "get", None) + await client.open_link(link) + await browser.open(await client.open_link(link)) # opens again + 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) diff --git a/personal_agent_protocol/__version__.py b/personal_agent_protocol/__version__.py index 8a42ab2..ab62c43 100644 --- a/personal_agent_protocol/__version__.py +++ b/personal_agent_protocol/__version__.py @@ -7,4 +7,4 @@ """Personal Agent Protocol.""" -__version__ = "0.37.1" +__version__ = "0.37.2" diff --git a/personal_agent_protocol/auth.py b/personal_agent_protocol/auth.py index 9dbe224..57620ae 100644 --- a/personal_agent_protocol/auth.py +++ b/personal_agent_protocol/auth.py @@ -271,6 +271,10 @@ class DirectSignInStart(ProtocolModel): #: Whether the authorization URL opens on a device other than the one the User is #: using (§4.2): a cross-device flow, as Device Sign-In always is (§10.8). cross_device: bool = False + #: The request's `state`, for a host whose redirect lands in another service than the + #: one that began (its callback keyed by it there): with PAR or a `link_page` the URL the + #: browser opens does not carry it. Never shown to the User or a model. + state: SecretStr | None = None #: The longest a Direct Sign-In request lives when its link opens on another device: a @@ -297,6 +301,22 @@ class _PendingDirectSignIn: link: str | None = None +async def _peek(store: AuthorizationStateStore, reference: str) -> object | None: + """A state record read without consuming it: the store's `get` when it has one (the + contract's SHOULD since 0.37.2). A store with only `put` and `take` is read by taking + and putting back, which a `complete` running between the two steps can race: such a + store SHOULD add `get`.""" + + get = getattr(store, "get", None) + if callable(get): + return await get(reference) + value = await store.take(reference) + expires_at = getattr(value, "expires_at", None) + if value is not None and isinstance(expires_at, datetime): + await store.put(reference, value, expires_at=expires_at) + return value + + def _link_reference(link: str) -> str: try: encoded = link.encode("ascii") @@ -473,6 +493,7 @@ async def begin( expires_at=expires_at, requested_scopes=request.scopes, cross_device=cross_device, + state=request.state, ) async def open_link(self, link: str) -> SecretStr: @@ -489,16 +510,27 @@ 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. + # Read, never consumed: only the callback `complete` receives takes state, so an + # opening and a completing callback can interleave, and a completed sign-in's link + # opens nothing more. link_reference = _link_reference(link) - pending = await store.take(link_reference) + pending = await _peek(store, link_reference) + if isinstance(pending, str): + # A link begun by 0.37.0, whose record names the callback state's reference: that + # state is followed, still never consumed, so a link left unexpired across an + # upgrade opens as before. + legacy = pending + pending = await _peek(store, legacy) if legacy.startswith("direct:") else None + if isinstance(pending, _PendingDirectSignIn) and not callable( + getattr(store, "get", None) + ): + # A store without `get` took the string record to read it: put back, with the + # sign-in's expiry, so the link opens again until the sign-in completes. + await store.put(link_reference, legacy, expires_at=pending.expires_at) 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(link_reference, pending, expires_at=pending.expires_at) return await self._authorization_url(pending) async def _authorization_url(self, pending: _PendingDirectSignIn) -> SecretStr: diff --git a/personal_agent_protocol/cli_host.py b/personal_agent_protocol/cli_host.py index 1e92d86..8987c86 100644 --- a/personal_agent_protocol/cli_host.py +++ b/personal_agent_protocol/cli_host.py @@ -202,6 +202,12 @@ def __init__(self, now: Callable[[], datetime]) -> None: async def put(self, reference: str, value: object, *, expires_at: datetime) -> None: self.values[reference] = (value, expires_at) + async def get(self, reference: str) -> object | None: + value, expires_at = self.values.get(reference, (None, None)) + if expires_at is not None and self.now() > expires_at: + return None + return value + async def take(self, reference: str) -> object | None: value, expires_at = self.values.pop(reference, (None, None)) if expires_at is not None and self.now() > expires_at: diff --git a/personal_agent_protocol/company/__init__.py b/personal_agent_protocol/company/__init__.py index 6dfeaff..32a1c07 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.1", + version="0.37.2", contribution_points=[ COMPANY_STORES.id, COMPANY_ACCOUNTS.id, diff --git a/personal_agent_protocol/reactor.py b/personal_agent_protocol/reactor.py index 3ac1f9b..8cf48f0 100644 --- a/personal_agent_protocol/reactor.py +++ b/personal_agent_protocol/reactor.py @@ -120,7 +120,14 @@ async def get_or_create( @runtime_checkable class AuthorizationStateStore(Protocol): - """Persist and atomically consume short-lived authorization state.""" + """Persist and atomically consume short-lived authorization state. + + A store SHOULD also have `async def get(reference) -> object | None`, which reads a + record without consuming it (`None` when unknown or expired): `DirectSignInClient.open_link` + reads a sign-in link's record with it, so opening a link never races the `take` of a + completing callback. Without `get` the link is read by `take` then `put`. `get` is not + part of this runtime-checked Protocol, so stores written before 0.37.2 still qualify. + """ async def put(self, reference: str, value: object, *, expires_at: datetime) -> None: ... @@ -1081,7 +1088,7 @@ def build_pap_reactor( platform.register_plugin( PluginManifest( name="personal-agent-protocol.core", - version="0.37.1", + version="0.37.2", contribution_points=[ DISCOVERY_TRANSPORTS.id, URL_SAFETY_POLICIES.id, diff --git a/src/__tests__/published-10.test.mjs b/src/__tests__/published-10.test.mjs index 989c49b..8fbff46 100644 --- a/src/__tests__/published-10.test.mjs +++ b/src/__tests__/published-10.test.mjs @@ -772,7 +772,8 @@ test("opening a link never takes the callback state", async () => { return take(reference); }; await browser.open(await client.openLink(link)); - assert.ok(taken.length > 0 && taken.every((reference) => !reference.startsWith("direct:"))); + // Read with the store's `get`: an opening consumes nothing, the link's record included. + assert.deepEqual(taken, []); // 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" }); @@ -803,3 +804,95 @@ test("an empty event name is the default message event", async () => { ["state"], ); }); + +async function pushedLink(w, browser) { + const client = new DirectSignInClient({ reactor: w.reactor, fetch: w.fetch }); + const start = await client.begin( + directArguments(w, { + pushedAuthorizationRequestEndpoint: w.metadata.pushed_authorization_request_endpoint, + requirePushedAuthorizationRequests: true, + linkPage: "https://atlas.example/sign-in/{link}", + }), + ); + return { client, link: browser.urls.at(-1).split("/").at(-1), start }; +} + +const hex = async (prefix, value) => + `${prefix}:${Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value))), (byte) => + byte.toString(16).padStart(2, "0"), + ).join("")}`; + +test("an opening paused while the callback completes never restores the link", async () => { + // Copilot's review of 0.37.1: an opening paused between reading the link and writing it back, + // while complete() consumed the sign-in, restored a link whose callbacks could not succeed. + const { w, browser } = await recordingWorld({ pushedAuthorizationRequests: "required" }); + const { client, link } = await pushedLink(w, browser); + await browser.open(await client.openLink(link)); + const callbackUrl = await w.shop.approveAuthorization(browser.requestId, { accountId: "acct_ada" }); + const store = firstContribution(w.reactor, AuthorizationStateStores, "authorization state store"); + const get = store.get.bind(store); + let read; + let resume; + const wasRead = new Promise((resolve) => (read = resolve)); + const resumed = new Promise((resolve) => (resume = resolve)); + store.get = async (reference) => { + const value = await get(reference); + read(); + await resumed; + return value; + }; + const opening = client.openLink(link); + await wasRead; + store.get = get; + assert.ok((await client.complete({ callbackUrl })).token !== undefined); + resume(); + await opening; // it read before the sign-in completed + await assert.rejects(client.openLink(link), AuthorizationError); +}); + +test("a link begun by 0.37.0 opens after an upgrade without consuming its state", async () => { + const { w, browser } = await recordingWorld({ pushedAuthorizationRequests: "required" }); + const { client, link, start } = await pushedLink(w, browser); + const store = firstContribution(w.reactor, AuthorizationStateStores, "authorization state store"); + const reference = await hex("direct", start.state.reveal()); + await store.put(await hex("direct-link", link), reference, { expiresAt: new Date(Date.now() + 300_000) }); + await browser.open(await client.openLink(link)); + assert.ok((await store.get(reference)) !== undefined); // the state is still there + 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 store without get is read by taking and putting back", async () => { + const { w, browser } = await recordingWorld({ pushedAuthorizationRequests: "offered" }); + const { client, link } = await pushedLink(w, browser); + const store = firstContribution(w.reactor, AuthorizationStateStores, "authorization state store"); + store.get = undefined; // a store written before 0.37.2 + assert.ok((await client.openLink(link)).reveal().includes("request_uri=")); + assert.ok((await client.openLink(link)).reveal().includes("request_uri=")); +}); + +test("the start names the state the callback carries", async () => { + const { w, browser } = await recordingWorld(); + const client = new DirectSignInClient({ reactor: w.reactor, fetch: w.fetch }); + const start = await client.begin(directArguments(w, { linkPage: "https://atlas.example/sign-in/{link}" })); + const opened = await client.openLink(browser.urls.at(-1).split("/").at(-1)); + assert.equal(new URL(opened.reveal()).searchParams.get("state"), start.state.reveal()); +}); + +test("a 0.37.0 link in a store without get opens again until the sign-in completes", async () => { + // Copilot's review of #20: a store without get took the 0.37.0 string record to read it, and + // nothing put it back, so the link opened once only. + const { w, browser } = await recordingWorld({ pushedAuthorizationRequests: "required" }); + const { client, link, start } = await pushedLink(w, browser); + const store = firstContribution(w.reactor, AuthorizationStateStores, "authorization state store"); + await store.put(await hex("direct-link", link), await hex("direct", start.state.reveal()), { + expiresAt: new Date(Date.now() + 300_000), + }); + store.get = undefined; + await client.openLink(link); + await browser.open(await client.openLink(link)); // opens again + 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); +}); diff --git a/src/__tests__/support/world.mjs b/src/__tests__/support/world.mjs index e163ec8..6812c39 100644 --- a/src/__tests__/support/world.mjs +++ b/src/__tests__/support/world.mjs @@ -300,6 +300,7 @@ export async function agentHost({ identity, fetch, clock, answers = [], controll value: { async put(reference, value) { state.set(reference, value); }, async take(reference) { const value = state.get(reference); state.delete(reference); return value; }, + async get(reference) { return state.get(reference); }, }, options: { id: "vault" }, }, diff --git a/src/auth.ts b/src/auth.ts index 320a0ac..9da0480 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -21,6 +21,7 @@ import { type SignInResult, } from "./sessions.js"; import { + type AuthorizationStateStore, AuthorizationStateStores, BrowserHandoffs, Clocks, @@ -313,6 +314,12 @@ export interface DirectSignInStart { * (§4.2): a cross-device flow, as Device Sign-In always is (§10.8). */ readonly crossDevice: boolean; + /** + * The request's `state`, for a host whose redirect lands in another service than the one that + * began (its callback keyed by it there): with PAR or a `linkPage` the URL the browser opens does + * not carry it. Never shown to the User or a model. + */ + readonly state?: SecretValue; } /** @@ -409,6 +416,19 @@ async function stateReference(state: string): Promise { ).join("")}`; } +/** + * A state record read without consuming it: the store's `get` when it has one (the contract's + * SHOULD since 0.37.2). A store with only `put` and `take` is read by taking and putting back, + * which a `complete` running between the two steps can race: such a store SHOULD add `get`. + */ +async function peek(store: AuthorizationStateStore, reference: string): Promise { + if (typeof store.get === "function") return store.get(reference); + const value = await store.take(reference); + const expiresAt = (value as { expiresAt?: unknown } | undefined)?.expiresAt; + if (value !== undefined && expiresAt instanceof Date) await store.put(reference, value, { expiresAt }); + return value; +} + /** A sign-in link's key in the authorization state store: its digest, never the link. */ async function linkReference(link: string): Promise { if ([...link].some((character) => character.charCodeAt(0) > 0x7f)) { @@ -574,7 +594,7 @@ export class DirectSignInClient { if (link !== undefined) await store.take(await linkReference(link)); throw new AuthorizationError("browser_handoff_failed", "Browser handoff failed", { cause }); } - return { expiresAt, requestedScopes: request.scopes, crossDevice }; + return { expiresAt, requestedScopes: request.scopes, crossDevice, state: request.state }; } /** @@ -587,15 +607,24 @@ 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. + // Read, never consumed: only the callback `complete` receives takes state, so an opening and + // a completing callback can interleave, and a completed sign-in's link opens nothing more. const linkKey = await linkReference(link); - const pending = await store.take(linkKey); + let pending = await peek(store, linkKey); + if (typeof pending === "string") { + // A link begun by 0.37.0, whose record names the callback state's reference: that state is + // followed, still never consumed, so a link left unexpired across an upgrade opens as before. + const legacy = pending; + pending = legacy.startsWith("direct:") ? await peek(store, legacy) : undefined; + if (isPendingDirectSignIn(pending) && typeof store.get !== "function") { + // A store without `get` took the string record to read it: put back, with the sign-in's + // expiry, so the link opens again until the sign-in completes. + await store.put(linkKey, legacy, { expiresAt: pending.expiresAt }); + } + } 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(linkKey, pending, { expiresAt: pending.expiresAt }); return this.#authorizationUrl(pending); } diff --git a/src/company/index.ts b/src/company/index.ts index 404ada6..de2d333 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.1", + version: "0.37.2", contributionPoints: [ CompanyStores, CompanyAccounts, diff --git a/src/reactor.ts b/src/reactor.ts index acd4f71..6b8183a 100644 --- a/src/reactor.ts +++ b/src/reactor.ts @@ -70,6 +70,13 @@ export interface PairwiseUserIdStore { export interface AuthorizationStateStore { put(reference: string, value: unknown, options: { readonly expiresAt: Date }): Promise; take(reference: string): Promise; + /** + * Reads a record without consuming it (`undefined` when unknown or expired). A store SHOULD + * have it (since 0.37.2): `DirectSignInClient.openLink` reads a sign-in link's record with it, + * so opening a link never races the `take` of a completing callback. Without it the link is read + * by `take` then `put`. + */ + get?(reference: string): Promise; } export interface ProtocolCache { @@ -364,7 +371,7 @@ export function createPapCorePlugin(options: PapCoreOptions = {}) { } return definePlugin({ name: "@datalayer/personal-agent-protocol-core", - version: "0.37.1", + version: "0.37.2", contributionPoints: [ DiscoveryTransports, UrlSafetyPolicies,