import { type CatalogEntry } from "./delegated.js"; import { type GrantAgeScope } from "./grants-age.js"; import type { DelegateJwk, SealedAgeProof, SealedMembershipProof } from "./ceremony/mandate.js"; import type { IntentBoundsInput } from "./ceremony/intent-sign/bounds.js"; import type { Branding, ReaderIdentity, TrustLevel } from "./types.js"; /** Why a grant operation refused — a TYPED union (never `string`; #95 review). */ export type GrantDoorCode = "not-authorized" | "not-allowed" | "invalid-request" | "invalid-amount" | "per-spend-exceeded" | "budget-exceeded" | "wrong-merchant" | "step-up" | "revoked" | "expired" | "agent-held-key" | "refused"; /** Bound WHAT the agent may buy (not just how much): explicit SKUs and/or catalog categories. */ export interface GrantAllow { skus?: string[]; categories?: string[]; } /** How the human authorizes a grant (spec 012): * • "page" — today's default: click Approve on the server page (server-issued-demo). * • "device" — the wallet SIGNS the Intent Mandate first; the grant reaches "authorized" * ONLY through the verified device signature (trust_level "device-signed"). */ export type GrantSigning = "device" | "page"; export interface CreateGrantOptions { /** The granted merchant scope. */ merchant: string; /** Cumulative budget in dollars — once drawn down, further spends refuse `budget-exceeded`. */ budget: number; /** Per-purchase cap in dollars — one spend over it refuses `per-spend-exceeded`. */ perSpend: number; /** Optional item bounds — a spend outside them refuses `not-allowed`, fail-closed. */ allow?: GrantAllow; /** The human sentence shown at approve time. */ description?: string; /** How the human authorizes (spec 012). Defaults to **"device"**: the grant's approveUrl serves * the wallet signing ceremony, and the grant only authorizes on a verified device signature over * its exact bounds. Pass "page" to opt INTO the click-to-approve stand-in — it takes the human's * word for it (`trustLevel: "server-issued-demo"`) and exists for demos, examples and CI, where * no phone is in the loop. Approving a grant is a signature by default; the weaker door must be * asked for by name. */ signing?: GrantSigning; /** * The AGENT's public key (spec 014, FR-5) — `agentKey.publicJwk` from the `/agent` entry point. * * Pass it and the gate never generates or holds the agent's key: the person's phone signs a * permission naming THIS key, and once they have, `grant.mandate.intent` is what the agent spends * — with `DelegatedIntent`, at any merchant the permission names, checked there by * `verifyDelegatedPurchase`. Such a grant does not spend through `grant.spend` (it refuses * `agent-held-key`): the gate has no key to spend it with, which is the point. * * Omit it and the gate generates the key and spends server-side, as before. Device signing only — * there is nothing for a page click to bind the key to. A PRIVATE JWK is refused. */ agentKey?: DelegateJwk; } export type GrantStatus = "pending" | "authorized" | "denied" | "revoked"; /** A grant's DISPLAY lifecycle — the projection/UI state, derived ONCE server-side from the * raw {@link GrantStatus} plus the live money read so a view never re-derives "low"/"exhausted" * independently (spec 011 FR-1 / UX A2). `low` = remaining has fallen to ≤ 20% of budget; * `exhausted` = the budget is fully drawn down. */ export type GrantLifecycle = "pending" | "active" | "low" | "exhausted" | "revoked" | "denied"; /** A grant's live money read, in the grant's dollars — what a display shows and what the * {@link grantLifecycle} derivation reads. `spent + remaining === budget`. */ export interface GrantUsage { budget: number; spent: number; remaining: number; } /** * The ONE lifecycle derivation (spec 011 FR-1 / UX A2): map a grant's raw status + live money * to its display lifecycle. Terminal/pending states pass straight through; an authorized grant * is `exhausted` when spent out, `low` at ≤ 20% remaining, else `active`. Kept here (not in the * widget) so every surface — server projection, tests, custom views — reads the same rule. */ export declare function grantLifecycle(input: { status: GrantStatus; budget: number; remaining: number; }): GrantLifecycle; /** The one spend door (spec 009 FR-003 shape). A retried idempotency key replays the ORIGINAL * outcome — success OR refusal (`replayed: true` on both) — so a key can never be repurposed * with a different item after a refusal (a P2 on #112). */ export type SpendDoor = { ok: true; amount: number; remaining: number; replayed: boolean; authorization: "delegated"; delegationId?: string; /** For a device-signed grant (spec 012, FR-5): the signed Intent Mandate this spend * draws against — `id` (the content-addressed mandate id) + `boundsHash` (the exact * bounds the device signed). Absent on page-mode grants. So a settled purchase traces * to the signed authority. */ mandate?: { id: string; boundsHash: string; }; } | { ok: false; code: GrantDoorCode; remaining?: number; retryable?: string; replayed?: boolean; }; /** The device-signature evidence recorded when a device-mode grant authorizes (spec 012). * `verifiedBy` + `trustLevel` are the FR-4 provenance: "gate"/"device-signed" for the in-gate * backend, or an external verifier's id + its attested level (relayed verbatim). */ export interface GrantMandateEvidence { boundsHash: string; signedAt: string; credentialType: string; verifiedBy: string; trustLevel: TrustLevel; /** * The AP2 Mandate Content the wallet signed — the TERMS, not just their digest. * * `boundsHash` says a signature covered these bounds; this says what the bounds were, in the * protocol's own vocabulary, so "what did I authorize?" can be answered from the grant record * without rebuilding it. Plain JSON. Absent on a grant sealed by a backend that reported none. */ mandates?: Array>; /** * The signed permission itself — the wallet's presentation and the `delegate` disclosures the * request carried. Exactly `DelegatedIntent.fromWalletPresentation`'s input, so an agent holding * the key it names can spend it. Holding it without that key spends nothing. */ intent?: { presentation: string; disclosures: string[]; }; } export interface SpendItems { /** Durable per-purchase key — a safe retry replays the SAME outcome (`replayed: true`). */ idempotencyKey: string; items: Array<{ sku: string; qty?: number; }>; } export interface GrantsDeps { walletOrigin: string; /** The priced catalog (dollars) — the ONE price source; also read by the `allow` bounds. */ catalog?: Record; /** Stable secret sealing the intent-sign reader context (spec 012). Defaults to a * per-instance random key — fine because grant records are in-memory / process-local. */ signingKey?: string; /** Stable reader identity the intent-sign request presents (absent ⇒ per-request self-signed). */ readerIdentity?: ReaderIdentity; /** Host brand for the signing page (absent ⇒ the built-in look; never brands the trust line). */ branding?: Branding; /** Your loyalty programme's discount, as a percentage (e.g. `10`). Setting it OPTS IN: the * page grows a "present your membership" step, and a grant the human proves one on prices * every unattended purchase at this rate (#172). Absent ⇒ no membership step anywhere and * every grant prices at full catalog price, exactly as before. The rate is SEALED into each * grant when it authorizes, so changing it here never re-prices a grant already authorized. */ loyaltyDiscountPct?: number; } export declare class Grants { private readonly deps; private readonly records; private readonly locks; private gate?; private served; /** Stable secret that seals the intent-sign reader context (spec 012). */ readonly signingSecret: string; /** The configured loyalty rate, or undefined when the host runs no programme (#172). Read by * the page and the grant-credential rail to decide whether a membership step exists at all. * Fail-closed on a nonsensical configuration rather than offer a rate that can't be honoured: * a discount must be a real percentage strictly between 0 and 100. */ get _loyaltyDiscountPct(): number | undefined; constructor(deps: GrantsDeps); /** Config the rails `grants.serve(app)` registers read — the intent-sign rail (spec 012) and * the grant-credential rail (#172). One object, so a page and its ceremonies can never be * configured differently. */ get railConfig(): { walletOrigin: string; secret: string; readerIdentity?: ReaderIdentity; branding?: Branding; loyaltyDiscountPct?: number; }; /** * Everything the intent-sign rail needs to build the AP2 Mandate Content for a grant, all of * it from the SERVER's record (spec 014). `null` when the grant is unknown, or when it has no * delegate key — a grant with no agent key to name in `cnf` cannot be delegated at all, and * saying so here is better than minting a mandate bound to nothing. * * `mandateExp` is the grant's own expiry when it has one. Without one it falls back to a year * from creation, because AP2 requires an expiry and a mandate that never expires is worse * than one whose horizon the caller can read. A grant that shows the human no expiry and then * signs a one-year one is a gap in the approve page, recorded in spec 014. */ _intentSignInputsFor(id: string): { bounds: IntentBoundsInput; delegate: { kty: "EC"; crv: "P-256"; x: string; y: string; }; agentHeld: boolean; mandateExp: number; allowedSkus: string[]; } | null; /** * The agent public key the SEALED ENGINE will spend with, once the grant is authorized. * * On a device-signed grant this must be the same key `_intentSignInputsFor` put in the * mandates' `cnf`, because that is the key the human's signature covers. They are minted in * two different places and handed across one seam, so the test that pins them together needs * to read both ends. `null` before authorization, or for a grant with no engine. */ _engineDelegateFor(id: string): DelegateJwk | null; /** * The concrete product ids this grant may buy — the value AP2's `checkout.line_items` * constraint carries. * * A grant bounded by CATEGORY names no products, and emitting its empty `skus` list straight * into the mandate said "nothing may be bought" (the constraint's own meaning) for a grant the * human had approved for a whole category. The categories are scanned against the catalog * here, the same way the approve page's age disclosure already scans them, so what the mandate * says matches what the page said and what `spend()` enforces. * * AGE-RESTRICTED ITEMS ARE OMITTED UNLESS THE HUMAN PROVED FOR THEM (#172). `spend()` refuses * an age-restricted line with `step-up` whenever the sealed proof does not cover it, so listing * those skus here would mint a mandate that authorizes MORE than the gate will ever honour — * the human signs "your agent may buy the whiskey", the agent is then refused every time. The * signature has to say exactly what is spendable, so the same `ageProofCovers` predicate the * spend path runs decides membership here. A grant gains nothing by omission: proving the age * BEFORE signing puts the items back, which is the order the page presents them in. * * `null` when the set cannot be determined — no catalog to scan. A caller MUST refuse to mint * rather than fall back to an empty list, which would authorize nothing while looking like a * grant. */ _allowedSkusFor(id: string): string[] | null; /** The grant's signed BOUNDS (spec 012) — assembled from the SERVER's record, never the * client. `null` when the grant is unknown. The intent-sign rail re-derives boundsHash * from this at /verify and requires equality with the value sealed at /request. */ _boundsInputFor(id: string): IntentBoundsInput | null; private engineGate; /** * Serve the approve/deny page at each grant's `approveUrl` (`/credentagent/grants/:id`) — * so the documented create-and-send-the-link flow actually works. Idempotent per instance. * The page is the demo stand-in for the wallet ceremony; it calls the same seams (#71). */ serve(app: unknown): void; /** Open a grant awaiting the human's one-time approval. Returns immediately (status "pending"). */ create(opts: CreateGrantOptions): Promise; /** Rehydrate a grant handle by id (the authorize-now / spend-later process boundary). */ retrieve(id: string): Promise; /** * The authorize seam — TODAY called by the demo approve page; the wallet key-signing ceremony * (roadmap #71) calls the SAME seam. Seals the intent (mints the engine grant) on approval. * A denied/revoked grant can never be authorized after the fact (terminal states). */ _authorize(id: string): Promise; /** * The age seam (#172) — called by the grant-credential rail when the human's wallet proves an * over-age claim, BEFORE the grant authorizes (before the Approve tap in page mode, before the * signature in device mode). The wallet ceremony and the instant-demo path both land here; * neither may pass a threshold of its own choosing (the rail re-derives it from the catalog). * * PENDING ONLY, and serialized with the rest of the lifecycle: an already-authorized grant can * never gain a capability the human didn't approve, and a proof can't race the approve tap. * Returns false when the grant is unknown or past pending — the caller surfaces that, it is * never a silent no-op. */ _recordAgeProof(id: string, proof: { provenAge: number; expiresAt?: string; }): Promise; /** * The membership seam (#172) — called by the grant-credential rail when the human's wallet * discloses a loyalty membership, BEFORE the grant authorizes. Its effect is the mirror of the * age proof's: where age UNLOCKS items, this LOWERS the price of every purchase the agent * later makes under the grant. * * PENDING ONLY and serialized with the rest of the lifecycle, for the same reason: an already * authorized grant must never gain terms the human didn't authorize. The rate is taken from * THIS instance's configuration and sealed with the claim — never from the request — so a * later config change cannot re-price a grant that is already sealed. */ _recordMembershipProof(id: string, proof: { membershipNumber: string; }): Promise; /** * The DEVICE authorize seam (spec 012) — called by the intent-sign rail's /verify ONLY * after it verified the wallet's device signature over this grant's exact bounds. Seals the * engine with the evidence's trust level (relayed verbatim — the gate never upgrades it) and * records the mandate. A page-mode grant, or a grant not pending, is refused — so a * device-signed authorization can never be forged around the verified-evidence path. */ _authorizeDevice(id: string, evidence: GrantMandateEvidence): Promise; /** The deny seam — the human rejected the approve screen. Terminal (spec FR-007). */ _deny(id: string): Promise; /** Is this sku inside the grant's `allow` bounds? Fail-closed: with bounds set, an unknown or * uncategorized item does NOT pass. No bounds ⇒ everything in the catalog is allowed. * Delegates to the SHARED predicate the approve page's age disclosure reads (grants-age.ts), * so what the page says a grant covers is exactly what this enforces (#172). * * A device-signed grant is bounded by BOTH: the live `allow` bounds AND the frozen list its * mandate names. Whichever is narrower wins, which is the signed one whenever the catalog has * grown since. */ private allowed; private view; } /** The grant handle `create()`/`retrieve()` return — status + the two verbs. */ export interface Grant { id: string; readonly status: GrantStatus; /** Where the human approves ONCE. Today a demo page the host serves; the wallet ceremony later. */ approveUrl: string; /** The one merchant this grant is cryptographically scoped to (the sealed authorization record). */ readonly merchant: string; budget: number; perSpend: number; allow?: GrantAllow; description?: string; /** How the human authorizes this grant (spec 012) — "device" (default: their wallet signs these * exact bounds) or "page" (the click-to-approve stand-in, an explicit opt-in for demos/CI). */ readonly signing: GrantSigning; /** When/how consent happened — "delegated-demo" until the wallet ceremony lands (honesty axis). */ presence: string; /** How strongly the authorization is bound (honesty axis): "server-issued-demo" for page mode, * "device-signed" once a device grant is wallet-signed (or a verifier's relayed level). */ trustLevel: string; /** The age-restricted products these bounds NAME, so the page can say so before the human * authorizes (#172). `{ minimumAge: null, items: [] }` when the grant names no restricted * product. DISCLOSURE only: the spend-time refusal is unchanged. */ readonly ageScope: GrantAgeScope; /** The age claim the human proved before authorizing, if they did (#172). Absent ⇒ an * age-restricted purchase steps up. Read it to answer "may this grant buy that?" the way the * gate does — pair it with `ageProofCovers(proof, requiredAge)`. */ readonly ageProof?: SealedAgeProof; /** The loyalty membership the human proved before authorizing, if they did (#172). Present ⇒ * every purchase under this grant is priced at `discountPct` off, on every path. */ readonly membershipProof?: SealedMembershipProof; /** The device-signature evidence — present ONLY once a device-mode grant is signed: the exact * bounds the device signed (`boundsHash`), when, which credential type, and who verified. * `mandates` is the AP2 Mandate Content the wallet signed — the TERMS, so "what did I * authorize?" is answerable from the grant and not only from a digest. Absent on page-mode * grants and unsigned device grants. */ readonly mandate?: { boundsHash: string; signedAt: string; credentialType: string; verifiedBy: string; mandates?: Array>; /** The signed permission, for a grant created with `agentKey` — pass it to * `DelegatedIntent.fromWalletPresentation` (from `/agent`) and spend it with that key. */ intent?: { presentation: string; disclosures: string[]; }; }; /** The agent's public key, when the grant was created with one (spec 014, FR-5). Such a grant * spends with `DelegatedIntent` at the merchant; `spend()` here refuses `agent-held-key`. */ readonly agentKey?: DelegateJwk; /** Live money read (dollars) for a display/projection — `{ budget, spent, remaining }`. Async * because the engine's committed-draws ledger is the authority (it may be remote later); a * pending grant reads `{ spent: 0, remaining: budget }`. Feeds {@link grantLifecycle}. */ usage(): Promise; spend(input: SpendItems): Promise; revoke(): Promise; }