diff --git a/CLAUDE.md b/CLAUDE.md index b9e89c95..688236af 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1886,6 +1886,42 @@ silently — `loadStepUpApprover` refuses it); letting `attestApprover` sign a what the human saw". `core/tests/store.step-up-approver.mjs` and `extension/tests/approver-policy.test.mts` pin these. +## A step-up link: the community's request, the person's answer (VTI-LNK-125 – 131) + +Someone acting for the person with a key they delegated — their assistant over +`vtc-mcp`, say — can redeem a VTC step-up but never make one. The community +refuses it with a single-use handle beside the inline request, and the +assistant shows the person a `step-up` link. The person pastes it into the +popup (`OpenStepUpLink`, `RUNTIME_STEP_UP_LINK`, extension pages only) or +clicks it on a page (`handleTriggerLink` routes `step-up` away from the +sign-in window). `background.ts::runStepUpLink` drives it: + +1. `OFFSCREEN_STEP_UP_FLOW` `read` (`step-up-flows.ts`): only a community the + wallet holds a `didSelfIssued` identity at (`isEntryFor`), or nothing is + sent (`not-in-records`); its DID document resolved and verified; + `auth/step-up/requests/show/0.1` from a fresh key with the handle + (`core/vtc/step-up-handoff.ts`); the returned `request` must be an + approve-request the community signed, to its subject, unexpired, and bound + to the returned operation (`binding-mismatch`); the subject must be one of + the wallet's identities there (`not-the-subject`). `notFound` is + `step-up-gone` (outcome `expired`). +2. The same `check-step-up`, approver prompt (`via: { kind: "link" }`: the + identity from the wallet's own record, the reason labelled as signed by the + community) and `sign-step-up` as `approveStepUp`. There is no page and no + origin pin: the audience is the community the read came from. +3. `answer`: the approve-response, signed by the agent as the subject + (`signTaskAsEntry`, purpose from `proofPurposeForDocumentType`), posted to + the community. Never back to whoever made the link. + +The outcome is a notification, since the popup closes when the prompt opens. + +**What breaks it:** showing anything from the link or the link's producer as +what is being approved; reading a step-up for a community not in the records; +skipping the binding recompute; answering through anything but the +community's own endpoint; or letting a page send `RUNTIME_STEP_UP_LINK`. +`core/tests/vtc.step-up-handoff.mjs` and `extension/tests/step-up-flows.test.mts` +pin these. + ## Repo mechanics worth knowing before you start - **Task modules are generated here, from `packages/core/trust-tasks.lock`.** diff --git a/packages/core/src/links/trigger-link.ts b/packages/core/src/links/trigger-link.ts index b591ea97..4e8fc552 100644 --- a/packages/core/src/links/trigger-link.ts +++ b/packages/core/src/links/trigger-link.ts @@ -58,7 +58,16 @@ export type TriggerLinkReason = | "domain-not-linked" // Local to this reader, outcome `invalid`: the community's verified document // lists no usable `SignInPortal` service (VTI-LNK-102 names no reason). - | "no-portal-service"; + | "no-portal-service" + // `step-up` (VTI-LNK-128 – 130), outcome `invalid`: the contact is not a + // service in the reader's records; its step-up names a subject the reader + // holds no identity for there; or its binding is not the operation's. + | "not-in-records" + | "not-the-subject" + | "binding-mismatch" + // `step-up` (VTI-LNK-129), outcome `expired`: the community answered the + // handle `notFound` — spent, expired, or its step-up already settled. + | "step-up-gone"; /** What the person can do about it (VTI-LNK-021). */ export type TriggerLinkOutcome = "update" | "expired" | "unreachable" | "pass-on" | "invalid"; @@ -72,6 +81,7 @@ export function outcomeOf(reason: TriggerLinkReason): TriggerLinkOutcome { case "unsupported-version": return "update"; case "expired": + case "step-up-gone": return "expired"; case "no-common-transport": return "unreachable"; @@ -384,11 +394,29 @@ export const SIGN_IN_FLOW: TriggerLinkFlowSpec = { allowsContact: isServiceContact, }; +/** + * `step-up` 0.1, draft (VTI-LNK-125 to 131). The contact is the service that + * refused an operation, and the reader acts only for one already in its own + * records (VTI-LNK-128): the contact rule does not apply, because the service + * qualified when the person added it. So every contact parses, and one that is + * not in the records — a `did:key` among them — is `not-in-records` once the + * flow looks, before anything is sent. + */ +export const STEP_UP_FLOW: TriggerLinkFlowSpec = { + name: "step-up", + base: `${FLOW_REGISTRY_BASE}step-up`, + major: 0, + minors: [1], + draft: true, + requiresExp: true, + allowsContact: () => true, +}; + /** The flows this plugin implements, as a reader. `vta-claim` is deliberately * absent: this wallet does not claim VTAs from a Farm, so such a link is * `unknown-flow` (outcome `update`). A reader that adds it uses * {@link isServiceContact} as its `allowsContact` (VTI-LNK-112). */ -export const READER_FLOWS: readonly TriggerLinkFlowSpec[] = [SIGN_IN_FLOW]; +export const READER_FLOWS: readonly TriggerLinkFlowSpec[] = [SIGN_IN_FLOW, STEP_UP_FLOW]; // ── Results ────────────────────────────────────────────────────────────────── diff --git a/packages/core/src/specs/auth/step-up/requests/show/0.1/payload.ts b/packages/core/src/specs/auth/step-up/requests/show/0.1/payload.ts new file mode 100644 index 00000000..5008e271 --- /dev/null +++ b/packages/core/src/specs/auth/step-up/requests/show/0.1/payload.ts @@ -0,0 +1,317 @@ +/** + * Generated by trust-tasks-gen-ts (@openvtc/trust-tasks-gen) — DO NOT EDIT BY HAND. + * Source: https://trusttasks.org/spec/auth/step-up/requests/show/0.1 (registry bundle) + */ + +import type { Ext } from "../../../../../_shared/components.js"; + + +/** + * A single-use reference to one pending step-up, minted by the relying party with at least 128 bits of entropy and carried as base64url without padding. It names the request; it is not the request's challenge, and knowing it authorizes nothing but this one read. + */ +export type Handle = string; + +/** + * The approver's agent asks the relying party for a pending step-up bound to one operation, named by the hand-off handle the relying party gave the operation's producer. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3. + */ +export interface AuthStepUpRequestShowPayload { + handle: Handle; + ext?: Ext; +} +/** + * The pending step-up and the operation it is bound to. Failures use trust-task-error, not this shape. + */ +export interface AuthStepUpRequestShowResponsePayload { + /** + * A complete auth/step-up/approve-request/0.5 Trust Task document, issued and signed by the relying party, whose recipient is the step-up's subject and whose payload is the request the operation's producer received inline — the same challenge, boundTo, accepts and approvers. The agent verifies it as a document in its own right — envelope, proof and payload against that specification's schema — over the members exactly as received: its proof covers every member, so it is deliberately an open object here rather than a typed one a binding could narrow. + */ + request: {}; + operation: Operation; + ext?: Ext; +} +/** + * The operation the step-up is bound to, exactly as the relying party received it. + */ +export interface Operation { + /** + * The operation's Type URI, as the document the relying party refused named it. + */ + type: string; + /** + * The operation's payload, member for member as received, so that the approver's agent can show it and — where it knows how the relying party derives `boundTo` — recompute the binding. + */ + payload: {}; +} + +/** Shared definitions this specification references, re-exported under the names it used to declare them with. */ +export type { Ext }; + +/** Trust Task type URI. */ +export const TYPE_URI = "https://trusttasks.org/spec/auth/step-up/requests/show/0.1" as const; + +/** + * The earlier version of this specification that this one declares it + * extends (front matter `extends`, SPEC §5.2 "Declared extension"), or + * `null`. Only the direct declaration — follow the chain with + * `extendsChain` / `readForSpec`. + */ +export const EXTENDS: string | null = null; + +/** + * Why this version is deprecated, or `null` while it is current. A + * superseded or retired version is still supported, and is withdrawn from + * this package in a later scheduled batch (SPEC "Superseded and Withdrawn + * Versions"). + */ +export const DEPRECATION: string | null = null; + +/** Stable alias for this specification's request payload shape. */ +export type Payload = AuthStepUpRequestShowPayload; + +/** Trust Task response type URI (request type URI + "#response"). */ +export const RESPONSE_TYPE_URI = "https://trusttasks.org/spec/auth/step-up/requests/show/0.1#response" as const; + +/** Stable alias for this specification's success-response payload shape. */ +export type Response = AuthStepUpRequestShowResponsePayload; + +/** + * This specification's payload schema, as a value. + * + * SPEC.md §7.2 item 2 is performed against this. It is shipped as data + * rather than only as a `.json` file because TypeScript types are erased + * at runtime: without a schema a consumer has nothing to validate, and + * every REQUIRED payload member is optional in practice. Cross-file + * `$ref`s are already inlined, so it needs no resolver. + */ +export const PAYLOAD_SCHEMA = { + "$defs": { + "Handle": { + "description": "A single-use reference to one pending step-up, minted by the relying party with at least 128 bits of entropy and carried as base64url without padding. It names the request; it is not the request's challenge, and knowing it authorizes nothing but this one read.", + "pattern": "^[A-Za-z0-9_-]{22,86}$", + "title": "Handle", + "type": "string" + }, + "Handoff": { + "additionalProperties": false, + "description": "What a relying party MAY carry as `details.stepUpHandoff` beside an inline `details.stepUpRequest` (auth/step-up/approve-request/0.5, Inline delivery), so that a producer which cannot obtain the evidence itself can hand the step-up to the subject's approver agent. Not a payload of this task: defined here so producers and consumers share one shape.", + "properties": { + "handle": { + "$ref": "#/$defs/Handle" + }, + "expiresAt": { + "description": "The instant after which the relying party answers the handle with `notFound`: no later than the pending step-up's own expiry.", + "format": "date-time", + "type": "string" + }, + "show": { + "const": "https://trusttasks.org/spec/auth/step-up/requests/show/0.1", + "description": "The Type URI the approver's agent sends with the handle.", + "type": "string" + } + }, + "required": [ + "handle", + "expiresAt", + "show" + ], + "title": "Handoff", + "type": "object" + }, + "Operation": { + "additionalProperties": false, + "description": "The operation the step-up is bound to, exactly as the relying party received it.", + "properties": { + "type": { + "description": "The operation's Type URI, as the document the relying party refused named it.", + "maxLength": 2048, + "minLength": 1, + "type": "string" + }, + "payload": { + "description": "The operation's payload, member for member as received, so that the approver's agent can show it and — where it knows how the relying party derives `boundTo` — recompute the binding.", + "type": "object" + } + }, + "required": [ + "type", + "payload" + ], + "title": "Operation", + "type": "object" + }, + "Response": { + "$anchor": "response", + "additionalProperties": false, + "description": "The pending step-up and the operation it is bound to. Failures use trust-task-error, not this shape.", + "properties": { + "request": { + "description": "A complete auth/step-up/approve-request/0.5 Trust Task document, issued and signed by the relying party, whose recipient is the step-up's subject and whose payload is the request the operation's producer received inline — the same challenge, boundTo, accepts and approvers. The agent verifies it as a document in its own right — envelope, proof and payload against that specification's schema — over the members exactly as received: its proof covers every member, so it is deliberately an open object here rather than a typed one a binding could narrow.", + "type": "object" + }, + "operation": { + "$ref": "#/$defs/Operation" + }, + "ext": { + "$ref": "#/$defs/Ext" + } + }, + "required": [ + "request", + "operation" + ], + "title": "Auth — Step-up Request Show — response payload", + "type": "object" + }, + "Ext": { + "additionalProperties": true, + "description": "Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.", + "minProperties": 1, + "propertyNames": { + "pattern": "^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$" + }, + "title": "Ext", + "type": "object" + } + }, + "$id": "https://trusttasks.org/spec/auth/step-up/requests/show/0.1", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "description": "The approver's agent asks the relying party for a pending step-up bound to one operation, named by the hand-off handle the relying party gave the operation's producer. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.", + "properties": { + "handle": { + "$ref": "#/$defs/Handle" + }, + "ext": { + "$ref": "#/$defs/Ext" + } + }, + "required": [ + "handle" + ], + "title": "Auth — Step-up Request Show — payload", + "type": "object" +} as const; + +/** As {@link PAYLOAD_SCHEMA}, for the success-response variant. */ +export const RESPONSE_PAYLOAD_SCHEMA = { + "$defs": { + "Handle": { + "description": "A single-use reference to one pending step-up, minted by the relying party with at least 128 bits of entropy and carried as base64url without padding. It names the request; it is not the request's challenge, and knowing it authorizes nothing but this one read.", + "pattern": "^[A-Za-z0-9_-]{22,86}$", + "title": "Handle", + "type": "string" + }, + "Handoff": { + "additionalProperties": false, + "description": "What a relying party MAY carry as `details.stepUpHandoff` beside an inline `details.stepUpRequest` (auth/step-up/approve-request/0.5, Inline delivery), so that a producer which cannot obtain the evidence itself can hand the step-up to the subject's approver agent. Not a payload of this task: defined here so producers and consumers share one shape.", + "properties": { + "handle": { + "$ref": "#/$defs/Handle" + }, + "expiresAt": { + "description": "The instant after which the relying party answers the handle with `notFound`: no later than the pending step-up's own expiry.", + "format": "date-time", + "type": "string" + }, + "show": { + "const": "https://trusttasks.org/spec/auth/step-up/requests/show/0.1", + "description": "The Type URI the approver's agent sends with the handle.", + "type": "string" + } + }, + "required": [ + "handle", + "expiresAt", + "show" + ], + "title": "Handoff", + "type": "object" + }, + "Operation": { + "additionalProperties": false, + "description": "The operation the step-up is bound to, exactly as the relying party received it.", + "properties": { + "type": { + "description": "The operation's Type URI, as the document the relying party refused named it.", + "maxLength": 2048, + "minLength": 1, + "type": "string" + }, + "payload": { + "description": "The operation's payload, member for member as received, so that the approver's agent can show it and — where it knows how the relying party derives `boundTo` — recompute the binding.", + "type": "object" + } + }, + "required": [ + "type", + "payload" + ], + "title": "Operation", + "type": "object" + }, + "Response": { + "$anchor": "response", + "additionalProperties": false, + "description": "The pending step-up and the operation it is bound to. Failures use trust-task-error, not this shape.", + "properties": { + "request": { + "description": "A complete auth/step-up/approve-request/0.5 Trust Task document, issued and signed by the relying party, whose recipient is the step-up's subject and whose payload is the request the operation's producer received inline — the same challenge, boundTo, accepts and approvers. The agent verifies it as a document in its own right — envelope, proof and payload against that specification's schema — over the members exactly as received: its proof covers every member, so it is deliberately an open object here rather than a typed one a binding could narrow.", + "type": "object" + }, + "operation": { + "$ref": "#/$defs/Operation" + }, + "ext": { + "$ref": "#/$defs/Ext" + } + }, + "required": [ + "request", + "operation" + ], + "title": "Auth — Step-up Request Show — response payload", + "type": "object" + }, + "Ext": { + "additionalProperties": true, + "description": "Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.", + "minProperties": 1, + "propertyNames": { + "pattern": "^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$" + }, + "title": "Ext", + "type": "object" + } + }, + "$ref": "#/$defs/Response", + "$schema": "https://json-schema.org/draft/2020-12/schema" +} as const; + +/** + * SPEC.md §7.2 policy for the request variant, from this specification's + * front matter. Pass to `consumeInbound` — items 5b, 7 and 8 are + * per-specification and cannot be derived from the document alone, and + * item 2 needs the schema this carries. + */ +export const SPEC = { + typeUri: TYPE_URI, + isBearer: false, + isProofRequired: true, + isRecipientRequired: true, + isIssuedAtRequired: true, + payloadSchema: PAYLOAD_SCHEMA, +} as const; + +/** + * SPEC.md §7.2 policy for the success-response variant. `isRecipientRequired` + * tracks the *issuer* party's requirement because a response swaps the + * parties (§7.3 item 5). + */ +export const RESPONSE_SPEC = { + typeUri: RESPONSE_TYPE_URI, + isBearer: false, + isProofRequired: true, + isRecipientRequired: true, + isIssuedAtRequired: true, + payloadSchema: RESPONSE_PAYLOAD_SCHEMA, +} as const; diff --git a/packages/core/src/specs/index.ts b/packages/core/src/specs/index.ts index 87505df2..0f3dc35a 100644 --- a/packages/core/src/specs/index.ts +++ b/packages/core/src/specs/index.ts @@ -27,6 +27,7 @@ export * as AuthSessionsList_v0_1 from "./auth/sessions/list/0.1/payload.js"; export * as AuthStepUpApproveRequest_v0_5 from "./auth/step-up/approve-request/0.5/payload.js"; export * as AuthStepUpApproveResponse_v0_7 from "./auth/step-up/approve-response/0.7/payload.js"; export * as AuthStepUpApproverAttest_v0_1 from "./auth/step-up/approver/attest/0.1/payload.js"; +export * as AuthStepUpRequestsShow_v0_1 from "./auth/step-up/requests/show/0.1/payload.js"; export * as AuthStepUpStart_v0_2 from "./auth/step-up/start/0.2/payload.js"; export * as AuthWhoami_v0_1 from "./auth/whoami/0.1/payload.js"; export * as ConfigPatch_v0_1 from "./config/patch/0.1/payload.js"; diff --git a/packages/core/src/vtc/index.ts b/packages/core/src/vtc/index.ts index 6a4061a7..eaa84e71 100644 --- a/packages/core/src/vtc/index.ts +++ b/packages/core/src/vtc/index.ts @@ -14,3 +14,4 @@ export * from "./directory-card.js"; export * from "./directory-present.js"; export * from "./forge-account.js"; export * from "./elections.js"; +export * from "./step-up-handoff.js"; diff --git a/packages/core/src/vtc/step-up-handoff.ts b/packages/core/src/vtc/step-up-handoff.ts new file mode 100644 index 00000000..54aab5f4 --- /dev/null +++ b/packages/core/src/vtc/step-up-handoff.ts @@ -0,0 +1,154 @@ +// The reader's half of the `step-up` trigger-link flow (VTI-LNK-125 – 131). +// +// A party acting for the person with a key they delegated — an assistant, say +// — is refused a gated act by a community with the step-up inline and a +// single-use handle beside it. It shows the person a `step-up` link. This +// module is what the wallet does with that link once it has decided the +// community is one it holds an identity at: +// +// 1. `buildStepUpShow`: `auth/step-up/requests/show/0.1`, from a key made +// for this exchange, carrying the handle as `handle` and as +// `parentThreadId` (VTI-LNK-054, 129). `sendOob` signs and posts it and +// checks the reply is the community's. +// 2. `checkStepUpShown`: the reply's `request` is a document in its own +// right — signed by the community, addressed to the step-up's subject, +// unexpired — and its `boundTo` is recomputed from the returned operation +// and the request's challenge (VTI-LNK-130, VTI-APV-015). Nothing the +// party that made the link said is taken; it never reaches the wallet. +// 3. `buildStepUpAnswer`: the approve-response the subject signs, carrying +// the approver's statement, sent to the community directly and never +// back through the link's producer (VTI-LNK-131). + +import { vtcStepUpBoundTo } from "../trust-tasks/domain-digest.js"; +import type { SigningIdentity } from "../siop/self-issued.js"; +import { + TYPE_URI as REQUESTS_SHOW, + type Payload as ShowPayload, + type Response as ShowResponse, +} from "../specs/auth/step-up/requests/show/0.1/payload.js"; +import { TYPE_URI as APPROVE_REQUEST } from "../specs/auth/step-up/approve-request/0.5/payload.js"; +import { TYPE_URI as APPROVE_RESPONSE } from "../specs/auth/step-up/approve-response/0.7/payload.js"; +import { assertSignedByCommunity, OobReplyInvalidError, type OobDocument } from "./oob-sign-in.js"; + +export { REQUESTS_SHOW as STEP_UP_REQUESTS_SHOW_TYPE, APPROVE_RESPONSE as STEP_UP_APPROVE_RESPONSE_TYPE }; + +/** A step-up the community's reply did not bear out, by the reason the flow + * stops with (VTI-LNK-130). */ +export class StepUpHandoffError extends Error { + constructor( + readonly reason: "binding-mismatch" | "not-the-subject", + message: string, + ) { + super(message); + this.name = "StepUpHandoffError"; + } +} + +function envelope

