# Owner grants for lot mutations (SDK 0.2.5)

A trusted plugin can change the price or active state of a lot without a recent
order delivery when its owner explicitly grants that permission. Grants are
server-owned capabilities, separate from plugin settings and schemas. Existing
installations begin with no grants; saving configuration or upgrading a plugin
does not create or expand them.

The plugin still needs its approved `lots:active` / `lots:price` scope and the
corresponding broker feature must be enabled. Grants support only
`lots.active.set` and `lots.price.set`. A selected grant also permits `lots.get`
for the same lot when the plugin has `lots:read`, so it can capture and verify
the current price before changing or restoring it. This does not grant account
listing access. Grants do not authorize title, stock,
raising, orders, payments, or other operations.

## Owner API

Use the existing authenticated owner session (web, including the normal mutation
Origin check, or desktop authentication). A plugin broker token cannot write grants.
The route prefix is `/api/v2/plugin-marketplace` for web and
`/api/v2/plugin-marketplace/desktop` for desktop.

1. `GET /installations/{installation_id}/resources?kind=lot` returns the full
   cached Worker catalog with `items`, `total`, `next_cursor`, `coverage`,
   `status`, and `updated_at`. Optional `search`, `account_id`, and `cursor`
   parameters use the same catalog pagination. Each lot has an opaque
   `resource_id`. This endpoint does not require a native UI declaration or a
   recent order. The Worker signs its catalog; a plugin cannot supply it.
2. `GET /installations/{installation_id}/resource-grants` returns
   `{"config_revision": 1, "grants": []}` for an unchanged old installation.
3. `PUT /installations/{installation_id}/resource-grants` replaces the complete
   selection atomically:

   ```json
   {
     "expected_config_revision": 1,
     "grants": [
       {
         "resource_id": "pri_<catalog ID>",
         "actions": ["lots.active.set", "lots.price.set"]
       }
     ]
   }
   ```

   The response contains the new `config_revision` and `grants`, each containing
   `resource_grant_id`, `resource_id`, `account_id`, `lot_id`, and `actions`.
   The owner-only `resource_id` permits preserving selections outside the current
   catalog page; it is not an authorization token. A stale revision
   returns 409. `grants: []` revokes all permissions and works even if the Worker
   catalog has expired. Selecting a new grant requires a catalog less than five
   minutes old. Duplicate resources/actions and undeclared actions are rejected.

Unchanged selections keep their grant ID. Removing a grant, changing its action
set, or granting again after removal produces a new random server ID. Do not
construct a grant ID from an account, lot, resource ID, or installation ID.

## Plugin use

`GET /api/v2/broker/config` includes a sibling `resource_grants` array next to
`config` and `config_revision`. These descriptors are readable by the bound
plugin; they cannot be written through plugin configuration. Pass the selected
`resource_grant_id` with its exact `account_id` and `lot_id` when requesting a lot
mutation. The action input must contain exactly one of `delivery_id` or
`resource_grant_id`. Existing delivery-bound calls retain their checks.

The server checks the grant at submission and every Worker claim/reclaim:
installation, license, VPS, action scope, trusted runtime, exact account/lot,
and a current Worker inventory containing that lot. A grant is persistent, but
execution stops while inventory is stale or the lot disappears. No 24-hour
order-delivery dependency applies to grants. Existing installation/account/lot
and queued-action quotas remain; the per-delivery bucket applies only to
calls using a delivery.

Reuse the normal action idempotency key for a retry of the same intent. An
idempotent replay can report the existing action; it does not authorize new
execution. After revocation, queued or expired-lease actions cannot execute
with an old grant ID, even if the owner later grants the same lot again.
Revocation cannot cancel work already issued to a Worker or an external FunPay
operation already in progress; reconcile that operation through its existing
action status before issuing a new intent.

## Calendar campaign example

The following helper queues a price change for one exact lot selected by the
owner. It works for both the beginning and end of a campaign; neither call needs
an order delivery. The campaign scheduler and its durable journal belong to the
plugin, not to the grant itself.

```python
import hashlib
import json

from funpay_pulse_sdk import BrokerClient


def queue_campaign_price(client, *, campaign_id, account_id, lot_id, phase, price):
    if phase not in {"apply", "restore"}:
        raise ValueError("phase must be apply or restore")
    grants = client.get_config().resource_grants
    grant = next(
        item for item in grants
        if item["account_id"] == account_id
        and item["lot_id"] == lot_id
        and "lots.price.set" in item["actions"]
    )  # No matching grant: stop this lot and ask the owner to review access.
    intent = json.dumps([campaign_id, account_id, lot_id, phase], separators=(",", ":"))
    key = "campaign:" + hashlib.sha256(intent.encode()).hexdigest()
    return client.set_lot_price(
        account_id=account_id,
        lot_id=lot_id,
        resource_grant_id=grant["resource_grant_id"],
        price=price,
        idempotency_key=key,
    )


client = BrokerClient.from_env()
# Call from your scheduler with immutable, previously persisted intent data:
# action = queue_campaign_price(client, campaign_id=campaign.id,
#     account_id=target.account_id, lot_id=target.lot_id,
#     phase="apply", price=target.campaign_price)
# At the campaign's end, including later than 24 hours:
# action = queue_campaign_price(client, campaign_id=campaign.id,
#     account_id=target.account_id, lot_id=target.lot_id,
#     phase="restore", price=target.original_price)
```

Before the first mutation, read the lot with `client.get_lot` using the same
grant and a separate stable idempotency key. Poll `client.get_action(action_id)`
until it succeeds, then read `status.lot_result()`. This is the Worker's cached
lot view, not an atomic price lock. Persist the original price, campaign price,
target identity and stable intent key in `storage:own` before submitting a
mutation. Store its `action_id` and reconcile status after a restart. A returned
queued action is not proof that the price changed.

At restoration, re-read the lot and apply the plugin's explicit policy for manual
owner edits; an unconditional restore could overwrite them. These APIs do not
provide compare-and-set on the external FunPay price. Do not change `price` for
an existing intent key or generate another key merely because a response was
lost. Revoked access, stale inventory or an uncertain previous result must stop
that lot until resolved. Re-granting is a new owner decision, not a way for the
plugin to bypass a revoked queued action. Process each selected lot separately;
there is no atomic bulk transaction across the catalog.

`set_lot_active` accepts the same grant binding and uses its own intent key.
Persist the original active state separately if the campaign changes it.

## Deployment compatibility

Alembic `20261028_0031` adds `plugin_resource_grants` on PostgreSQL and SQLite;
SQLite application initialization also creates missing model tables. There is
no legacy data rewrite. Apply the schema before deploying code that reads it.
Ownership foreign keys cascade deletes so old cleanup paths remain compatible.
A rollback should restore the previous application while retaining the table;
the explicit schema downgrade refuses to drop a nonempty grant table.
