diff --git a/docs/KNOWLEDGE_COMPOSITION.md b/docs/KNOWLEDGE_COMPOSITION.md index d0e3aca..ca86c53 100644 --- a/docs/KNOWLEDGE_COMPOSITION.md +++ b/docs/KNOWLEDGE_COMPOSITION.md @@ -289,6 +289,15 @@ the UI reads the actual `GrantView` and displays its returned grant ID/status and revocation controls; a failed management lookup does not undo accepted consent. Logout revokes the browser session, not every agent family. +After an approved PKCE request, the browser replaces the consent-page history +entry with `/account/agents/authorize?grant_id=` before following the +registered callback unchanged. Use Back to return to current owner-only grant +controls and bookmark their link. This URL contains only the public locator, +not an authorization code, state, or credential; it does not grant access. +The pinned Agent Access `0.1.1` uses the same locator for the request and grant. +Returning through this link reads the current `GrantView` directly, even after +the original approval request expires. It does not list other grants. + `/staff/knowledge` exposes capability-gated collection reads, management, draft/report review, exact publication, article retirement and exact evidence revocation. `/knowledge` uses only the three signed-in portal operations and diff --git a/docs/SUPPORT_ASSISTANT_STAGE.md b/docs/SUPPORT_ASSISTANT_STAGE.md index 6cee562..f620c26 100644 --- a/docs/SUPPORT_ASSISTANT_STAGE.md +++ b/docs/SUPPORT_ASSISTANT_STAGE.md @@ -51,7 +51,7 @@ checked during cloud qualification. See ## Run the local checks Use the repository's supported Node version and frozen dependency install. -The current package selection is Support Desk `0.2.12` with direct Knowledge Base +The current package selection is Support Desk `0.2.13` with direct Knowledge Base `0.1.8`; [package.json](../package.json) and the [lockfile](../pnpm-lock.yaml) are authoritative. @@ -91,7 +91,7 @@ reconciliation, with the persisted ledger stable across later duplicates. These historical results apply to that fictional fixture. The earlier public `0.2.5` graph passed the normal 1,125-test local/CI [adoption checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint). -That checkpoint does not qualify the current `0.2.12` graph. Current host +That checkpoint does not qualify the current `0.2.13` graph. Current host validation remains pending. Deployed broker timing, retry delivery, CPU use and wider workloads retain their qualification gates. diff --git a/docs/SUPPORT_CHECKER_CPU_STAGE.md b/docs/SUPPORT_CHECKER_CPU_STAGE.md index 370e4fc..74717f8 100644 --- a/docs/SUPPORT_CHECKER_CPU_STAGE.md +++ b/docs/SUPPORT_CHECKER_CPU_STAGE.md @@ -1,6 +1,6 @@ # Isolated whole-checker CPU fixture -This source harness supports measuring one complete published Support Desk `0.2.12` +This source harness supports measuring one complete published Support Desk `0.2.13` checker invocation with the actual pinned `gpt-tokenizer@4.1.2` GPT-5.4 counter. The [entry](../worker/src/support-checker-cpu-stage-entry.ts) accepts only four fixed queue selectors. The [runner](../worker/src/support-checker-cpu-stage.ts) diff --git a/docs/SUPPORT_CHECKER_UPGRADE.md b/docs/SUPPORT_CHECKER_UPGRADE.md index 88d14f2..6c60d6d 100644 --- a/docs/SUPPORT_CHECKER_UPGRADE.md +++ b/docs/SUPPORT_CHECKER_UPGRADE.md @@ -1,10 +1,10 @@ # Preparing the independent checker wire upgrade -The host pins synchronized public Support Desk `0.2.12`, released from -`b41b301c955b1960ca2c6f9d3a186f2c6be28ca2` after strict public registry and +The host pins synchronized public Support Desk `0.2.13`, released from +`114094de1f55a6b18ba1378cecafa91df877d735` after strict public registry and release-artifact verification. The -[public release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.12) -supersedes the host's `0.2.11` dependency selection. Publication and local tests +[public release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.13) +supersedes the host's `0.2.12` dependency selection. Publication and local tests do not establish provider quality, deployed Free CPU acceptance or customer activation. @@ -36,10 +36,11 @@ Qualification model/version, framing and evidence dates remain operator evidence, checked by the SDK. Unknown models refuse before key access or a provider request. The legacy GPT-4.1-mini checker selection, generation, customer-answer and release-follow-up generator allowlists remain unchanged. -All host checker consumers receive the shared checker tuple/counter; the -published SDK separately refuses provider groups for release-follow-up checks. -That purpose remains held for a group route rather than inheriting a learning -or engineering approval. No +All host checker consumers receive the shared checker tuple/counter. Public +`0.2.13` also supports the explicit group opt-in for release-follow-up checks, +with separate current SD05 purpose evidence; learning or engineering approval +does not authorize that purpose. Release-follow-up generation retains its +existing endpoint restrictions. No route, price, approval, credential or feature flag is installed or enabled by this code change. Customer AI remains off. @@ -86,5 +87,5 @@ Its queue trigger requires its own effective Free CPU allowance and correlated platform invocation evidence; a queue result does not qualify another trigger. Producer contract: -[AI adapter](https://github.com/pegma-dev/support-desk/blob/b41b301c955b1960ca2c6f9d3a186f2c6be28ca2/packages/ai/README.md), -[upgrade notes](https://github.com/pegma-dev/support-desk/blob/b41b301c955b1960ca2c6f9d3a186f2c6be28ca2/docs/UPGRADING.md). +[AI adapter](https://github.com/pegma-dev/support-desk/blob/114094de1f55a6b18ba1378cecafa91df877d735/packages/ai/README.md), +[upgrade notes](https://github.com/pegma-dev/support-desk/blob/114094de1f55a6b18ba1378cecafa91df877d735/docs/UPGRADING.md). diff --git a/docs/SUPPORT_COMPOSITION.md b/docs/SUPPORT_COMPOSITION.md index eb11687..2dece29 100644 --- a/docs/SUPPORT_COMPOSITION.md +++ b/docs/SUPPORT_COMPOSITION.md @@ -16,16 +16,16 @@ provider and customer activation retain their acceptance gates. See the ## Packages -Public selection as of 2026-11-14: Support Desk `0.2.12`, Knowledge Base `0.1.8` +Public selection as of 2026-11-14: Support Desk `0.2.13`, Knowledge Base `0.1.8` and Sessions `0.3.0`. [`package.json`](../package.json) and [`pnpm-lock.yaml`](../pnpm-lock.yaml) are the source of truth for current direct selections and the installed graph. -- `@pegma/support-desk-application@0.2.12` -- `@pegma/support-desk-contracts@0.2.12` -- `@pegma/support-desk-core@0.2.12` -- `@pegma/support-desk-templates@0.2.12` -- `@pegma/support-desk-ai@0.2.12` (optional coordinator) +- `@pegma/support-desk-application@0.2.13` +- `@pegma/support-desk-contracts@0.2.13` +- `@pegma/support-desk-core@0.2.13` +- `@pegma/support-desk-templates@0.2.13` +- `@pegma/support-desk-ai@0.2.13` (optional coordinator) - `@pegma/authorization-admin@0.4.0` (role administration service) - `@pegma/authorization-core@0.4.0` (AccessContext resolution) - `@pegma/authorization-policy@0.4.0` (PolicyDocumentV1 schema validation) @@ -35,7 +35,7 @@ All five Support Desk packages have completed producer publication and registry qualification. The optional AI package selects exact KB application and contracts `0.1.8`; the host selects all four KB packages at that version. Producer qualification and installation do not complete host or provider -acceptance. [Public Support Desk release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.12), +acceptance. [Public Support Desk release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.13), [public KB release](https://github.com/pegma-dev/knowledge-base/releases/tag/v0.1.8). The [checker wire upgrade](SUPPORT_CHECKER_UPGRADE.md) describes fresh route and tokenizer qualification, complete-message admission and the separate Free CPU diff --git a/docs/SUPPORT_LEARNING.md b/docs/SUPPORT_LEARNING.md index b3b9b92..e91eb51 100644 --- a/docs/SUPPORT_LEARNING.md +++ b/docs/SUPPORT_LEARNING.md @@ -17,9 +17,9 @@ activation evidence. ## Packages and authority -The host selects all five published Support Desk packages at **0.2.12** and its +The host selects all five published Support Desk packages at **0.2.13** and its four direct Knowledge Base packages at **0.1.8**. The qualified -[Support 0.2.12 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.12) +[Support 0.2.13 release](https://github.com/pegma-dev/support-desk/releases/tag/v0.2.13) also uses exact KB **0.1.8** public contracts. The [public forwarding port](../worker/src/support-learning-ports.ts) preserves the actual KB error instances; the obsolete KB 0.1.2 constructor alias and translation @@ -31,7 +31,7 @@ Historically, Support **0.2.1** used nested KB **0.1.2** while this host selecte direct KB **0.1.5**. The exact `@pegma/knowledge-base-ai-compat` registry alias and recognized-error translation belonged to that earlier assembly. Its failed isolated production-layout diagnostic remains historical evidence; neither its -ordinary fixture passes nor that failure qualifies the current 0.2.12 graph. +ordinary fixture passes nor that failure qualifies the current 0.2.13 graph. The current [host policy](../worker/src/support-access.ts), `pegma.dev-policy-8`, grants four human learning permissions through the actual stored, audited @@ -329,7 +329,7 @@ cases, with zero errors in its Astro, Worker and recipe check. These historical counts overlap the assembly baseline. They predate the earlier 0.2.2 adoption and full-intent/commit-guard changes and do not qualify the current host source. The earlier public `0.2.5` [adoption checkpoint](KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint) -passed 1,125 tests locally and in CI. It does not qualify the current `0.2.12` +passed 1,125 tests locally and in CI. It does not qualify the current `0.2.13` graph. Current host validation, review and deployment acceptance remain pending. Relevant executable sources are the diff --git a/evals/assembly-eval.test.ts b/evals/assembly-eval.test.ts index d96713c..d350971 100644 --- a/evals/assembly-eval.test.ts +++ b/evals/assembly-eval.test.ts @@ -39,9 +39,9 @@ const EVAL_NPM: Record = { '@pegma/authorization-tokens': '0.4.0', '@pegma/authorization-identity': '0.4.0', '@pegma/audit': '0.2.0', - '@pegma/support-desk-contracts': '0.2.12', - '@pegma/support-desk-core': '0.2.12', - '@pegma/support-desk-application': '0.2.12', + '@pegma/support-desk-contracts': '0.2.13', + '@pegma/support-desk-core': '0.2.13', + '@pegma/support-desk-application': '0.2.13', '@pegma/support-desk-templates': '0.1.1', '@pegma/webhooks': '0.1.1', '@pegma/sessions': '0.3.0', diff --git a/package.json b/package.json index 9a108c8..1755d70 100644 --- a/package.json +++ b/package.json @@ -47,11 +47,11 @@ "@pegma/spine": "^0.1.1", "@pegma/storage-cloudflare-d1": "0.4.7", "@pegma/storage-core": "0.4.0", - "@pegma/support-desk-ai": "0.2.12", - "@pegma/support-desk-application": "0.2.12", - "@pegma/support-desk-contracts": "0.2.12", - "@pegma/support-desk-core": "0.2.12", - "@pegma/support-desk-templates": "0.2.12", + "@pegma/support-desk-ai": "0.2.13", + "@pegma/support-desk-application": "0.2.13", + "@pegma/support-desk-contracts": "0.2.13", + "@pegma/support-desk-core": "0.2.13", + "@pegma/support-desk-templates": "0.2.13", "@pegma/webhooks": "0.1.1", "agents": "^0.20.1", "gpt-tokenizer": "4.1.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a150190..f5e9f55 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -89,20 +89,20 @@ importers: specifier: 0.4.0 version: 0.4.0 '@pegma/support-desk-ai': - specifier: 0.2.12 - version: 0.2.12 + specifier: 0.2.13 + version: 0.2.13 '@pegma/support-desk-application': - specifier: 0.2.12 - version: 0.2.12 + specifier: 0.2.13 + version: 0.2.13 '@pegma/support-desk-contracts': - specifier: 0.2.12 - version: 0.2.12 + specifier: 0.2.13 + version: 0.2.13 '@pegma/support-desk-core': - specifier: 0.2.12 - version: 0.2.12 + specifier: 0.2.13 + version: 0.2.13 '@pegma/support-desk-templates': - specifier: 0.2.12 - version: 0.2.12 + specifier: 0.2.13 + version: 0.2.13 '@pegma/webhooks': specifier: 0.1.1 version: 0.1.1 @@ -1240,24 +1240,24 @@ packages: resolution: {integrity: sha512-aWbRhhis4Qs4TvH1Sb+OCI0a0ddOyV+6pm6HhPs+XPlaP86mTaV7OlwkIIPqk5Hw45t//tNaqfaggUeOc7rIGA==} engines: {node: '>=22'} - '@pegma/support-desk-ai@0.2.12': - resolution: {integrity: sha512-K9KoutI61ksMt8g2xn8aT3rOAXeNc8HLoFC8gdAzIjTm9k0RQ7KS4LgKvfwkw6++px/hOFlXZwRxaJ6ESJDbLA==} + '@pegma/support-desk-ai@0.2.13': + resolution: {integrity: sha512-XLZDWjUhY6QL5GYkudRGJW3Cv+Xnbm8BO1D6dmQoXbMF2SZ+DzwWBIOJgB5SzPr7S6n8D0UmERIe3cJxFQmOFw==} engines: {node: '>=22'} - '@pegma/support-desk-application@0.2.12': - resolution: {integrity: sha512-ag5K/dWM3Y7si6/+XvSYFMjqVwSlFTnnC3xAIOLDasTBntJCJJC3VyPX4wiI13SxhGArq8CxmOmHPM0PEBhD0w==} + '@pegma/support-desk-application@0.2.13': + resolution: {integrity: sha512-bmAxXdDufh9ppC/QupsMcf/9yKYXRUrBrRlxPfqd3OfGjVwteY+jMKsrD6kzvvjGOPPtP5uIC9d0KfYAQBAsVw==} engines: {node: '>=22'} - '@pegma/support-desk-contracts@0.2.12': - resolution: {integrity: sha512-RG/fKyCC7Wl4ev6xn3fdKMDQIvvjMfWNOuvJ1x/egqJ2JcAuJ8T33v7Ef/mSSIhogYttaBsELqqs3tIehbBckQ==} + '@pegma/support-desk-contracts@0.2.13': + resolution: {integrity: sha512-jDYNkshAJBcaZYjkOYnVpXAlgTm1cp8VEAWTu0xIDzXUKTv4kMPjSuGmTZXwJSMM6s/lQlKgEyEIRP+RfcrICw==} engines: {node: '>=22'} - '@pegma/support-desk-core@0.2.12': - resolution: {integrity: sha512-xAWASDcjux4heGV3WuJKEPf22FpkJ8A1nI4Xwh3+D2tI77wdvPktYk2addL5jzOXfeYP1Q8AH0F7RUyQ0uSLLQ==} + '@pegma/support-desk-core@0.2.13': + resolution: {integrity: sha512-uE99JUsXIcT+0sCjwvfUZ5t83VHbHdyfBG8brzDoawNP4nPzTX7LUXpi3gx39lEhdy0bW1R4MMDdqTXCiZsE8A==} engines: {node: '>=22'} - '@pegma/support-desk-templates@0.2.12': - resolution: {integrity: sha512-hTHbATrWofzR0RLV67fVJU5D41nsW/0F975VHT7PourArEMoM/QND4WCR+Ib7vE8vkr4oEUxMv8rZEO81N7PSQ==} + '@pegma/support-desk-templates@0.2.13': + resolution: {integrity: sha512-MfmT0jKqzK/D3k8UrXn0wZm9cQR9HbpxiMDyKhIv2fz7AUZPzmydIcXeWRxNQFfaQ/7sGILdaNX9CV8hu2IlLw==} engines: {node: '>=22'} '@pegma/webhooks@0.1.1': @@ -4245,35 +4245,35 @@ snapshots: '@pegma/storage-core@0.4.0': {} - '@pegma/support-desk-ai@0.2.12': + '@pegma/support-desk-ai@0.2.13': dependencies: '@pegma/authorization-core': 0.4.0 '@pegma/knowledge-base-application': 0.1.8 '@pegma/knowledge-base-contracts': 0.1.8 '@pegma/spine': 0.1.2 '@pegma/storage-core': 0.4.0 - '@pegma/support-desk-application': 0.2.12 + '@pegma/support-desk-application': 0.2.13 zod: 4.6.7 - '@pegma/support-desk-application@0.2.12': + '@pegma/support-desk-application@0.2.13': dependencies: '@pegma/audit': 0.2.0 '@pegma/authorization-core': 0.4.0 '@pegma/mail': 0.1.1 '@pegma/spine': 0.1.2 '@pegma/storage-core': 0.4.0 - '@pegma/support-desk-contracts': 0.2.12 - '@pegma/support-desk-core': 0.2.12 + '@pegma/support-desk-contracts': 0.2.13 + '@pegma/support-desk-core': 0.2.13 - '@pegma/support-desk-contracts@0.2.12': + '@pegma/support-desk-contracts@0.2.13': dependencies: '@pegma/spine': 0.1.2 - '@pegma/support-desk-core@0.2.12': + '@pegma/support-desk-core@0.2.13': dependencies: - '@pegma/support-desk-contracts': 0.2.12 + '@pegma/support-desk-contracts': 0.2.13 - '@pegma/support-desk-templates@0.2.12': {} + '@pegma/support-desk-templates@0.2.13': {} '@pegma/webhooks@0.1.1': dependencies: diff --git a/public/agent-access.js b/public/agent-access.js index ee85bb0..6d13af5 100644 --- a/public/agent-access.js +++ b/public/agent-access.js @@ -150,6 +150,10 @@ function parameter(name) { return values.length === 1 && values[0].length <= 128 ? values[0] : ''; } +function grantManagementPath(id) { + return `/account/agents/authorize?${new URLSearchParams({ grant_id: id })}`; +} + function setMutationPending(pending) { mutationPending = pending; for (const button of consentForm.querySelectorAll('button')) @@ -242,6 +246,19 @@ consentForm.addEventListener('submit', async (event) => { !(callback.protocol === 'http:' && loopback) ) throw new Error('invalid_request'); + if (decision === 'approve') { + // Retain only the public locator for Back/bookmark recovery. The owner + // lookup rechecks current access; the callback and its PKCE data stay unchanged. + try { + window.history.replaceState( + null, + '', + grantManagementPath(request.requestId), + ); + } catch { + // A history failure must not interrupt an already accepted callback. + } + } window.location.assign(callback.href); return; } @@ -292,6 +309,13 @@ async function loadGrant(id, acceptedConsent = false) { grantPanel.hidden = false; document.querySelector('#agent-grant-instructions').textContent = `Grant ID: ${grant.grantId}. Use this ID in the lookup form or choose Revoke this grant below. Status: ${grant.status}.`; + const managementLink = document.querySelector( + '#agent-grant-management-link', + ); + if (managementLink) { + managementLink.href = grantManagementPath(grant.grantId); + managementLink.hidden = false; + } setMutationPending(mutationPending); if (acceptedConsent) document.querySelector('#agent-approved-grant').hidden = true; @@ -358,6 +382,13 @@ async function start() { userCodeInput.value = parameter('user_code'); status('Enter or confirm the code shown by your agent.'); } else { + if (new URLSearchParams(window.location.search).has('grant_id')) { + const grantId = parameter('grant_id'); + if (!/^[A-Za-z0-9_-]{1,128}$/u.test(grantId)) + throw new Error('invalid_request'); + await loadGrant(grantId); + return; + } const requestId = parameter('request_id'); if (requestId) await loadApproval(new URLSearchParams({ request_id: requestId })); @@ -371,4 +402,25 @@ async function start() { } } +window.addEventListener('pageshow', (event) => { + if ( + !event.persisted || + flow !== 'authorization_code' || + !new URLSearchParams(window.location.search).has('grant_id') + ) + return; + // Back may restore this document without executing the module again. + ++loadGeneration; + ++grantGeneration; + csrfToken = ''; + approval = null; + currentGrant = null; + requestPanel.hidden = true; + grantPanel.hidden = true; + panel.hidden = true; + signedOut.hidden = true; + setMutationPending(mutationPending); + void start(); +}); + await start(); diff --git a/src/agent-access-ui.test.ts b/src/agent-access-ui.test.ts new file mode 100644 index 0000000..2cfd421 --- /dev/null +++ b/src/agent-access-ui.test.ts @@ -0,0 +1,406 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; +import { describe, expect, it, vi } from 'vitest'; +import { BrowserNode, documentFromTemplate } from './test-support-browser'; + +const locator = 'synthetic_owned_grant'; +const resource = 'https://pegma.dev/api/knowledge/mcp'; +const managementPath = `/account/agents/authorize?grant_id=${locator}`; +const approval = { + flow: 'authorization_code', + requestId: locator, + status: 'pending', + clientId: 'synthetic-client', + clientName: 'Synthetic hosted client', + resource, + requestedScopes: [ + { name: 'knowledge.draft.read', description: 'Read drafts' }, + ], + expiresAt: '2026-11-14T16:10:00.000Z', +}; +const grant = { + grantId: locator, + clientId: approval.clientId, + resource, + scopes: approval.requestedScopes, + status: 'active', + createdAt: '2026-11-14T16:00:00.000Z', + expiresAt: '2026-11-21T16:00:00.000Z', +}; + +/** A navigation stack, rather than a replaceState spy: Back reopens its URL. */ +function navigation(initial: string, failHistory = false) { + const entries = [new URL(initial, 'https://pegma.dev').href]; + const events: { kind: string; url: string; state?: unknown }[] = []; + let index = 0; + return { + entries, + events, + location: { + get href() { + return entries[index] ?? ''; + }, + get pathname() { + return new URL(this.href).pathname; + }, + get search() { + return new URL(this.href).search; + }, + assign(url: string) { + events.push({ kind: 'assign', url }); + entries.splice( + index + 1, + entries.length, + new URL(url, this.href).href, + ); + ++index; + }, + }, + history: { + replaceState(state: unknown, _unused: string, url: string) { + if (failHistory) throw new Error('Synthetic unavailable history'); + const target = new URL(url, entries[index]); + if (target.origin !== 'https://pegma.dev') + throw new Error('Cross-origin history'); + entries[index] = target.href; + events.push({ kind: 'replace', url: target.href, state }); + }, + back() { + if (index > 0) --index; + }, + }, + }; +} + +interface Call { + readonly path: string; + readonly method: string; + readonly body?: string; + readonly init: RequestInit; +} + +async function browser( + nav: ReturnType, + respond: (call: Call) => Response | Promise, +) { + const document = documentFromTemplate( + readFileSync( + new URL('./pages/account/agents/authorize.astro', import.meta.url), + 'utf8', + ), + ); + const query = document.querySelector.bind(document); + document.querySelector = (selector: string) => + selector === '[data-agent-flow]' + ? (document + .all() + .find((node) => node.dataset.agentFlow !== undefined) ?? null) + : query(selector); + // BrowserNode intentionally models only the DOM subset needed by host tests. + document.createElement = (tag: string) => { + const node = new BrowserNode(tag); + for (const key of ['id', 'name']) + Object.defineProperty(node, key, { + get: () => node.attributes.get(key) ?? '', + set: (value: string) => node.attributes.set(key, value), + }); + return node; + }; + const calls: Call[] = []; + const storage = new Proxy( + {}, + { + get() { + throw new Error('Unexpected browser storage'); + }, + }, + ); + const window = Object.assign(new EventTarget(), { + ...nav, + confirm: () => true, + localStorage: storage, + sessionStorage: storage, + }); + await runInNewContext( + `(async () => {${readFileSync( + new URL('../public/agent-access.js', import.meta.url), + 'utf8', + )}\n})()`, + { + document, + window, + localStorage: storage, + sessionStorage: storage, + URL, + URLSearchParams, + Headers, + Date, + fetch: async (path: string, init: RequestInit = {}) => { + if (init.body !== undefined && typeof init.body !== 'string') + throw new Error('Unexpected request body'); + const call = { + path, + method: init.method ?? 'GET', + body: init.body, + init, + }; + calls.push(call); + return respond(call); + }, + }, + ); + function node(id: string) { + const found = document.querySelector(`#${id}`); + if (found === null) throw new Error(`Missing page element: ${id}`); + return found; + } + function submit(decision = 'approve') { + const event = new Event('submit', { cancelable: true }); + Object.defineProperty(event, 'submitter', { + value: { value: decision }, + }); + node('agent-consent').dispatchEvent(event); + } + function restore() { + const event = new Event('pageshow'); + Object.defineProperty(event, 'persisted', { value: true }); + window.dispatchEvent(event); + } + return { calls, node, submit, restore }; +} + +function json(value: unknown, status = 200) { + return new Response(JSON.stringify(value), { status }); +} +const state = { csrfToken: 'synthetic-csrf', resource }; + +describe('Agent Access hosted-PKCE management recovery', () => { + it.each([ + 'https://client.example.test/callback?existing=keep&code=synthetic-code&iss=https%3A%2F%2Fpegma.dev&state=exact%2F%2B%25', + 'http://127.0.0.1:54983/callback?code=synthetic-code&iss=https%3A%2F%2Fpegma.dev&state=exact%2F%2B%25', + ])( + 'retains a locator-only Back entry before the unchanged callback %s', + async (callback) => { + const nav = navigation( + `/account/agents/authorize?request_id=${locator}&state=not-retained`, + ); + const first = await browser(nav, ({ path, method }) => { + if (path === '/api/agent-access/state') return json(state); + if (path === `/api/agent-access/approval?request_id=${locator}`) + return json(approval); + if (path === '/api/agent-access/approval' && method === 'POST') + return json({ + flow: 'authorization_code', + redirectUri: callback, + }); + throw new Error(`Unexpected approval request: ${method} ${path}`); + }); + first.submit(); + await vi.waitFor(() => expect(nav.events).toHaveLength(2)); + expect(nav.events).toEqual([ + { + kind: 'replace', + url: `https://pegma.dev${managementPath}`, + state: null, + }, + { kind: 'assign', url: callback }, + ]); + expect(first.calls.map(({ path }) => path)).toEqual([ + '/api/agent-access/state', + `/api/agent-access/approval?request_id=${locator}`, + '/api/agent-access/approval', + ]); + expect(JSON.parse(first.calls[2]?.body ?? '')).toEqual({ + requestId: locator, + decision: 'approve', + approvedScopes: ['knowledge.draft.read'], + }); + expect( + new Headers(first.calls[2]?.init.headers).get('X-Pegma-CSRF'), + ).toBe(state.csrfToken); + expect(first.calls[2]?.init).toMatchObject({ + credentials: 'same-origin', + cache: 'no-store', + referrerPolicy: 'no-referrer', + }); + nav.history.back(); + expect(nav.location.href).toBe(`https://pegma.dev${managementPath}`); + // The pending approval is now expired; its endpoint must never be used. + const returned = await browser(nav, ({ path }) => { + if (path === '/api/agent-access/state') return json(state); + if (path === `/api/agent-access/grants/${locator}`) + return json(grant); + if (path.startsWith('/api/agent-access/approval')) + return json({ error: 'expired_token' }, 400); + throw new Error(`Unexpected return lookup: ${path}`); + }); + expect(returned.calls.map(({ path }) => path)).toEqual([ + '/api/agent-access/state', + `/api/agent-access/grants/${locator}`, + ]); + expect(returned.node('agent-grant').hidden).toBe(false); + expect(returned.node('agent-grant-details').textContent).toContain( + locator, + ); + expect(returned.node('agent-grant-management-link').href).toBe( + managementPath, + ); + expect(returned.node('agent-revoke').disabled).toBe(false); + }, + ); + + it.each(['owner', 'different-owner'])( + 'refreshes the same retained document after Back with %s access', + async (actor) => { + const nav = navigation( + `/account/agents/authorize?request_id=${locator}`, + ); + const callback = + 'https://client.example.test/callback?code=synthetic-code&state=exact'; + let returning = false; + let restoreStatePending = true; + let finishState = (_response: Response) => {}; + const pendingState = new Promise((resolve) => { + finishState = resolve; + }); + const b = await browser(nav, ({ path, method }) => { + if (path === '/api/agent-access/state') { + if (returning && restoreStatePending) { + restoreStatePending = false; + return pendingState; + } + return json(state); + } + if (returning) { + if (path !== `/api/agent-access/grants/${locator}`) + throw new Error( + 'Restoration must not reuse the expired approval.', + ); + return actor === 'owner' + ? json({ ...grant, status: 'revoked' }) + : json({ error: 'access_denied' }, 403); + } + if (method === 'GET') return json(approval); + return json({ flow: 'authorization_code', redirectUri: callback }); + }); + b.submit(); + await vi.waitFor(() => expect(nav.events).toHaveLength(2)); + nav.history.back(); + returning = true; + b.restore(); + expect(b.node('agent-panel').hidden).toBe(true); + expect(b.node('agent-request').hidden).toBe(true); + expect(b.node('agent-grant').hidden).toBe(true); + expect(nav.location.href).toBe(`https://pegma.dev${managementPath}`); + finishState(json(state)); + if (actor === 'owner') { + await vi.waitFor(() => + expect(b.node('agent-status').textContent).toBe('Grant loaded.'), + ); + expect(b.node('agent-grant-details').textContent).toContain( + 'revoked', + ); + expect(b.node('agent-revoke').disabled).toBe(true); + } else { + await vi.waitFor(() => + expect(b.node('agent-status').textContent).toContain( + 'not available to this account', + ), + ); + expect(b.node('agent-grant').hidden).toBe(true); + } + expect( + b.calls.filter(({ method }) => method === 'POST'), + ).toHaveLength(1); + expect( + b.calls.filter(({ path }) => + path.startsWith('/api/agent-access/approval?'), + ), + ).toHaveLength(1); + expect( + b.calls.filter( + ({ path }) => path === `/api/agent-access/grants/${locator}`, + ), + ).toHaveLength(1); + expect(nav.events).toHaveLength(2); + }, + ); + + it.each(['active', 'revoked', 'expired'])( + 'renders the current owner GrantView status %s from a bookmark', + async (status) => { + const b = await browser(navigation(managementPath), ({ path }) => + path === '/api/agent-access/state' + ? json(state) + : json({ ...grant, status }), + ); + expect(b.node('agent-grant-details').textContent).toContain(status); + expect(b.node('agent-revoke').disabled).toBe(status === 'revoked'); + expect(b.calls).toHaveLength(2); + }, + ); + + it('does not expose a foreign grant or turn its locator into owner authority', async () => { + const b = await browser(navigation(managementPath), ({ path }) => + path === '/api/agent-access/state' + ? json(state) + : json({ error: 'access_denied' }, 403), + ); + expect(b.node('agent-grant').hidden).toBe(true); + expect(b.node('agent-grant-details').textContent).toBe(''); + expect(b.node('agent-grant-management-link').hidden).toBe(true); + expect(b.node('agent-status').textContent).toContain( + 'not available to this account', + ); + expect(b.calls.map(({ method }) => method)).toEqual([ + 'GET', + 'GET', + 'GET', + ]); + }); + + it.each(['grant_id=', 'grant_id=one&grant_id=two', 'grant_id=bad%2Fid'])( + 'refuses an invalid or ambiguous management locator: %s', + async (query) => { + const b = await browser( + navigation( + `/account/agents/authorize?${query}&request_id=${locator}`, + ), + () => json(state), + ); + expect(b.calls).toHaveLength(1); + expect(b.node('agent-status').textContent).toContain( + 'Check the request', + ); + }, + ); + + it.each(['deny', 'failed-approval', 'unavailable-history'])( + 'preserves callback/error behavior for %s', + async (mode) => { + const callback = `https://client.example.test/callback?${mode === 'deny' ? 'error=access_denied' : 'code=synthetic-code'}&state=exact`; + const nav = navigation( + `/account/agents/authorize?request_id=${locator}`, + mode === 'unavailable-history', + ); + const b = await browser(nav, ({ path, method }) => { + if (path === '/api/agent-access/state') return json(state); + if (method === 'GET') return json(approval); + return mode === 'failed-approval' + ? json({ error: 'expired_token' }, 400) + : json({ flow: 'authorization_code', redirectUri: callback }); + }); + b.submit(mode === 'deny' ? 'deny' : 'approve'); + if (mode === 'failed-approval') { + await vi.waitFor(() => + expect(b.node('agent-status').dataset.tone).toBe('error'), + ); + expect(nav.events).toEqual([]); + } else { + await vi.waitFor(() => + expect(nav.events).toEqual([{ kind: 'assign', url: callback }]), + ); + } + }, + ); +}); diff --git a/src/data/components.ts b/src/data/components.ts index 39afaca..c2c1deb 100644 --- a/src/data/components.ts +++ b/src/data/components.ts @@ -199,7 +199,7 @@ export const components: readonly PegmaComponent[] = [ 'Being a hosted SaaS — hosts run it, own its data, and choose its providers', 'AI processing before the host documents what may leave its boundary', ], - now: 'The 0.2.12 package set is published on npm and composed by the Cloudflare reference host; optional AI routes remain host-controlled.', + now: 'Exact published package versions are compiled from npm; optional AI routes remain host-controlled.', plan: 'docs/PROJECT_PLAN.md', }, { diff --git a/src/data/recipe-backlog.ts b/src/data/recipe-backlog.ts index bb967ba..fa40e53 100644 --- a/src/data/recipe-backlog.ts +++ b/src/data/recipe-backlog.ts @@ -247,9 +247,9 @@ export const RECIPE_BACKLOG: readonly CatalogRecipe[] = [ '@pegma/mail@0.1.1', '@pegma/rate-limit@0.2.0', '@pegma/health@0.2.0', - '@pegma/support-desk-application@0.2.12', - '@pegma/support-desk-contracts@0.2.12', - '@pegma/support-desk-core@0.2.12', + '@pegma/support-desk-application@0.2.13', + '@pegma/support-desk-contracts@0.2.13', + '@pegma/support-desk-core@0.2.13', '@pegma/authorization-core@0.4.0', '@pegma/storage-core@0.4.0', '@pegma/spine@0.1.1', diff --git a/src/pages/account/agents/authorize.astro b/src/pages/account/agents/authorize.astro index 4fe48d8..641a05d 100644 --- a/src/pages/account/agents/authorize.astro +++ b/src/pages/account/agents/authorize.astro @@ -34,7 +34,7 @@ import Base from '../../../layouts/Base.astro';