(type: string, issuer: string, recipient: string, payload: P): OobDocument

{ + return { + id: globalThis.crypto.randomUUID(), + type, + issuer, + recipient, + issuedAt: new Date().toISOString(), + payload, + }; +} + +/** `auth/step-up/requests/show/0.1`: issuer the exchange's own key, recipient + * the community, the handle as `payload.handle` and as `parentThreadId`. */ +export function buildStepUpShow( + kA: SigningIdentity, + vtcDid: string, + handle: string, +): OobDocument { + return { ...envelope(REQUESTS_SHOW, kA.did, vtcDid, { handle }), parentThreadId: handle }; +} + +/** A step-up, read and checked. */ +export interface ShownStepUp { + /** The step-up's subject: the identity the operation acts as. */ + subject: string; + /** The approve-request payload, as the community signed it. */ + request: Record & { subject: string; challenge: string; boundTo: string }; + /** The operation, exactly as the community received it. */ + operation: { type: string; payload: Record }; + /** When the request stops being answerable (epoch ms). */ + expiresAt: number; +} + +export interface StepUpShownExpectations { + vtcDid: string; + /** The community's verified DID document, the one the reply was checked + * against. */ + vtcDocument: Record; + /** Epoch milliseconds. */ + now: number; +} + +/** + * Check the reply to `requests/show` (VTI-LNK-130). The `request` must be an + * `approve-request/0.5` document the community signed (`authentication`, an + * operational proof), addressed to the step-up's subject and unexpired; the + * binding recomputed from the returned operation and its challenge must be + * the request's `boundTo`, or the flow stops `binding-mismatch`. Malformed + * replies throw {@link OobReplyInvalidError}. + */ +export async function checkStepUpShown( + reply: ShowResponse, + want: StepUpShownExpectations, +): Promise { + const bad = (what: string): never => { + throw new OobReplyInvalidError(`step-up request: ${what}`); + }; + const doc = reply?.request as unknown as OobDocument> | undefined; + if (!doc || typeof doc !== "object") bad("no request"); + if (doc!.type !== APPROVE_REQUEST) bad(`a ${String(doc!.type)}, not an approve-request`); + if (doc!.issuer !== want.vtcDid) bad("not issued by the community"); + await assertSignedByCommunity(doc!, want.vtcDid, want.vtcDocument, "step-up request", "authentication"); + const p = doc!.payload; + if (!p || typeof p !== "object") bad("no payload"); + const subject = p.subject; + const challenge = p.challenge; + const boundTo = p.boundTo; + if (typeof subject !== "string" || typeof challenge !== "string" || typeof boundTo !== "string") { + bad("no subject, challenge or binding"); + } + if (doc!.recipient !== subject) bad("not addressed to its subject"); + const expiresAt = typeof doc!.expiresAt === "string" ? Date.parse(doc!.expiresAt) : Number.NaN; + if (!Number.isFinite(expiresAt)) bad("no expiry"); + if (expiresAt <= want.now) bad("expired"); + const op = reply.operation; + if (!op || typeof op.type !== "string" || !op.payload || typeof op.payload !== "object") { + bad("no operation"); + } + const recomputed = await vtcStepUpBoundTo(op.type, op.payload, challenge as string); + if (recomputed !== boundTo) { + throw new StepUpHandoffError( + "binding-mismatch", + "the step-up is not bound to the operation the community returned", + ); + } + return { + subject: subject as string, + request: p as ShownStepUp["request"], + operation: { type: op.type, payload: op.payload as Record }, + expiresAt, + }; +} + +/** The approve-response the subject signs: approved, with the approver's + * statement as evidence (approve-response 0.7). Unsigned; the person's agent + * signs it as the subject. */ +export function buildStepUpAnswer( + vtcDid: string, + shown: ShownStepUp, + statement: Record, +): OobDocument { + return envelope(APPROVE_RESPONSE, shown.subject, vtcDid, { + subject: shown.subject, + challenge: shown.request.challenge, + decision: "approved", + evidence: { kind: "approverSigned", statement }, + }); +} diff --git a/packages/core/tests/links.trigger-link.mjs b/packages/core/tests/links.trigger-link.mjs index ca43b5a6..3f462ca9 100644 --- a/packages/core/tests/links.trigger-link.mjs +++ b/packages/core/tests/links.trigger-link.mjs @@ -445,7 +445,7 @@ test("step 8: an absolute flow on another host is wrong-host", () => { }); test("step 8: an unknown flow is unknown-flow (update)", () => { - refused(read(withFragment(fields({ _type: "/vti/flow/step-up/0.1" }))), "unknown-flow", "update"); + refused(read(withFragment(fields({ _type: "/vti/flow/device-enrol/0.1" }))), "unknown-flow", "update"); }); test("step 8: a MAJOR or (draft) MINOR the reader does not implement is unsupported-version", () => { diff --git a/packages/core/tests/task-surface.mjs b/packages/core/tests/task-surface.mjs index 8e2044bb..4cb66990 100644 --- a/packages/core/tests/task-surface.mjs +++ b/packages/core/tests/task-surface.mjs @@ -81,6 +81,14 @@ const NOT_IN_SDK = [ "vault/sign-trust-task, never tasks sent to the agent. The VTC, not the VTA, is the " + "counterparty, so vta-sdk carries no constant for them.", }, + { + prefix: "https://trusttasks.org/spec/auth/step-up/requests/show/", + why: + "A step-up handed to the person by a trigger link (vtc/step-up-handoff.ts, " + + "VTI-LNK-129): the wallet reads the step-up from the community's VTC with a key " + + "made for the read. The VTC, not the VTA, is the counterparty, so vta-sdk carries " + + "no constant for it.", + }, { prefix: "https://trusttasks.org/spec/vtc/join-requests/submit/0.3", why: diff --git a/packages/core/tests/vtc.step-up-handoff.mjs b/packages/core/tests/vtc.step-up-handoff.mjs new file mode 100644 index 00000000..5d6e8387 --- /dev/null +++ b/packages/core/tests/vtc.step-up-handoff.mjs @@ -0,0 +1,194 @@ +// The reader's half of the `step-up` trigger-link flow (VTI-LNK-125 – 131), +// against a fake community that signs the way a VTC does: the reply and the +// approve-request inside it, both operational (`authentication`). +// +// What is pinned is what the wallet refuses before it shows the person +// anything: a link on another flow, a request the community did not sign, one +// addressed to someone other than its subject, an expired one, and a binding +// that is not the returned operation's. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + newApproverKey, + sendOob, + OobRefusedError, + buildStepUpShow, + checkStepUpShown, + buildStepUpAnswer, + StepUpHandoffError, + STEP_UP_REQUESTS_SHOW_TYPE, + STEP_UP_APPROVE_RESPONSE_TYPE, +} from "../dist/vtc/index.js"; +import { generateSigningIdentity, signTrustTask, vtcStepUpBoundTo } from "../dist/index.js"; +import { parseTriggerLink, outcomeOf } from "../dist/links/index.js"; + +const VTC = "did:webvh:QmPEQVM1JPTyrvEgBcDXwjK4TeyLGSX1PxjgyeAisPviUx:members.example.org"; +const HANDLE = "Hk2pQ9xV4mT7rW1sZ8yN3A"; +const SUBJECT = "did:webvh:QmS:people.example:alice"; +const ENDPOINT = "https://members.example.org/v1/trust-tasks"; +const APPROVE_REQUEST = "https://trusttasks.org/spec/auth/step-up/approve-request/0.5"; +const OP = { + type: "https://trusttasks.org/spec/auth/step-up/approver/invite/0.2", + payload: { subject: "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK" }, +}; + +const vtcKey = generateSigningIdentity(); +const VM = `${VTC}#key-1`; +const vtcSigner = { ...vtcKey, did: VTC, kid: VM }; +const vtcDoc = { + id: VTC, + verificationMethod: [ + { id: VM, type: "Multikey", controller: VTC, publicKeyMultibase: vtcKey.did.slice("did:key:".length) }, + ], + assertionMethod: [VM], + authentication: [VM], +}; + +/** The inline request the community refused the operation with. */ +async function inline(over = {}) { + const challenge = "q3XKtZJ0p8m4Ud2vWcH7Rs1aLyN6bEf9"; + return { + subject: SUBJECT, + challenge, + boundTo: await vtcStepUpBoundTo(OP.type, OP.payload, challenge), + reason: "Invite an approver", + accepts: ["approverSigned"], + approvers: ["did:key:z6MkrJVnaZkeFzdQyMZu1cgjg7k1pZZ6pvBQ7XJPt4swbTQ2"], + ...over, + }; +} + +/** The approve-request document the community signs to the subject. */ +async function requestDoc({ payload, recipient = SUBJECT, signer = vtcSigner, expiresIn = 240_000 } = {}) { + const doc = { + id: crypto.randomUUID(), + type: APPROVE_REQUEST, + issuer: VTC, + recipient, + issuedAt: new Date().toISOString(), + expiresAt: new Date(Date.now() + expiresIn).toISOString(), + payload: payload ?? (await inline()), + }; + await signTrustTask({ envelope: doc, signing: signer, proofPurpose: "authentication" }); + return doc; +} + +/** A community answering `requests/show` with `body(doc)`, signed operationally. */ +function community(body) { + const seen = []; + const fetch = async (url, init) => { + const doc = JSON.parse(init.body); + seen.push(doc); + const out = await body(doc); + if (out.error) { + return new Response( + JSON.stringify({ type: "https://trusttasks.org/spec/trust-task-error/0.3", payload: { code: out.error, retryable: false } }), + { status: 404, headers: { "content-type": "application/json" } }, + ); + } + const res = { + id: crypto.randomUUID(), + type: `${doc.type}#response`, + issuer: VTC, + recipient: doc.issuer, + threadId: doc.id, + issuedAt: new Date().toISOString(), + payload: out.payload, + }; + await signTrustTask({ envelope: res, signing: vtcSigner, proofPurpose: "authentication" }); + return new Response(JSON.stringify(res), { status: 200, headers: { "content-type": "application/json" } }); + }; + return { fetch, seen }; +} + +const opts = (fetch) => ({ vtcDid: VTC, vtcDocument: vtcDoc, trustTaskEndpoint: ENDPOINT, fetch }); +const want = { vtcDid: VTC, vtcDocument: vtcDoc }; + +async function read(c) { + const kA = newApproverKey(); + const reply = await sendOob(kA, buildStepUpShow(kA, VTC, HANDLE), opts(c.fetch), "show", "authentication"); + return { kA, reply }; +} + +test("VTI-LNK-125: a step-up link parses as the step-up flow, and needs an expiry", () => { + const now = 1_791_460_800; + const link = `https://link.trustoverip.org/t#_from=${VTC}&_id=${HANDLE}&_exp=${now + 200}&_type=/vti/flow/step-up/0.1`; + const r = parseTriggerLink(link, { now }); + assert.equal(r.ok, true); + assert.equal(r.link.flow.spec.name, "step-up"); + assert.equal(r.link.flow.uri, "https://link.trustoverip.org/vti/flow/step-up/0.1"); + + const noExp = parseTriggerLink(link.replace(`&_exp=${now + 200}`, ""), { now }); + assert.deepEqual([noExp.ok, noExp.reason], [false, "missing-exp"]); + + // Every contact parses: whether it is one of the reader's services is the + // flow's question (VTI-LNK-128), answered before anything is sent. + const didKey = parseTriggerLink(link.replace(VTC, "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"), { now }); + assert.equal(didKey.ok, true); +}); + +test("VTI-LNK-128 – 129: the flow's reasons map to the outcomes the chapter gives them", () => { + assert.equal(outcomeOf("step-up-gone"), "expired"); + for (const r of ["not-in-records", "not-the-subject", "binding-mismatch"]) assert.equal(outcomeOf(r), "invalid"); +}); + +test("VTI-LNK-054 / 129: the first request carries the handle twice, from a fresh key", async () => { + const c = community(async () => ({ payload: { request: await requestDoc(), operation: OP } })); + const { kA } = await read(c); + const [sent] = c.seen; + assert.equal(sent.type, STEP_UP_REQUESTS_SHOW_TYPE); + assert.equal(sent.issuer, kA.did); + assert.match(kA.did, /^did:key:z6Mk/); + assert.equal(sent.recipient, VTC); + assert.equal(sent.parentThreadId, HANDLE); + assert.deepEqual(sent.payload, { handle: HANDLE }); + assert.equal(sent.proof.proofPurpose, "authentication"); +}); + +test("VTI-LNK-130: a request the community signed to its subject, bound to the returned operation, checks out", async () => { + const c = community(async () => ({ payload: { request: await requestDoc(), operation: OP } })); + const { reply } = await read(c); + const shown = await checkStepUpShown(reply.payload, { ...want, now: Date.now() }); + assert.equal(shown.subject, SUBJECT); + assert.deepEqual(shown.operation, OP); + assert.equal(shown.request.reason, "Invite an approver"); + + const answer = buildStepUpAnswer(VTC, shown, { id: "urn:uuid:statement" }); + assert.equal(answer.type, STEP_UP_APPROVE_RESPONSE_TYPE); + assert.equal(answer.issuer, SUBJECT, "the answer is the subject's"); + assert.equal(answer.recipient, VTC); + assert.deepEqual(answer.payload, { + subject: SUBJECT, + challenge: shown.request.challenge, + decision: "approved", + evidence: { kind: "approverSigned", statement: { id: "urn:uuid:statement" } }, + }); +}); + +test("VTI-LNK-130: an operation that is not the one the binding was computed over is binding-mismatch", async () => { + const other = { ...OP, payload: { subject: "did:key:z6MkSomeoneElse" } }; + const c = community(async () => ({ payload: { request: await requestDoc(), operation: other } })); + const { reply } = await read(c); + await assert.rejects( + checkStepUpShown(reply.payload, { ...want, now: Date.now() }), + (e) => e instanceof StepUpHandoffError && e.reason === "binding-mismatch", + ); +}); + +test("VTI-LNK-130: a request someone else signed, addressed elsewhere, or expired is refused", async () => { + const check = async (request) => + checkStepUpShown({ request, operation: OP }, { ...want, now: Date.now() }); + const stranger = generateSigningIdentity(); + await assert.rejects(check(await requestDoc({ signer: { ...stranger, did: VTC, kid: VM } })), /not signed by the community/); + await assert.rejects(check(await requestDoc({ recipient: "did:webvh:QmX:else.example" })), /not addressed to its subject/); + await assert.rejects(check(await requestDoc({ expiresIn: -1_000 })), /expired/); + const tampered = await requestDoc(); + tampered.payload.reason = "Something gentler"; + await assert.rejects(check(tampered), /not signed by the community/); +}); + +test("VTI-LNK-129: a handle the community cannot answer is its notFound refusal", async () => { + const c = community(async () => ({ error: "auth/step-up/requests/show:notFound" })); + await assert.rejects(read(c), (e) => e instanceof OobRefusedError && e.code === "auth/step-up/requests/show:notFound"); +}); diff --git a/packages/core/trust-tasks.lock b/packages/core/trust-tasks.lock index 66de0cf7..45d8d966 100644 --- a/packages/core/trust-tasks.lock +++ b/packages/core/trust-tasks.lock @@ -146,6 +146,12 @@ version = "0.1" type_uri = "https://trusttasks.org/spec/auth/step-up/approver/attest/0.1" digest = "sha256:9ad1dde405b9db723c790a741cb797af997fff412e62f4617bea8919a706ca9e" +[[task]] +slug = "auth/step-up/requests/show" +version = "0.1" +type_uri = "https://trusttasks.org/spec/auth/step-up/requests/show/0.1" +digest = "sha256:ba32f26c8b5ae1fad912f468e63f7ea3789497ec6fae746b9f6a19c7701d6fd8" + [[task]] slug = "auth/step-up/start" version = "0.2" diff --git a/packages/core/trust-tasks.toml b/packages/core/trust-tasks.toml index c4c7f89f..0b36073f 100644 --- a/packages/core/trust-tasks.toml +++ b/packages/core/trust-tasks.toml @@ -26,6 +26,7 @@ registry = "https://trusttasks.org" "auth/step-up/approve-request" = "0.5" "auth/step-up/approve-response" = "0.7" "auth/step-up/approver/attest" = "0.1" +"auth/step-up/requests/show" = "0.1" "auth/step-up/start" = "0.2" "auth/whoami" = "0.1" "config/patch" = "0.1" diff --git a/packages/core/trust-tasks/auth/step-up/requests/show/0.1.bundle.json b/packages/core/trust-tasks/auth/step-up/requests/show/0.1.bundle.json new file mode 100644 index 00000000..1c52e409 --- /dev/null +++ b/packages/core/trust-tasks/auth/step-up/requests/show/0.1.bundle.json @@ -0,0 +1 @@ +{"bundleVersion":1,"defOrigins":{"Ext":"https://trusttasks.org/spec/trust-task/0.4/framework#/$defs/Ext"},"defsOrder":{"/responseSchema":["Handle","Handoff","Operation","Response","Ext"],"/schema":["Handle","Handoff","Operation","Response","Ext"]},"deprecation":null,"errorCodes":[{"code":"auth/step-up/requests/show:notFound","meaning":"No pending step-up answers to this handle — unknown, already read, expired, or its step-up already approved or withdrawn. One code for all of them, so a handle reveals nothing about which.","retryable":false}],"extends":null,"policy":{"bearer":false,"issuedAtRequired":{"request":true,"response":true},"maxDocumentBytes":{"request":null,"response":null},"proofRequired":{"request":true,"response":true},"recipientRequired":{"request":true,"response":true}},"propertyOrder":{"/responseSchema/$defs/Handoff":["handle","expiresAt","show"],"/responseSchema/$defs/Operation":["type","payload"],"/responseSchema/$defs/Response":["request","operation","ext"],"/schema":["handle","ext"],"/schema/$defs/Handoff":["handle","expiresAt","show"],"/schema/$defs/Operation":["type","payload"],"/schema/$defs/Response":["request","operation","ext"]},"responseSchema":{"$defs":{"Ext":{"additionalProperties":true,"description":"Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.","minProperties":1,"propertyNames":{"pattern":"^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$"},"title":"Ext","type":"object"},"Handle":{"description":"A single-use reference to one pending step-up, minted by the relying party with at least 128 bits of entropy and carried as base64url without padding. It names the request; it is not the request's challenge, and knowing it authorizes nothing but this one read.","pattern":"^[A-Za-z0-9_-]{22,86}$","title":"Handle","type":"string"},"Handoff":{"additionalProperties":false,"description":"What a relying party MAY carry as `details.stepUpHandoff` beside an inline `details.stepUpRequest` (auth/step-up/approve-request/0.5, Inline delivery), so that a producer which cannot obtain the evidence itself can hand the step-up to the subject's approver agent. Not a payload of this task: defined here so producers and consumers share one shape.","properties":{"expiresAt":{"description":"The instant after which the relying party answers the handle with `notFound`: no later than the pending step-up's own expiry.","format":"date-time","type":"string"},"handle":{"$ref":"#/$defs/Handle"},"show":{"const":"https://trusttasks.org/spec/auth/step-up/requests/show/0.1","description":"The Type URI the approver's agent sends with the handle.","type":"string"}},"required":["handle","expiresAt","show"],"title":"Handoff","type":"object"},"Operation":{"additionalProperties":false,"description":"The operation the step-up is bound to, exactly as the relying party received it.","properties":{"payload":{"description":"The operation's payload, member for member as received, so that the approver's agent can show it and — where it knows how the relying party derives `boundTo` — recompute the binding.","type":"object"},"type":{"description":"The operation's Type URI, as the document the relying party refused named it.","maxLength":2048,"minLength":1,"type":"string"}},"required":["type","payload"],"title":"Operation","type":"object"},"Response":{"$anchor":"response","additionalProperties":false,"description":"The pending step-up and the operation it is bound to. Failures use trust-task-error, not this shape.","properties":{"ext":{"$ref":"#/$defs/Ext"},"operation":{"$ref":"#/$defs/Operation"},"request":{"description":"A complete auth/step-up/approve-request/0.5 Trust Task document, issued and signed by the relying party, whose recipient is the step-up's subject and whose payload is the request the operation's producer received inline — the same challenge, boundTo, accepts and approvers. The agent verifies it as a document in its own right — envelope, proof and payload against that specification's schema — over the members exactly as received: its proof covers every member, so it is deliberately an open object here rather than a typed one a binding could narrow.","type":"object"}},"required":["request","operation"],"title":"Auth — Step-up Request Show — response payload","type":"object"}},"$ref":"#/$defs/Response","$schema":"https://json-schema.org/draft/2020-12/schema"},"schema":{"$defs":{"Ext":{"additionalProperties":true,"description":"Vendor-namespaced extension object per SPEC.md §4.5.1. Each immediate key MUST be a reverse-DNS namespace; structure under each namespace is opaque to the framework.","minProperties":1,"propertyNames":{"pattern":"^[a-z][a-z0-9-]*(\\.[a-z0-9-]+)+$"},"title":"Ext","type":"object"},"Handle":{"description":"A single-use reference to one pending step-up, minted by the relying party with at least 128 bits of entropy and carried as base64url without padding. It names the request; it is not the request's challenge, and knowing it authorizes nothing but this one read.","pattern":"^[A-Za-z0-9_-]{22,86}$","title":"Handle","type":"string"},"Handoff":{"additionalProperties":false,"description":"What a relying party MAY carry as `details.stepUpHandoff` beside an inline `details.stepUpRequest` (auth/step-up/approve-request/0.5, Inline delivery), so that a producer which cannot obtain the evidence itself can hand the step-up to the subject's approver agent. Not a payload of this task: defined here so producers and consumers share one shape.","properties":{"expiresAt":{"description":"The instant after which the relying party answers the handle with `notFound`: no later than the pending step-up's own expiry.","format":"date-time","type":"string"},"handle":{"$ref":"#/$defs/Handle"},"show":{"const":"https://trusttasks.org/spec/auth/step-up/requests/show/0.1","description":"The Type URI the approver's agent sends with the handle.","type":"string"}},"required":["handle","expiresAt","show"],"title":"Handoff","type":"object"},"Operation":{"additionalProperties":false,"description":"The operation the step-up is bound to, exactly as the relying party received it.","properties":{"payload":{"description":"The operation's payload, member for member as received, so that the approver's agent can show it and — where it knows how the relying party derives `boundTo` — recompute the binding.","type":"object"},"type":{"description":"The operation's Type URI, as the document the relying party refused named it.","maxLength":2048,"minLength":1,"type":"string"}},"required":["type","payload"],"title":"Operation","type":"object"},"Response":{"$anchor":"response","additionalProperties":false,"description":"The pending step-up and the operation it is bound to. Failures use trust-task-error, not this shape.","properties":{"ext":{"$ref":"#/$defs/Ext"},"operation":{"$ref":"#/$defs/Operation"},"request":{"description":"A complete auth/step-up/approve-request/0.5 Trust Task document, issued and signed by the relying party, whose recipient is the step-up's subject and whose payload is the request the operation's producer received inline — the same challenge, boundTo, accepts and approvers. The agent verifies it as a document in its own right — envelope, proof and payload against that specification's schema — over the members exactly as received: its proof covers every member, so it is deliberately an open object here rather than a typed one a binding could narrow.","type":"object"}},"required":["request","operation"],"title":"Auth — Step-up Request Show — response payload","type":"object"}},"$id":"https://trusttasks.org/spec/auth/step-up/requests/show/0.1","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"The approver's agent asks the relying party for a pending step-up bound to one operation, named by the hand-off handle the relying party gave the operation's producer. The outer document members (id, type, issuer, recipient, issuedAt, expiresAt, proof) are owned by the framework — SPEC §6.3.","properties":{"ext":{"$ref":"#/$defs/Ext"},"handle":{"$ref":"#/$defs/Handle"}},"required":["handle"],"title":"Auth — Step-up Request Show — payload","type":"object"},"slug":"auth/step-up/requests/show","status":"draft","supersededBy":null,"targetFrameworkVersion":"0.6.0","typeUri":"https://trusttasks.org/spec/auth/step-up/requests/show/0.1","version":"0.1"} \ No newline at end of file diff --git a/packages/extension/src/approver-consent.tsx b/packages/extension/src/approver-consent.tsx index 67d01a16..11cf68d8 100644 --- a/packages/extension/src/approver-consent.tsx +++ b/packages/extension/src/approver-consent.tsx @@ -153,17 +153,35 @@ export function ApproverConsent({

Community
-
- Asked from {originHost(request.origin)}, which you signed in to this - community from. -
+ {request.via?.kind === "link" ? ( +
+ Its portal is {originHost(request.origin)}. You opened a step-up + link: someone acting for you there, such as your assistant, asked for this. +
+ ) : ( +
+ Asked from {originHost(request.origin)}, which you signed in to this + community from. +
+ )}
+ {request.via?.kind === "link" ? ( +
+
As
+
{request.via.identityLabel}
+
+ ) : null} + {request.kind === "stepUp" && request.operation ? ( <> {request.reason ? (
-
The community's reason (not verified by the wallet)
+
+ {request.via?.kind === "link" + ? "The community's reason (signed by the community)" + : "The community's reason (not verified by the wallet)"} +
{request.reason}
diff --git a/packages/extension/src/approver-policy.ts b/packages/extension/src/approver-policy.ts index 8f4396ad..7ade54de 100644 --- a/packages/extension/src/approver-policy.ts +++ b/packages/extension/src/approver-policy.ts @@ -389,6 +389,12 @@ export interface ApproverConsentRequest { /** decision only: the VTC's summary of the action, unverified. */ summary?: string; actionId?: string; + /** stepUp only: the step-up came through a `step-up` trigger link + * (VTI-LNK-130), not from a page. The request and its `reason` were then + * signed by the community itself, and `identityLabel` is the wallet's own + * record of the identity the operation acts as. `origin` is the portal the + * community's verified document names. */ + via?: { kind: "link"; identityLabel: string }; } /** The string the gesture's WebAuthn challenge is derived from: the ceremony's diff --git a/packages/extension/src/background.ts b/packages/extension/src/background.ts index 2ee669d1..98aca6e9 100644 --- a/packages/extension/src/background.ts +++ b/packages/extension/src/background.ts @@ -323,9 +323,16 @@ import { import { vetEgressUrl } from "./proxy-url.js"; import { ConsentReplayLedger, replayKey } from "./consent-replay.js"; import { deliverConsentResult, openConsentWindow, type ConsentDecision } from "./consent-window.js"; -import { parseTriggerLink } from "@openvtc/pnm-core/links"; +import { parseTriggerLink, outcomeOf, triggerLinkMessage } from "@openvtc/pnm-core/links"; import { isTriggerLinkShaped } from "./trigger-link-click.js"; +import type { StepUpReadResult, StepUpAnswerResult } from "./step-up-flows.js"; import { + RUNTIME_STEP_UP_LINK, + OFFSCREEN_STEP_UP_FLOW, + type RuntimeStepUpLinkRequest, + type RuntimeStepUpLinkResponse, + type OffscreenStepUpFlowOp, + type OffscreenStepUpFlowResponse, RUNTIME_TRIGGER_LINK, RUNTIME_TRIGGER_LINK_NUMBER, RUNTIME_SIGN_IN_STEP, @@ -3759,6 +3766,12 @@ async function handleTriggerLink(msg: RuntimeTriggerLinkRequest, tabId: number | if (tabId !== undefined) await chrome.tabs.update(tabId, { url: link }).catch(() => undefined); return; } + // A step-up handed to the person (VTI-LNK-125 – 131) is not a sign-in: no + // window of its own, the approver prompt, and the outcome as a notice. + if (parsed.ok && parsed.link.flow?.spec.name === "step-up") { + void runStepUpLink(link).then(notifyStepUpOutcome); + return; + } const flowId = crypto.randomUUID(); const record: SignInFlowRecord = { link: msg.link, @@ -3779,6 +3792,132 @@ async function handleTriggerLink(msg: RuntimeTriggerLinkRequest, tabId: number | }); } +// ─── A step-up handed to the person by a trigger link (VTI-LNK-125 – 131) ─── +// +// The person opened a `step-up` link: pasted into the popup, or clicked on a +// page. The offscreen document reads the step-up from the community and checks +// it (`step-up-flows.ts`); the approver prompt shows the operation the +// community returned and the identity from the wallet's own records; on +// approval the approver signs, and the person's agent sends the answer as the +// subject straight to the community. The party that made the link never sees +// any of it. Nothing of the link is logged. + +async function stepUpFlowOp( + op: OffscreenStepUpFlowOp, +): Promise { + await ensureOffscreenDocument(); + const reply = (await chrome.runtime.sendMessage({ + target: OFFSCREEN_TARGET, + type: OFFSCREEN_STEP_UP_FLOW, + ...op, + })) as OffscreenStepUpFlowResponse | undefined; + return reply ?? { ok: false, error: "the offscreen document did not answer" }; +} + +/** The words the person is shown for a reason the flow stopped with: only the + * outcome's message (VTI-LNK-021). */ +function stepUpReasonMessage(reason: Parameters[0]): string { + return triggerLinkMessage(outcomeOf(reason)) ?? "This code can't be used."; +} + +async function runStepUpLink(link: string): Promise { + const parsed = parseTriggerLink(link, { now: Math.floor(Date.now() / 1000) }); + if (!parsed.ok) return { ok: false, error: stepUpReasonMessage(parsed.reason) }; + if (parsed.link.flow?.spec.name !== "step-up") return { ok: false, error: "This is not a step-up code." }; + const active = await readActiveConnection(); + if (!active.ok) return { ok: false, error: active.error }; + + const read = await stepUpFlowOp({ + op: "read", + link, + vtaDid: active.conn.vtaDid, + ...(active.conn.restBaseUrl ? { restBaseUrl: active.conn.restBaseUrl } : {}), + }); + if (!read.ok) return { ok: false, error: read.error }; + const shown = read.result as StepUpReadResult; + if (!shown.ok) { + console.warn("[pnm step-up] read refused", { reason: shown.reason }); + return { ok: false, error: stepUpReasonMessage(shown.reason) }; + } + const v = shown.view; + const end = () => stepUpFlowOp({ op: "end", flowId: v.flowId }); + + // Every check `approveStepUp` makes, before the person sees anything: an + // approver for this community, offered by the request, and `boundTo` the + // digest of the operation shown. The offscreen makes them again by the key. + const params = { audience: v.vtcDid, request: v.request, operation: v.operation }; + const check = await stepUpApproverOp({ op: "check-step-up", params }); + if (!check.ok) { + await end(); + return { ok: false, error: check.error }; + } + const consent = await requestApproverConsent({ + kind: "stepUp", + origin: v.portalOrigin, + audience: v.vtcDid, + approverDid: String(check.result.approverDid), + subject: v.request.subject, + reason: typeof v.request.reason === "string" ? v.request.reason : "", + operation: v.operation, + challenge: v.request.challenge, + boundTo: String(check.result.boundTo), + via: { kind: "link", identityLabel: v.identityLabel }, + }); + if (!consent.approved) { + await end(); + return { ok: true, result: { outcome: "declined" } }; + } + const signed = await stepUpApproverOp({ + op: "sign-step-up", + params, + prfOutputB64u: consent.prfOutputB64u!, + }); + if (!signed.ok) { + await end(); + return { ok: false, error: signed.error }; + } + const answered = await stepUpFlowOp({ + op: "answer", + flowId: v.flowId, + statement: signed.result.statement as Record, + }); + if (!answered.ok) return { ok: false, error: answered.error }; + const result = answered.result as StepUpAnswerResult; + if (!result.ok) { + console.warn("[pnm step-up] answer refused", { reason: result.reason, code: result.code }); + return { + ok: false, + error: + result.reason === "refused" + ? "The community did not accept the approval. Ask for the step-up again." + : stepUpReasonMessage(result.reason), + }; + } + return { ok: true, result: { outcome: "approved" } }; +} + +/** A step-up link clicked on a page has no window to answer into; its outcome + * is a notice. */ +function notifyStepUpOutcome(res: RuntimeStepUpLinkResponse): void { + if (res.ok && res.result.outcome === "opened") return; + const declined = res.ok && res.result.outcome === "declined"; + const message = res.ok + ? declined + ? "You declined. Nothing was approved." + : "Approved. The same request can now be sent again." + : res.error; + chrome.notifications.create( + { + type: "basic", + iconUrl: chrome.runtime.getURL("icon-128.png"), + title: res.ok && !declined ? "Step-up approved" : "Step-up not approved", + message, + priority: 2, + }, + () => void chrome.runtime.lastError, + ); +} + /** * The number the portal shows for a request (C11), from the content script on * the page the code was clicked on. It goes to the flow whose link carries @@ -4443,6 +4582,35 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { return true; // async sendResponse } + if ((message as { type?: string })?.type === RUNTIME_STEP_UP_LINK) { + // The popup only: a pasted link is the person's own act (VTI-LNK-056). A + // page cannot reach this type — it is not in the content script's table. + if (!isExtensionPageSender(sender)) { + sendResponse({ ok: false, error: "step-up links are opened from the wallet itself" }); + return false; + } + const link = String((message as RuntimeStepUpLinkRequest).link ?? "").trim(); + // The popup closes when the approver prompt takes focus, so it is answered + // at once: whether the text is a step-up link. The outcome is a notice. + const parsed = parseTriggerLink(link, { now: Math.floor(Date.now() / 1000) }); + if (!parsed.ok) { + sendResponse({ ok: false, error: stepUpReasonMessage(parsed.reason) } satisfies RuntimeStepUpLinkResponse); + return false; + } + if (parsed.link.flow?.spec.name !== "step-up") { + sendResponse({ ok: false, error: "This is not a step-up code." } satisfies RuntimeStepUpLinkResponse); + return false; + } + sendResponse({ ok: true, result: { outcome: "opened" } } satisfies RuntimeStepUpLinkResponse); + void runStepUpLink(link) + .catch((e: unknown): RuntimeStepUpLinkResponse => ({ + ok: false, + error: e instanceof Error ? e.message : String(e), + })) + .then(notifyStepUpOutcome); + return false; + } + if ((message as { type?: string })?.type === RUNTIME_APPROVE_STEP_UP) { handleApproveStepUp(message as RuntimeApproveStepUpRequest) .then(sendResponse) diff --git a/packages/extension/src/bridge-protocol.ts b/packages/extension/src/bridge-protocol.ts index abd96192..45be8dfd 100644 --- a/packages/extension/src/bridge-protocol.ts +++ b/packages/extension/src/bridge-protocol.ts @@ -3944,3 +3944,47 @@ export interface OffscreenRoomOffersRequest { } export type OffscreenRoomOffersResponse = { ok: true; result: unknown } | { ok: false; error: string; code?: string }; + +// ─── A step-up handed to the person by a trigger link (VTI-LNK-125 – 131) ─── +// +// popup / content script ──RUNTIME_STEP_UP_LINK / RUNTIME_TRIGGER_LINK──▶ background +// The person pasted a `step-up` link into the popup, or clicked one on a +// page. The background re-parses it and runs the flow; nothing is +// answered to a page. +// +// background ──OFFSCREEN_STEP_UP_FLOW──▶ offscreen +// `read`: the offscreen document reads the step-up from the community +// and checks it (`step-up-flows.ts`). The background then raises the +// approver prompt with what was read, and on approval has the approver +// sign (`OFFSCREEN_STEP_UP_APPROVER`, `sign-step-up`). `answer`: the +// approve-response the person's agent signs as the subject, sent to the +// community. `end`: the person declined; forget the flow. + +/** popup → background: a `step-up` link the person pasted. */ +export const RUNTIME_STEP_UP_LINK = "vta-wallet/step-up-link" as const; + +export interface RuntimeStepUpLinkRequest { + type: typeof RUNTIME_STEP_UP_LINK; + link: string; +} + +/** What the person is told: opened (the popup's answer: the flow runs on and + * its outcome is a notice), approved, declined, or why not, in the words + * VTI-LNK-021 gives each outcome. */ +export type RuntimeStepUpLinkResponse = + | { ok: true; result: { outcome: "opened" | "approved" | "declined" } } + | { ok: false; error: string }; + +export const OFFSCREEN_STEP_UP_FLOW = "offscreen/step-up-flow" as const; + +export type OffscreenStepUpFlowOp = + | { op: "read"; link: string; vtaDid: string; restBaseUrl?: string } + | { op: "answer"; flowId: string; statement: Record } + | { op: "end"; flowId: string }; + +export type OffscreenStepUpFlowRequest = { + target: typeof OFFSCREEN_TARGET; + type: typeof OFFSCREEN_STEP_UP_FLOW; +} & OffscreenStepUpFlowOp; + +export type OffscreenStepUpFlowResponse = { ok: true; result: unknown } | { ok: false; error: string }; diff --git a/packages/extension/src/offscreen.ts b/packages/extension/src/offscreen.ts index 347fbbb1..0550dcac 100644 --- a/packages/extension/src/offscreen.ts +++ b/packages/extension/src/offscreen.ts @@ -246,6 +246,9 @@ import { } from "./bridge-protocol.js"; import { OFFSCREEN_SIGN_IN_STEP, + OFFSCREEN_STEP_UP_FLOW, + type OffscreenStepUpFlowRequest, + type OffscreenStepUpFlowResponse, OFFSCREEN_SIGN_IN_PAGE_NUMBER, OFFSCREEN_UV_SETTINGS, type OffscreenSignInPageNumberRequest, @@ -256,6 +259,7 @@ import { type UvSettingsAgent, } from "./bridge-protocol.js"; import { SignInFlows, type SignInVaultEntry } from "./sign-in-flows.js"; +import { StepUpFlows } from "./step-up-flows.js"; import { approvers as uvApproversAt, enrolPhone, @@ -369,6 +373,20 @@ chrome.runtime.onMessage.addListener((message, sender, respond) => { ); return true; // async sendResponse } + if (msg.type === OFFSCREEN_STEP_UP_FLOW) { + // Only the background drives a step-up flow; a content script reaching + // this listener directly is refused. + if (!isExtensionContextSender(sender)) { + sendResponse({ ok: false, error: "step-up flows are the wallet's own" } satisfies OffscreenStepUpFlowResponse); + return false; + } + doStepUpFlow(message as OffscreenStepUpFlowRequest) + .then(sendResponse) + .catch((e: unknown) => + sendResponse({ ok: false, error: e instanceof Error ? e.message : String(e) }), + ); + return true; // async sendResponse + } if (msg.type === OFFSCREEN_SIGN_IN_PAGE_NUMBER) { const req = message as OffscreenSignInPageNumberRequest; signInFlows.pageNumber(req.flowId, req.matchNumber); @@ -1660,6 +1678,47 @@ async function listSelfIssued(vtaDid: string, restBaseUrl?: string): Promise { + const { session, holder, service } = await getVtaSession(vtaDid, restBaseUrl); + const { signedEnvelope } = await vaultSignTrustTask(session, { + holder, + service, + entryId, + unsignedEnvelope: unsigned as unknown as TrustTaskEnvelope, + }); + return signedEnvelope; +} + +// A step-up handed to the person by a `step-up` trigger link (VTI-LNK-125 – +// 131). The approver prompt and signature are the background's and +// `OFFSCREEN_STEP_UP_APPROVER`'s; this reads the step-up and sends the answer. +const stepUpFlows = new StepUpFlows({ + now: () => Date.now(), + vta: (vtaDid, restBaseUrl) => ({ + listIdentities: () => listSelfIssued(vtaDid, restBaseUrl), + signTask: (entryId, unsigned) => signTaskAsEntry(vtaDid, restBaseUrl, entryId, unsigned), + }), +}); + +async function doStepUpFlow(req: OffscreenStepUpFlowRequest): Promise { + switch (req.op) { + case "read": + return { ok: true, result: await stepUpFlows.read(req.link, req.vtaDid, req.restBaseUrl) }; + case "answer": + return { ok: true, result: await stepUpFlows.answer(req.flowId, req.statement) }; + case "end": + stepUpFlows.end(req.flowId); + return { ok: true, result: null }; + } +} + const signInFlows = new SignInFlows({ now: () => Date.now(), // A ceiling the member grants; the community ends the session at the @@ -1696,16 +1755,7 @@ const signInFlows = new SignInFlows({ }, // A join request, signed as the persona the person chose: the community // takes the applicant from this signature. - signTask: async (entryId, unsigned) => { - const { session, holder, service } = await getVtaSession(vtaDid, restBaseUrl); - const { signedEnvelope } = await vaultSignTrustTask(session, { - holder, - service, - entryId, - unsignedEnvelope: unsigned as unknown as TrustTaskEnvelope, - }); - return signedEnvelope; - }, + signTask: (entryId, unsigned) => signTaskAsEntry(vtaDid, restBaseUrl, entryId, unsigned), // Only the label changes: the entry is written back with its own id, // version, context, targets and kind, and no secret, so the VTA keeps the // one it holds. diff --git a/packages/extension/src/popup.tsx b/packages/extension/src/popup.tsx index d03a35cf..acc988aa 100644 --- a/packages/extension/src/popup.tsx +++ b/packages/extension/src/popup.tsx @@ -19,6 +19,9 @@ import { } from "./store.js"; import { RUNTIME_CREATE_CONTEXT, + RUNTIME_STEP_UP_LINK, + type RuntimeStepUpLinkRequest, + type RuntimeStepUpLinkResponse, RUNTIME_DERIVE_SIGNING_KEY_ID, RUNTIME_HOLDER_STATE, RUNTIME_LIST_CONTEXTS, @@ -270,6 +273,46 @@ function VtaSwitcher({ ); } +/** + * A `step-up` link someone acting for you — your assistant, say — gave you + * (VTI-LNK-125 – 131). Pasting it here is your own act (VTI-LNK-056); the + * wallet reads the step-up from the community itself and shows you what will + * be done before anything is approved. The outcome arrives as a notice, since + * this popup closes when the approver prompt opens. + */ +function OpenStepUpLink(): React.JSX.Element { + const [link, setLink] = useState(""); + const [error, setError] = useState(null); + async function open(): Promise { + setError(null); + const res = (await chrome.runtime.sendMessage({ + type: RUNTIME_STEP_UP_LINK, + link, + } satisfies RuntimeStepUpLinkRequest)) as RuntimeStepUpLinkResponse | undefined; + if (!res) setError("The wallet did not answer."); + else if (!res.ok) setError(res.error); + else setLink(""); + } + return ( +
+
Approve a step-up link
+
+ setLink(e.target.value)} + placeholder="https://link.trustoverip.org/t#…" + aria-label="Step-up link" + style={{ flex: 1, fontSize: 12 }} + /> + +
+ {error ? {error} : null} +
+ ); +} + function truncateDid(did: string): string { if (did.length <= 36) return did; return `${did.slice(0, 20)}…${did.slice(-12)}`; @@ -458,6 +501,8 @@ function ConnectedView({ This adds no admin code to the popup bundle — it opens a URL. The CI guard that keeps `pnm-core/admin` out of every wallet surface is unaffected, and still passes. */} + +