Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ targets Codex-provider mode. Their compatibility remains unproven until actual
per-client runs; other T3 providers are also unproven. An official SDK protocol
test does not establish support for those applications.

Hosts can list the signed-in owner's linked agents with the owner-scoped,
paginated `listGrants` ([owner grant listing](docs/API.md#owner-grant-listing))
and can opt individual protected-resource authenticators in to bounded
multipart uploads with header-only bearer credentials
([opt-in multipart uploads](docs/HTTP.md#opt-in-multipart-uploads)). Both are
unreleased source additions and change no package version.

Read the [architecture](docs/ARCHITECTURE.md), [API](docs/API.md), and
[HTTP composition](docs/HTTP.md) before wiring a host. The
[project plan](docs/PROJECT_PLAN.md) distinguishes source work from host gates;
Expand Down
138 changes: 136 additions & 2 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ camelCase; OAuth token responses use the standard snake_case fields.
| `revokeToken` | `{ clientId, token, tokenTypeHint? }` | void; unknown tokens are harmless |
| `getGrant` | browser context, `grantId` | `GrantView` |
| `revokeGrant` | browser context, `grantId` | void |
| `listGrants` | browser context, `{ ownerPrincipal, cursor?, limit?, statuses? }` | `GrantPage` |
| `backfillGrantIndex` | `{ cursor?, limit? }` (host maintenance, no browser context) | `BackfillGrantIndexResult` |

`BrowserApprovalContext` is exactly
`{ authentication: "browser-session", access: AccessContext }`. It comes from
Expand Down Expand Up @@ -116,6 +118,103 @@ current permissions with the approved scope definitions; `roles` and
`entitlements` are always empty. The host must authorize the actual resource
operation using this restricted context.

## Owner grant listing

Hosts that render a connected-agents page call `listGrants` from the trusted
browser session instead of keeping their own owner-to-grant index:

```ts
const page = await service.listGrants(browserContext, {
ownerPrincipal: browserContext.access.principalId,
limit: 20,
});
for (const grant of page.grants) render(grant); // escape display strings
// Next page: pass page.nextCursor back unchanged; null means no older entries.
// Revoke from a CSRF/origin-checked host mutation using a listed grantId:
await service.revokeGrant(browserContext, selectedGrantId);
```

- **Owner-only.** The context must pass the same approval-permission and
current-resolver checks as `getGrant`, and `ownerPrincipal` must equal the
trusted session principal; otherwise the call fails with `access_denied`.
A non-string, empty, control-character, or over-512-character principal and
unknown input fields are `invalid_request`.
- **Bounded pages.** `limit` defaults to 20 and
may not exceed 100. A page performs one owner-index
head read plus at most `limit` index reads and `limit` grant-head reads; it
never scans storage. Results are newest indexed first. Because inactive,
filtered, or removed grants still consume their slot, a page may hold fewer
than `limit` grants, even none, while `nextCursor` is non-null. Approvals
made while paging appear on a fresh first page and never duplicate entries.
- **Owner-bound cursor.** `nextCursor` is an opaque `pgc1.` string bound to
the owner's index partition. It carries a public, unkeyed checksum that
detects inconsistent or accidental edits; it is not tamper-proof, because a
caller can recompute the checksum. A cursor from another owner, an edit that
does not match its checksum, or any malformed value fails with
`invalid_request` and reveals nothing. Safety never depends on the cursor:
every page re-verifies the session and owner, a cursor for another owner's
partition is always rejected, and a position past the owner's current head
is clamped. A deliberately recomputed position only repositions the caller
within their own grants.
- **Safe views.** Each item is exactly the `GrantView` that `getGrant` returns.
Credential hashes, consent fingerprints, PKCE challenges, redirects, and raw
storage records are never included.
- **Statuses.** Listing covers grants the owner approved. Each item carries
its current status: `pending` (approved, credentials not yet issued),
`active`, `revoked`, or `expired` (derived from the absolute expiry as in
`getGrant`). Unapproved authorization requests and denied requests are not
linked agents and are not listed; `getGrant` still reads them by ID. Pass
`statuses`, a non-empty set of distinct values from `pending`, `active`,
`revoked`, and `expired`, to keep only matching items, for example
`statuses: ["active"]`. Because denied requests are never listed, a
`denied` filter value is rejected with `invalid_request` instead of
silently returning empty pages.

The owner index is a separate Storage Core collection,
`agent-access.owner-index.v1`, with one partition per hashed
(issuer, resource, owner). Storage Core transactions are single-partition, so
the index cannot share the grant partition's transaction and no cross-partition
atomicity is claimed. Instead, approval commits the owner's index entry (head
counter, membership, and entry in one owner-partition transaction) _before_ the
grant's approval transition. A committed approval therefore always has an
entry. If the approval is then refused, conflicts, or has an unknown outcome,
the leftover entry is harmless: listing re-reads each authoritative grant head
and returns it only when its issuer, resource, and owner match. Revocation and
expiry change only the grant head, which listing reads, so they need no index
write. Membership records make indexing idempotent.

**Upgrade provisioning.** After this change every approval also reads and
writes `agent-access.owner-index.v1`. Storage Core adapters that keep all
collections in one table or database need no action. A host whose store
provisions collections, tables, or roles explicitly must provision this
collection with the same read/write/transaction rights as
`agent-access.records.v1` before deploying; otherwise approvals fail closed
with `server_error` while existing grants, tokens, and resource access keep
working.

Grants approved before this index existed have no entries. They remain fully
usable through `getGrant`, `revokeGrant`, and every token operation, but do not
appear in `listGrants` until the host runs the bounded, idempotent backfill:

```ts
let cursor: string | null = null;
do {
const step = await service.backfillGrantIndex({
limit: 100,
...(cursor === null ? {} : { cursor }),
});
cursor = step.nextCursor;
} while (cursor !== null);
```

Each call scans at most `limit` physical grant rows (default 100, maximum 1000) through Storage Core's authoritative scan and indexes approved, owned
heads for this issuer and resource. Reruns and concurrent approvals add nothing
twice. The scan cursor is the storage adapter's own continuation and is passed
through unchanged. A non-string or empty cursor, or one exceeding the
configured input bound, fails as `invalid_request`; a cursor the adapter
itself rejects fails as `server_error`. Run it from a host maintenance job
behind host rate limits, never from an agent-facing route.

## Internal credential and validation helpers

These implementation helpers are not exported from the package entry point;
Expand Down Expand Up @@ -156,9 +255,44 @@ when constructed without a status override.

## Retention and activation

The first API deliberately has no list or sweep operation. A host retention
job must keep the entire partition, including consumed refresh hashes and
The API deliberately has no sweep operation; `listGrants` is owner-scoped
discovery, not a retention enumerator. A host retention job must keep the
entire partition, including consumed refresh hashes and
Audit events, until the absolute family lifetime has ended. Cleanup must use
bounded storage operations and a reviewed host retention policy. Deleting
consumed hashes early would disable reuse detection. Source validation does
not publish the package, configure a trusted publisher, or activate a host.

Owner-index rows hold only a grant ID and a sequence number. Listing skips
an entry whose grant head is missing (removed by retention), owned by another
principal, or never approved. Such entries arise only from host retention or
from an approval that failed or lost its outcome after its write-ahead index
commit, so they are rare, but each still occupies a slot on its page. A host
maintenance job may prune them with bounded keyed work. Owner-index and grant
partitions cannot be updated atomically together, so pruning can never be made
strictly race-free against an approval. `approve` commits the index entry
first, and its grant transaction can still commit shortly after the request
deadline, because the deadline is checked before the transaction is sent.
Treat a pending head as possibly in flight well past its expiry:

1. Read an owner's `entry:` row and the referenced grant head.
2. Skip the entry if the head is owned by that principal and approved, or if
the head is `pending` and the current time is earlier than its request
expiry plus a grace period longer than the host's longest approval request
or storage timeout (for example, at least ten minutes).
3. Otherwise (the head is missing, terminal, approved for another principal,
or pending beyond that grace period), delete the `entry:` and matching
`grant:` rows.
4. Run `backfillGrantIndex` to completion on a recurring schedule, not only
once after pruning. It is idempotent and restores any entry that a residual
race removed for a grant that is now approved for its owner, for example an
approval whose transaction outlived the grace period or a device request
that reused a retained locator. Until that repair runs, such a grant stays
fully usable and revocable by ID but is missing from `listGrants`.

Hosts that cannot schedule recurring backfill should not prune: dangling
entries are only skipped page slots, never a disclosure or authorization path.

Never delete an owner-index `head` row while the owner has entries, because
the head orders new entries; a reset head makes later approvals for that owner
fail closed.
11 changes: 11 additions & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ enables a keyed read; only a matching complete credential hash authorizes its
transition. No cross-partition, cross-collection, or role-change transaction is
claimed. Required lifecycle work never depends on the lossy Spine event bus.

Owner discovery uses a separate owner-index collection with one partition per
hashed issuer, resource, and owner. Because the index lives in another
partition, it is a write-ahead locator rather than part of the grant
transaction: approval commits the owner entry first, then the grant
transition. Listing re-reads every authoritative grant head and returns it only
when the owner, issuer, and resource still match, so a leftover entry from a
failed approval never surfaces another principal's grant. Status changes touch
only the grant head. Pages are bounded keyed reads, not scans; a bounded,
idempotent backfill indexes grants approved before the index existed. See
[API.md](API.md#owner-grant-listing).

Credentials use Web Crypto randomness and hashing. Raw device, authorization,
access, and refresh credentials are returned to the client and never persisted,
logged, or included in Audit. This also excludes user codes, PKCE verifiers,
Expand Down
78 changes: 70 additions & 8 deletions docs/HTTP.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,19 +61,81 @@ attach permissive CORS headers to browser consent endpoints.

## Protected resources

`createProtectedResourceAuthenticator({ service, configuration })` returns
`{ authenticate(request, requiredScopes?) }`. Its Promise resolves to
`DelegatedAccess` or an error `Response`. It accepts one `Authorization: Bearer`
`createProtectedResourceAuthenticator({ service, configuration, multipart? })`
returns `{ authenticate(request, requiredScopes?) }`. Its Promise resolves to
`ProtectedResourceAccess` (a `DelegatedAccess`, plus `form` for an opted-in
multipart request) or an error `Response`. It accepts one `Authorization: Bearer`
credential, rejects query `access_token`, and emits a `WWW-Authenticate`
challenge with `resource_metadata` on authentication errors. An insufficient
scope returns HTTP 403 and the required scope in the challenge. Unavailable
authority returns HTTP 503.

The helper never consumes the host's resource body. It rejects form and
multipart content types, so credentials cannot arrive simultaneously in form
and header transports. Hosts requiring form resource operations must implement
their own bounded check for forbidden body credentials around the service's
`authenticate` method. The host still authorizes the actual operation using
By default the helper never consumes the host's resource body. It rejects form
and multipart content types, so credentials cannot arrive simultaneously in
form and header transports. URL-encoded form resource operations remain
unsupported; hosts requiring them must implement their own bounded check for
forbidden body credentials around the service's `authenticate` method.

### Opt-in multipart uploads

File-upload endpoints can opt in per authenticator:

```ts
const uploads = createProtectedResourceAuthenticator({
service,
configuration,
multipart: { maxBytes: 4 * 1024 * 1024 }, // omit maxBytes for the 1 MiB default
});
const result = await uploads.authenticate(request, ["files.write"]);
if (result instanceof Response) return result;
const file = result.form?.get("file"); // already parsed and inspected
```

Only an authenticator created with `multipart` accepts `multipart/form-data`;
every other authenticator keeps rejecting it. `maxBytes` defaults to
1 MiB (1048576 bytes) and must be a positive integer no larger
than 16 MiB (16777216 bytes); an invalid bound throws `OAuthError` at
construction. Larger uploads need a separate host transport, such as a
pre-authorized direct upload.

The order is fixed. Header checks run first: Content-Type parameters are
parsed quote-aware (RFC 9110, so quoted values may contain `;`), there must
be exactly one valid RFC 2046 `boundary` parameter (a token, or a quoted
string when it uses spaces or other separators), and a declared
`Content-Length` must be well formed and no larger than the bound. A declared oversize body returns HTTP 413 before any byte
is read. The `Authorization: Bearer` header is then authenticated exactly as
for other requests, so a missing or invalid bearer returns its 401 challenge
without reading the body. Only after the bearer is accepted is the body parsed. Because an upload can
take arbitrarily long, the bearer is authenticated again after parsing, and
the returned access reflects that second check: revocation, expiry, or an
authority change during the upload fails closed.

Credentials still come only from the header. The body is read from
`request.clone()` through a byte counter, so the host's original `Request`
stays unread on success. An oversized or unbounded stream is stopped at the
bound with HTTP 413. On every rejection after the multipart headers are
examined, both tee branches are cancelled so the upload source itself closes;
the host must not read the body of a rejected request. The parsed form is returned as `result.form` so the host need
not parse twice; the host may instead read its untouched original body. For simple file
uploads, budget about twice `maxBytes` per in-flight upload: the tee retains
the unread original while the clone is parsed. This is not a general memory
bound. The bound limits streamed bytes only; the runtime's parsed `FormData`
adds per-part objects and string representations, so bodies with many small
parts or large text fields can cost more. Keep `maxBytes` small for
endpoints that accept many fields, and apply host request concurrency limits. The authenticator rejects with HTTP
400 `invalid_request` any part named `access_token`, `refresh_token`,
`id_token`, `client_secret`, `client_assertion`, `client_assertion_type`,
`device_code`, or `code_verifier` (case-insensitive), and any part name, text value,
or filename containing an issued Agent Access credential. Query `access_token` is
still rejected. File contents are not scanned. Missing, duplicate, or invalid
boundaries, an empty body, and a malformed multipart body are HTTP 400
`invalid_request`. Every 4xx rejection carries the usual `WWW-Authenticate`
challenge; a 503 `server_error` (for example, unavailable current authority)
carries none, as for other resource requests. No rejection includes submitted
values. Non-multipart requests through an opted-in
authenticator behave exactly as before and carry no `form`.

The host still authorizes the actual operation using
the returned restricted `access`; accepting a token alone does not authorize
an operation. Resource transport CORS, routing, body limits, and host limiter
remain host responsibilities.
Expand Down
17 changes: 17 additions & 0 deletions packages/agent-access/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,23 @@ routes with `createAgentAccessHttp` and protect resource handlers with
context for the actual operation. Keep browser approval and its CSRF/origin
checks in the host.

Hosts that render a connected-agents page list the signed-in owner's approved
grants with `listGrants(browserContext, { ownerPrincipal, cursor, limit })`.
Pages are owner-only, bounded (default 20, maximum 100), and continue with an
owner-bound opaque cursor. Each item is the same safe `GrantView` that
`getGrant` returns, including its current status, and can be revoked with
`revokeGrant`. Grants approved before listing existed appear after the host
runs the bounded, idempotent `backfillGrantIndex` maintenance call.

File-upload endpoints may opt in to multipart bodies per authenticator with
`createProtectedResourceAuthenticator({ service, configuration, multipart: { maxBytes } })`.
The bearer still comes only from the `Authorization` header. The body is bounded
before and during streaming, parsed from a clone so the original request stays
readable on success, rejected (with the upload source cancelled) when any part
carries credential fields, and returned as `result.form`. The bearer is
authenticated again after parsing, so revocation during a slow upload fails
closed. Without the option, multipart bodies are rejected as before.

Actual existing-login/Admin-consent integration and per-client acceptance remain
open for each host. The fictional protocol example does not establish those
results.
Expand Down
21 changes: 21 additions & 0 deletions packages/agent-access/src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,24 @@ export function scopeFingerprint(
}));
return sha256(`agent-access:scopes:v1:${JSON.stringify(selected)}`);
}

/** Owner-index partition; unambiguous JSON framing separates the bound identifiers. */
export function ownerIndexPartition(
issuer: string,
resource: string,
ownerId: string,
): Promise<string> {
return sha256(
`agent-access:owner-index:v1:${JSON.stringify([issuer, resource, ownerId])}`,
);
}

/** Integrity check for a public listing cursor. It is not a secret and never authorizes. */
export async function grantCursorCheck(
ownerPartition: string,
position: number,
): Promise<string> {
return (
await sha256(`agent-access:grant-cursor:v1:${ownerPartition}.${position}`)
).slice(0, 22);
}
Loading
Loading