View or revoke a known grant

-

Enter the grant ID from your approval. Only your own grants are available here.

+

Enter the grant ID from your approval. Only your own grants are available here. After approval redirects to your agent, use your browser's Back button to return to these controls, then bookmark the grant link.

diff --git a/src/test-support-browser.ts b/src/test-support-browser.ts index 5c10890..9eedf3b 100644 --- a/src/test-support-browser.ts +++ b/src/test-support-browser.ts @@ -79,7 +79,7 @@ export class BrowserNode extends EventTarget { } } -function documentFromTemplate(template: string) { +export function documentFromTemplate(template: string) { const root = new BrowserNode('document'); const stack = [root]; const voidTags = new Set(['input', 'img', 'link', 'meta', 'br', 'hr']); diff --git a/worker/README.md b/worker/README.md index f27c035..ab64887 100644 --- a/worker/README.md +++ b/worker/README.md @@ -248,7 +248,7 @@ public acknowledgement endpoint. ## Support Desk composition -Authenticated product feedback composes exact `0.2.12` versions of +Authenticated product feedback composes exact `0.2.13` versions of `@pegma/support-desk-contracts`, `@pegma/support-desk-core`, `@pegma/support-desk-application`, and `@pegma/support-desk-templates` over the same `IDENTITY_DB` D1 binding. Support Desk collections @@ -259,7 +259,7 @@ via AccessContext defaults (not a paid entitlement). Categories: `feedback`, `bug`, `feature_request`, `documentation`, `question`. Subject marker: `[PEG-…]`. Tracking pages: `/feedback` and `/feedback/ticket/?id=…`. -The optional `@pegma/support-desk-ai@0.2.12` package is installed for the +The optional `@pegma/support-desk-ai@0.2.13` package is installed for the [isolated scripted answering stage](../docs/SUPPORT_ASSISTANT_STAGE.md). The earlier public `0.2.5` graph passed the 1,125-test local/CI [adoption checkpoint](../docs/KNOWLEDGE_COMPOSITION.md#public-025-adoption-checkpoint); diff --git a/worker/src/agent-access-runtime.test.ts b/worker/src/agent-access-runtime.test.ts index db4cd2e..1685bf0 100644 --- a/worker/src/agent-access-runtime.test.ts +++ b/worker/src/agent-access-runtime.test.ts @@ -5,6 +5,7 @@ import { createRoleStore } from '@pegma/authorization-storage'; import { identityLinkKeyFromVerifiedIdentityClaims } from '@pegma/authorization-identity'; import { hasPermission } from '@pegma/authorization-core'; import type { PublicClient } from '@pegma/agent-access'; +import type { Clock } from '@pegma/spine'; import type { IdentityPort, IdentityUser, @@ -53,7 +54,7 @@ function text(value: Record, key: string): string { return field; } -async function fixture() { +async function fixture(clock?: Clock) { const store = createMemoryStore(); const logger = { log: vi.fn() }; const sessions = createSessionStore(store, { logger }); @@ -142,6 +143,7 @@ async function fixture() { logger, identityLinkFromClaims: identityLinkKeyFromVerifiedIdentityClaims, clients: [client], + ...(clock === undefined ? {} : { clock }), }; const candidateRuntime = createAgentAccessRuntime(options); if (candidateRuntime === null) @@ -210,7 +212,139 @@ async function fixture() { }; } +async function approvedAuthorization( + f: Awaited>, +) { + const verifier = 'v'.repeat(64); + const challenge = Buffer.from( + await crypto.subtle.digest( + 'SHA-256', + new TextEncoder().encode(verifier), + ), + ).toString('base64url'); + const redirectUri = client.redirectUris[0] ?? ''; + const authorize = await f.runtime.protocol.handle( + f.request( + `/api/agent-access/authorize?${new URLSearchParams({ + response_type: 'code', + client_id: client.clientId, + redirect_uri: redirectUri, + resource: AGENT_RESOURCE, + scope: AGENT_KNOWLEDGE_PERMISSIONS[0] ?? '', + code_challenge: challenge, + code_challenge_method: 'S256', + state: 'exact/+% state', + })}`, + ), + ); + expect(authorize?.status).toBe(303); + const approvalUrl = new URL(authorize?.headers.get('Location') ?? ''); + const requestId = approvalUrl.searchParams.get('request_id'); + if (requestId === null) + throw new Error('Expected a PKCE request locator.'); + const approvalPath = `/api/agent-access/approval?request_id=${requestId}`; + expect( + await body(await f.runtime.api(f.request(approvalPath))), + ).toMatchObject({ + requestId, + flow: 'authorization_code', + status: 'pending', + }); + const result = await body( + await f.runtime.api( + f.request('/api/agent-access/approval', 'admin', { + method: 'POST', + body: JSON.stringify({ + requestId, + decision: 'approve', + approvedScopes: [AGENT_KNOWLEDGE_PERMISSIONS[0]], + }), + }), + ), + ); + expect(result.flow).toBe('authorization_code'); + const callback = new URL(text(result, 'redirectUri')); + expect(callback.origin + callback.pathname).toBe(redirectUri); + expect(callback.searchParams.get('state')).toBe('exact/+% state'); + expect(callback.searchParams.get('iss')).toBe(IDENTITY_ISSUER); + const code = callback.searchParams.get('code'); + if (code === null) + throw new Error('Expected a real authorization code.'); + const tokens = await f.runtime.service.exchangeAuthorizationCode({ + clientId: client.clientId, + resource: AGENT_RESOURCE, + code, + redirectUri, + codeVerifier: verifier, + }); + return { requestId, approvalPath, tokens }; +} + describe('Agent Access host composition', () => { + it('recovers the actual PKCE grant by its request locator after the approval request expires', async () => { + let now = Date.now(); + const f = await fixture({ now: () => new Date(now).toISOString() }); + const { requestId, approvalPath, tokens } = + await approvedAuthorization(f); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).resolves.toMatchObject({ grantId: requestId }); + now += 601_000; + const expired = await f.runtime.api(f.request(approvalPath)); + expect(expired?.status).toBe(400); + expect(await body(expired)).toMatchObject({ error: 'expired_token' }); + const current = await f.runtime.api( + f.request(`/api/agent-access/grants/${requestId}`), + ); + expect(current?.status).toBe(200); + expect(await body(current)).toMatchObject({ + grantId: requestId, + status: 'active', + clientId: client.clientId, + resource: AGENT_RESOURCE, + ownerId: 'admin', + }); + expect(current?.headers.get('Cache-Control')).toContain('no-store'); + }); + + it('denies a different Admin the real PKCE grant locator and preserves owner revocation', async () => { + const f = await fixture(); + const { requestId, tokens } = await approvedAuthorization(f); + const path = `/api/agent-access/grants/${requestId}`; + for (const method of ['GET', 'DELETE']) { + const denied = await f.runtime.api( + f.request(path, 'other-admin', { method }), + ); + expect(denied?.status).toBe(403); + expect(await body(denied)).not.toHaveProperty('grantId'); + } + expect(await body(await f.runtime.api(f.request(path)))).toMatchObject( + { + grantId: requestId, + status: 'active', + }, + ); + expect( + (await f.runtime.api(f.request(path, 'admin', { method: 'DELETE' }))) + ?.status, + ).toBe(204); + expect(await body(await f.runtime.api(f.request(path)))).toMatchObject( + { + grantId: requestId, + status: 'revoked', + }, + ); + await expect( + f.runtime.service.authenticate({ + token: tokens.access_token, + resource: AGENT_RESOURCE, + }), + ).rejects.toThrow(); + }); + it('applies an explicit resource budget using the existing durable limiter', async () => { const f = await fixture(); const runtime = createAgentAccessRuntime({ diff --git a/worker/src/index.ts b/worker/src/index.ts index 494ccd9..27fa212 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -978,7 +978,7 @@ return { probe: 'disabled' | 'ok' | 'fail'; } = { storage: 'cloudflare-d1', - packages: '@pegma/support-desk-application@0.2.12', + packages: '@pegma/support-desk-application@0.2.13', probe: 'disabled', }; if (supportHealthProbeEnabled(env)) { diff --git a/worker/src/knowledge-query-budget.d1.test.ts b/worker/src/knowledge-query-budget.d1.test.ts index 6e5a1d7..63d9e90 100644 --- a/worker/src/knowledge-query-budget.d1.test.ts +++ b/worker/src/knowledge-query-budget.d1.test.ts @@ -1313,6 +1313,8 @@ describe('real production KB request budgets over actual D1', () => { }, ); + // This real-backend walkthrough spans many separate invocations, including + // history setup. Its aggregate wall-time allowance is not a Workers CPU budget. it('profiles both protocols and the full staff/portal lifecycle over one genuine32-proof high-history D1 article', async () => { const f = await fixture(true); let sequence = 0; @@ -1809,5 +1811,5 @@ describe('real production KB request budgets over actual D1', () => { } finally { f.meter.assertFreeBudget(); } - }, 180_000); + }, 300_000); }); diff --git a/worker/src/support-paid-checker-group.test.ts b/worker/src/support-paid-checker-group.test.ts index 0670b19..b6d275a 100644 --- a/worker/src/support-paid-checker-group.test.ts +++ b/worker/src/support-paid-checker-group.test.ts @@ -586,9 +586,9 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { }, ); - it("retains the actual SDK follow-up purpose hold while its generator remains legacy", async () => { - // A ready legacy control rules out missing keys/purpose evidence as the - // reason that the otherwise qualified group counterpart is held. + it("admits qualified SDK follow-up group checks while its generator remains legacy", async () => { + // Public 0.2.13 permits the explicit group for checks with its own current + // SD05 proof. Generation and credential-free policy reads stay unchanged. for (const group of [false, true]) { const f = await supportFollowupPaidFixture(); if (group) await selectGroupChecks(f.profile.checks); @@ -634,8 +634,32 @@ describe("normal paid bootstrap checker-only GPT-5.4 capability", () => { "pegma.dev", ); expect((await checks.resolvePolicy(undefined, signal())).outcome).toBe( - group ? "unavailable" : "ready", + "ready", ); + if (group) { + const { releaseFollowup: _purpose, approval, ...unsigned } = + f.profile.checks.route; + const withoutPurpose = { + ...unsigned, + approval: { + ...approval, + requestPolicySha256: await independentCheckRoutePolicyHash(unsigned), + }, + }; + const unqualified = createSupportReleaseFollowupChecks( + { + ...paid.checks, + readRoute: () => withoutPurpose, + store: createMemoryStore(), + application, + releaseEvidence: { verifyInput: evidence, confirm: evidence }, + }, + "pegma.dev", + ); + expect( + (await unqualified.resolvePolicy(undefined, signal())).outcome, + ).toBe("unavailable"); + } expect(application).not.toHaveBeenCalled(); expect(evidence).not.toHaveBeenCalled(); expect(providerKey).not.toHaveBeenCalled();