Skip to content

Engineering & Technology

Inbound data: Rows from your own server, the moment they happen

Some pegs have a server of their own. A forms peg collects answers on a public page; a booking peg takes requests from a website. Each of those belongs in the peg’s table, and the table’s hooks should run the moment it arrives, not when somebody next opens the peg.

This post shows how your server gets a key for that, why the key now comes from a person’s own Allow and never from your page, and how to hold one key for each person who allows it.

The problem, and what an inbound key is

Without a key you have two choices, and both are bad.

  • Pull when the peg opens. Your page asks your server what came in and writes the rows itself. Nothing happens until somebody opens the peg, and neither do the hooks.
  • Give your server a full credential. It could read every table, edit and delete rows, and reach far more than one table. A leak loses all of it.

What your server needs is much smaller: add rows to the peg’s table, and nothing else. That is an inbound key.

An inbound key looks like wpin_<id>_<secret>. The id is 32 lower-case hex digits, and the secret is 43 characters of url-safe base64, which may contain _ and -. Workpeg stores only a hash of the secret. The key works on two routes under https://api.workpeg.com:

  • POST /v1/inbound/rows/ adds one row;
  • GET /v1/inbound/whoami/ says where the key writes, and writes nothing.

It cannot read, list, edit or delete a row. It covers either one of your peg’s tables, or with "*" all of your peg’s own tables in that business, the ones it has now and the ones it makes later. Never another peg’s table, a mail table, or a table in another business.

And a key writes as its holder: the person who allowed it. Each row is recorded as added by them, and every write checks again that they are still active, still in the business, still an owner or admin, and still able to add rows to that table.

Why your page no longer makes keys

Because a key acts as a person, only that person can create it, by pressing Allow on Workpeg’s own screen. Workpeg then sends the key server to server, to the service address Workpeg registered for your peg. No key ever passes through your page, and your page cannot draw the question, press its buttons or see the secret.

Older page code that made keys stops at the build:

Inbound keys are given by permission now: declare one in workpeg.json and call workpeg.request_permission.

That is what workpeg.create_inbound_key fails with. A workpeg.post, put or patch whose URL names inbound-keys fails the build too, and the runtime refuses such a request before sending it when the URL is only known at run time. A peg built before this change gets 410 with code page_keys_closed from the api for any signed-in staff member of the business, and no key is made. Anyone else is refused before that, with 401 or 403.

Keys your page made earlier keep working until the business’s first permission key is delivered and confirmed. Then they stop, and their next 401 names the reason page_keys_closed. workpeg.get_inbound_keys and workpeg.revoke_inbound_key stay, so a page can still list and revoke what it made. A key that came by permission is never in that list; only Settings > Permissions turns it off.

One key per person

A permission is per person. Each owner or admin who presses Allow gets their own grant and their own key, which adds rows as them, only to tables they can write. Nobody allows for anybody else.

So your service may hold several keys for one business, one per grant. Every delivery names the person with two fields:

  • holder: an opaque id, stable for your peg, that business and that person. It is never a name, an email or an internal id, and two pegs never see one person under the same ph_ id.
  • holder_kind: "sso" when Workpeg set your service’s own Sign in with Workpeg client, in which case holder is the sub your client already sees for that person. Otherwise "peg", and holder is ph_ and 40 hex digits.

That lets you route a row to the right key. If the row belongs to an owner or admin who allowed and signed in with Workpeg, such as the one who published the form, use the key whose holder_kind is "sso" and whose holder is their sub. Otherwise use the key you have held longest. A member never holds a key, since only owners and admins can Allow, so a row a member published goes out under another holder’s key and reads as added by that person.

When a holder loses owner or admin, leaves the business, can no longer write the table, or their account is deactivated, their grant closes, their keys stop, and you get permission.revoked with reason person. Nobody else’s grant changes. Drop that one key and send with the others. The person may allow again later if they qualify.

End to end

1. Declare the permission

In your peg’s workpeg.json:

"permissions": [{
  "name": "instant_answers",
  "kind": "inbound",
  "purpose": "Adds each answer to Responses seconds after someone submits it.",
  "ask": "install",
  "inbound": {"table": "responses"}
}]
  • name: 1 to 40 lower-case letters, digits or underscores, starting with a letter, and not containing workpeg.
  • purpose: one sentence, at most 160 bytes, with no web address, email or domain, and no Workpeg. Only Workpeg’s reviewer reads it; the business never sees it.
  • ask: "install" (the default) asks right after an owner or admin installs the peg. "settings" waits for Settings > Permissions. "runtime" waits for your code to call workpeg.request_permission.
  • inbound: exactly {"table": "<alias>"} or {"table": "*"}.

An entry takes exactly those five keys. A peg declares at most one inbound permission, for one alias or for "*", never both. A second one fails the build, and the api refuses the same section, which then declares nothing. Build with SDK 0.170.0 or newer.

workpeg ui build copies the section into dist/manifest.json, which you upload:

workpeg cdn submit ui/dist/manifest.json --path manifest.json --overwrite

Every write with a key checks that your live manifest still declares the permission. Remove it and Workpeg revokes the grants and their keys; declare it again and everyone is asked again.

With "runtime", ask from a click:

async def ask(self):
    answer = await workpeg.request_permission("instant_answers")
    if answer == "needs_admin":
        self.note = "Ask an owner or admin to turn on instant answers."

It takes only the name and resolves to one word, and never fails: allowed, denied, dismissed, needs_admin or unavailable. The question is drawn only after a person’s click or key press; from a page load or a timer it draws nothing and answers from the stored state. workpeg.permission_status(name) shows nothing and works as a FutureBuilder future. At most 3 questions a page load, and 3 a day for a person.

2. Ask Workpeg to allow the kind and set your callback

Two things only Workpeg can do, because your manifest is not signed and must never say where a credential goes:

  1. Approve your peg to ask for the inbound kind. Until then the permission is listed nowhere and nothing can allow it.
  2. Set your callback, an https URL, and give you its signing secret once, privately. The address is never read from the manifest.

Keep the secret where your server keeps its other secrets. If it leaks, ask for a new one; the address stays and allowed keys keep working. If the callback address changes, every key sent to the old one stops at once and each owner or admin is asked again.

3. The person is asked, by Workpeg

The alert is drawn by Workpeg Accounts, either on its own page or in a frame over your peg that your page cannot read, cover or press. It says the same for every peg of this kind:

Forms wants to add information to your tables from the internet

It can only add new information. It can’t see, change or delete anything.

[Details] [Don’t Allow] [Allow]

Details shows where it adds (“Adds to: Responses, in Acme Ltd”), that each entry is recorded as added by them, and that Settings > Permissions can change it. Nothing can be decided in Details.

Allow cannot be pressed by accident. It does nothing until the whole alert has been on screen, visible and focused, for 1.5 seconds with no press on it. Any press on the alert before then, a click, a tap, Enter or Space, starts the wait over, and a held press lasts until it is released. After the wait, a pointer coming onto Allow, a tap or a click on it (even with the cursor already resting there), or Tab then Enter or Space answers. So presses closer together than 1.5 seconds can never land on Allow: a click meant for something else, or a game that has you tap fast where Allow appears, answers nothing. What no rule can tell apart is a press that comes a full 1.5 seconds after the last one, with the question in plain sight the whole time; that press is taken as the person’s own. Opening Details, a blur or a hidden tab start the wait again.

In the frame over your peg, a browser that can report the frame is fully visible (Chromium today) keeps Allow from arming while anything covers, fades or crops the frame, or while the screen is too small to show it all; Don’t Allow and Not now still work. A browser that cannot report it (Firefox and Safari today) shows “Continue on Workpeg Accounts” in Allow’s place, which opens Settings in a new tab. On Workpeg Accounts’ own pages, Allow always shows.

Don’t Allow answers at once and is remembered. Not now and Escape in the frame, and Escape or the backdrop at install, are remembered by Workpeg for a day on every device. Closing the card around the frame, with its × or the backdrop over your page, holds for a day on that browser only. Closing a Review in Settings records nothing.

The question is never asked on a dev install page, a staging host, or a peg page that is itself in a frame. Those get unavailable.

If a one-table permission’s table does not exist yet, Allow is recorded and nothing is sent. When your page creates the table with that alias, Workpeg checks everything again, makes the key and sends it. That first create_table can take up to 15 seconds longer. A "*" Allow never waits: its key arrives even if the peg has no table yet.

4. The signed delivery

On Allow, Workpeg POSTs permission.granted to your callback: https only, to public addresses only, no redirects, 5 s to connect and 10 s to read, 15 s in all. Your reply is read to a limit and thrown away.

Content-Type: application/json
X-Workpeg-Signature: v1=<hex>
X-Workpeg-Timestamp: <unix seconds>
X-Workpeg-Event: permission.granted
X-Workpeg-Delivery: <uuid4, equal to body.delivery>
User-Agent: Workpeg-Permissions/1
{"event": "permission.granted", "delivery": "<uuid4>", "reason": "install",
 "peg": "<peg>", "kind": "inbound", "name": "instant_answers",
 "business": "<business_uuid>", "business_name": "Acme Ltd",
 "grant": "<grant_uuid>", "sequence": 1,
 "key": "wpin_<32hex>_<43>", "key_id": "<32hex>", "replaces": null,
 "table": "<table_uuid>",
 "scope": {"kind": "inbound", "tables": "<table_uuid>", "can": ["add_rows"]},
 "tables": [{"id": "<table_uuid>", "alias": "responses", "name": "Responses"}],
 "tables_more": false, "holder": "ph_<40hex>", "holder_kind": "peg",
 "allowed_at": "<iso>", "expires_at": null}

The signature is v1= and the hex HMAC-SHA256 of "<timestamp>.<raw body>" under your secret. The timestamp is inside what is signed, so a captured delivery cannot be replayed forever, but refusing an old one is your job.

reason is install, settings, request, renew (Renew and Retry) or rotate. Don’t treat that set as closed. For "*", table is null, scope.tables is "*", and tables lists at most 20 tables, cut further to keep the body under 16 KiB; tables_more says it was cut. whoami lists up to 200, with a tables_more of its own. The body never carries a person’s name or email, row data or the purpose. New fields are only ever added at the top level, so ignore the ones you don’t know and never refuse a body for them.

5. Verify, confirm with whoami, store

In order: POST only, at most 16 KiB; the four X-Workpeg- headers present; timestamp within 300 s; signature checked with hmac.compare_digest; event and delivery equal to their headers; a delivery id not seen in the last 10 minutes; peg, kind and name your own, and the id inside the key equal to key_id; whoami agrees with the body; the key stored encrypted, per grant, refusing a sequence equal to or lower than the one you hold for that same grant. Only then answer 2xx.

The rule: answer 2xx only for a key you stored, and never call whoami for a key you will not keep, because whoami is also what confirms the key.

import hashlib, hmac, json, os, time
import requests
from cryptography.fernet import Fernet

API = "https://api.workpeg.com"
SECRET = os.environ["WORKPEG_SIGNING_SECRET"].encode()
SEAL = Fernet(os.environ["INBOUND_KEY_SEAL"])   # its own secret
PEG, NAME = "forms", "instant_answers"         # yours, as declared
NEEDED = ("X-Workpeg-Signature", "X-Workpeg-Timestamp",
          "X-Workpeg-Event", "X-Workpeg-Delivery")


def whoami(key):
    return requests.get(f"{API}/v1/inbound/whoami/", timeout=4,
                        allow_redirects=False,
                        headers={"Authorization": f"Bearer {key}"})


def receive(method, headers, raw, db):
    if method != "POST":
        return 405
    if len(raw) > 16 * 1024:
        return 413
    if not all(headers.get(h) for h in NEEDED):
        return 401
    ts, sig = headers["X-Workpeg-Timestamp"], headers["X-Workpeg-Signature"]
    if not (ts.isascii() and ts.isdigit() and sig.isascii()):
        return 401               # "²".isdigit() is True; int("²") is not
    if abs(time.time() - int(ts)) > 300:
        return 401
    mac = hmac.new(SECRET, ts.encode() + b"." + raw, hashlib.sha256)
    if not hmac.compare_digest(b"v1=" + mac.hexdigest().encode(),
                               sig.encode()):
        return 401
    body = json.loads(raw)
    if (body.get("event"), body.get("delivery")) != (
            headers["X-Workpeg-Event"], headers["X-Workpeg-Delivery"]):
        return 400
    if not db.remember_delivery(body["delivery"], seconds=600):
        return 409
    status = 503
    try:
        handler = {"permission.granted": granted,
                   "permission.revoked": revoked,
                   "permission.changed": changed}.get(body["event"])
        status = handler(body, db) if handler else 422
    finally:
        if status >= 500:        # let Workpeg's retry of this id through
            db.forget_delivery(body["delivery"])
    return status


def granted(body, db):
    grant, seq = body["grant"], body["sequence"]
    if (body.get("peg"), body.get("kind"), body.get("name")) != (
            PEG, "inbound", NAME):
        return 422               # not the permission you declared
    part = str(body.get("key") or "").split("_", 2)
    if len(part) != 3 or part[0] != "wpin" or part[1] != body.get("key_id"):
        return 422               # every later step finds it by key_id
    if db.floor(grant) >= seq:
        return 409               # older than the key we hold for it
    if not db.will_keep(body):
        return 422               # decided before asking Workpeg anything
    try:
        r = whoami(body["key"])
    except requests.RequestException:
        return 503
    if r.status_code == 429 or r.status_code >= 500:
        return 503
    if r.status_code != 200:
        return 422
    me = r.json()
    if (me["business"], me["table"], me["grant"]) != (
            body["business"], body["table"], grant):
        return 422
    with db.lock(body["business"]):
        if db.floor(grant) >= seq:
            return 409
        db.store_key(grant, business=body["business"], sequence=seq,
                     key_id=body["key_id"], replaces=body["replaces"],
                     reason=body["reason"],
                     sealed=SEAL.encrypt(body["key"].encode()),
                     holder=body["holder"], holder_kind=body["holder_kind"],
                     tables=me.get("tables"))   # whoami's list wins for "*"
    return 200

db.store_key keeps the key that replaces names, when there is one, as the grant’s previous key, rather than overwriting it (see Renew below). A key nobody confirms within 10 minutes is refused 403 unconfirmed and revoked.

Any non-2xx tells Workpeg the key did not arrive, and Workpeg revokes that new key at once. Settings shows “Couldn’t reach Forms.” with Retry. Workpeg never resends permission.granted by itself; a person presses Retry.

6. Send rows

POST /v1/inbound/rows/
Authorization: Bearer wpin_<id>_<secret>
Idempotency-Key: <your own id for this item>

{"data": {"<column id>": "value"}}

A "*" key must send exactly {"table": "<alias or id>", "data": {...}}; a one-table key may name only its own table. The body is at most 256 KiB, every key in data is a column id, and the row goes through the ordinary row checks as the key’s holder.

Idempotency-Key is 1 to 100 printable ASCII characters. A replay of a written row answers 200 with the first row; a replay while the first is still writing answers 409 still_writing. It holds per key and table.

Never send from a browser: any request with an Origin header is 403 from_browser. Limits are 120 a minute per key and 240 per table.

Status Meaning
201 {id, business, table}
200 Idempotent replay
400 Body, unknown_column, bad Idempotency-Key, or unfit
401 key_invalid, or key_revoked with reason
403 Origin, permission, person or table checks
409 still_writing, Retry-After: 5
413 Over 256 KiB
422 refused_by_table: a pre-save hook said no
429 Throttled, with Retry-After
503 not_now: a hook failed or timed out, Retry-After: 5

Every refusal is {detail, code}. Act on code, never on detail. The 403 codes include paused, peg_off, turned_off, holder_not_admin, cannot_write and too_old. No answer ever repeats row data or a hook’s words.

Here is a push that routes to the person’s key and fails per key, never per business:

def push(item, db):
    keys = db.healthy_keys(item.business)      # held longest first
    if item.pinned_key_id:                     # an earlier try got no answer
        keys = [k for k in keys if k.key_id == item.pinned_key_id]
    else:
        mine = [k for k in keys
                if k.holder_kind == "sso" and k.holder == item.owner_sub]
        keys = mine + [k for k in keys if k not in mine]
    for k in keys:
        body = {"data": item.data}
        if k.all_tables:
            body = {"table": "responses", "data": item.data}
        try:
            r = requests.post(
                f"{API}/v1/inbound/rows/", json=body, timeout=10,
                allow_redirects=False,
                headers={"Authorization": f"Bearer {k.open(SEAL)}",
                         "Idempotency-Key": item.public_id})
        except requests.RequestException:
            return db.retry_later(item, pin=k.key_id)
        if r.status_code in (200, 201):
            got = r.json()
            if got.get("business") == k.business and k.binds(got.get("table")):
                return db.delivered(item)      # a "*" key learns its table
            db.mark(k, "elsewhere")            # written, but not where bound
            return db.leave_for_pull(item)
        if r.status_code in (401, 403):
            code = r.json().get("code")
            if code in ("paused", "peg_off"):
                db.pause(k, seconds=300)
            else:
                db.mark(k, code)               # this key only
            continue                           # same item, next key
        if r.status_code in (409, 429) or r.status_code >= 500:
            return db.retry_later(item, pin=k.key_id)
        return db.give_up(item, r.status_code)  # 400, 413, 422
    db.leave_for_pull(item)

The pin matters. A write that got no answer may already be stored under that key’s Idempotency-Key, so retry it only with the same key. Another key would store it twice and run the hooks twice. If that key is gone, leave the item for your pull, which skips what the table already holds.

Check every 2xx too: its business and table must be the ones the key is bound to. A "*" key records its table’s id from its first accepted write.

7. Renew, Retry and Turn off

In Settings > Permissions each owner or admin sees their own key, with Turn off and Renew, or Retry when the key could not be delivered. Only the holder may Renew or Retry. Under it they see the other owners’ and admins’ keys, with Turn off only.

Renew and Retry raise the grant’s sequence by 1, make a new key as the holder and send it with reason: "renew". When the grant still has a working key (a Renew, or a Retry while an older key works), replaces names it, and the old key keeps working until the new one is delivered and confirmed by your whoami. Then the old key gets permission.revoked with reason replaced. So keep the old key until you hear replaced for it, and fall back to it if the new one is revoked as lost or failed.

A Retry after a failed first delivery has no old key to keep. That key was revoked as failed the moment its delivery failed, so replaces is null, the new key is the grant’s only one, and no replaced follows.

If Workpeg cannot tell whether your callback got the new key, but your whoami confirmed it, use decides: any call with the new key promotes it. After 10 minutes the new key is dropped as lost only if the old key wrote a row in that time and the new key was never used. A whoami or rotate with the old key never counts as use.

Turn off revokes the grant’s keys at once and raises its sequence by 1. You get permission.revoked with reason admin.

8. The revoked and changed notices

permission.revoked carries no key. It names one grant and, usually, one key: drop only that key, and raise that grant’s floor to the notice’s sequence, so an older delivery can never bring the key back. When a grant closes after its keys had already ended, key_id is null; drop whatever you still hold for that grant.

A revocation that ends the permission comes at the grant’s closing sequence, one higher than the grant’s own, so it is never lower than any key the grant made. A Turn off during a Renew ends both keys, and the old key’s notice then comes two higher than that key. One that leaves it on (replaced, unconfirmed, lost, failed) comes at the key’s own, so it never passes its replacement. When a person allows again, Workpeg names their old, already dead keys with reason admin at the sequence the grant had before.

Reasons that end it: admin, workpeg, uninstall, undeclared, person, table_deleted, table_moved, business_deleted, and service. Don’t treat that set as closed either. service means Workpeg moved your callback; it goes to the old callback, with a shorter body that names the business, grant and key and little else, and only when Workpeg chooses to tell it. A notice is sent only after the key has stopped.

permission.changed is a hint and carries no key. change is tables, renamed, access, paused or resumed. On it, call whoami with the key you hold and keep whoami’s answer. It never moves the floor.

def revoked(body, db):
    with db.lock(body["business"]):
        db.drop_key(body["grant"], key_id=body["key_id"])  # null: the grant's
        db.raise_floor(body["grant"], body["sequence"])
    return 200


def changed(body, db):
    k = db.key(body["grant"], key_id=body["key_id"])
    if k is None:
        return 200
    try:
        r = whoami(k.open(SEAL))
    except requests.RequestException:
        return 503                       # Workpeg sends it again
    if r.status_code == 429 or r.status_code >= 500:
        return 503                       # Workpeg's trouble, not the key's
    try:
        me = r.json()
    except ValueError:
        me = {}
    if r.status_code == 200 and (
            me.get("business"), me.get("table"), me.get("grant")) == (
            k.business, k.table, body["grant"]):
        db.refresh(k, me)                # tables, holder; clears any mark
    elif r.status_code == 403 and me.get("code") in ("paused", "peg_off"):
        db.pause(k)
    else:
        db.mark(k, r.status_code)        # refused, or bound elsewhere
    return 200

db.drop_key removes that one key. If it was the current key and you kept the previous one, the previous becomes current again.

Workpeg retries these notices on a 5xx or no answer, after 1, 4 and 16 minutes. A 4xx is final. That is why the receiver forgets a delivery id it answered 5xx.

Rotating a key from outside

Your service can ask for a fresh key with the one it holds: after a suspected leak, or on a schedule. Workpeg makes the new key as the same holder for the same grant and delivers it to your registered callback, as permission.granted with reason: "rotate" and replaces set, while your call is still open. The answer never contains a key, so a thief calling rotate never sees the new one, and once your service confirms it the stolen key answers 401 key_revoked with reason replaced. Serve the callback from another worker than the one making the call.

If rotation is ever switched off, the route answers 404 rotate_off; stop rotating and keep using the key you hold.

def rotate(k, db):
    asked = db.set_pending_rotation(k)         # commit before asking
    try:
        r = requests.post(f"{API}/v1/inbound/rotate/", json={},
                          timeout=(4, 20), allow_redirects=False,
                          headers={"Authorization": f"Bearer {k.open(SEAL)}"})
    except requests.ReadTimeout:
        return settle_unsure(k, db, asked)     # sent: it may still land
    except requests.RequestException:
        return db.clear_pending_rotation(k)
    if r.status_code == 202:
        return settle_unsure(k, db, asked, named=r.json().get("key_id"))
    db.clear_pending_rotation(k)               # every definite answer
    if r.status_code == 200:
        return                                 # your callback stored it
    if r.status_code == 404:
        return db.stop_rotating()              # rotation is off
    code = r.json().get("code")
    if r.status_code in (401, 403) and code in ("paused", "peg_off"):
        return db.pause(k)
    if r.status_code in (401, 403):
        return db.mark(k, code)
    # 409, 429, 502: try later


def settle_unsure(k, db, asked, named=None):
    new = db.key_for_grant(k.grant)
    if (new.key_id == k.key_id                 # still the old key
            or new.reason != "rotate" or new.replaces != k.key_id
            or new.stored_at < asked           # not this rotation's
            or (named and new.key_id != named)):
        return False                           # leave it; the old key works
    try:
        r = whoami(new.open(SEAL))             # use promotes it
    except requests.RequestException:
        return False                           # Workpeg decides
    me = r.json() if r.status_code == 200 else {}
    return me.get("grant") == k.grant and me.get("slot") == "current"
Answer Meaning
200 {delivery: "delivered", key_id, sequence}
202 {delivery: "unsure", key_id, sequence}: see below
502 delivery_failed; your current key still works
400 body_shape: the body must be exactly {}
401 key_revoked or key_invalid
403 not_a_grant_key, other_service, blocked, or a write check’s
409 not_current, rotation_pending (with Retry-After), or busy
429 too_soon, throttled, or busy
503 not_now

Only the service holding the holder’s confirmed current key may rotate, and not with a key that is itself a pending replacement. A key must be at least an hour old. At most 4 rotations a day per grant, and 300 an hour per peg.

On 202 or a read timeout, Workpeg could not be sure your callback got the new key. Look in your store, and count a key as this rotation’s only if your callback stored it from a reason: "rotate" delivery whose replaces named the old key, after you asked, and, after a 202, it is the key_id the answer named. A different key alone proves nothing: a Renew’s would pass too. If it is this rotation’s, call whoami once with it, which promotes it; it is promoted when whoami answers "slot": "current" for the same grant. Otherwise leave it; your current key keeps working until a new one is confirmed.

Doing it safely on your server

  • Keep the signing secret with your server’s other secrets, never in peg code or a repository.
  • Store keys encrypted, under a secret of their own. A database dump alone should hold no usable key.
  • Send a key only to https://api.workpeg.com, only in the Authorization header, with redirects off. Never log it; log the public key id.
  • Never store or log Workpeg’s response bodies. Keep fixed words and a status.
  • Decide whether you will keep a key before calling whoami, and answer 2xx only after storing it.
  • Forget a delivery id you answered 5xx, or Workpeg’s retry is refused as a duplicate.
  • Retry an unanswered write only with the key that sent it.
  • When you change the secret your keys are sealed with, re-seal them with the old secret still able to open, then rotate every key.

formnow is an open-source service built this way, and you can copy most of it. It differs from this post in three places. It keeps one key per grant and overwrites it on a Renew or a rotation, so it holds no previous key to fall back to after lost or failed. On 401 key_revoked with reason replaced, it waits up to 10 minutes for the new key before marking the old one. And it routes a row to its publisher’s key only with FORMNOW_INBOUND_PER_PERSON=1, which is off by default.

Its docs/contract.md covers the receiver, one key per person, refusal codes, rotation and all-tables keys under “Instant answers by permission”. docs/build-your-own.md section 10, “Optional: add rows the moment they arrive”, walks the steps. docs/security.md covers storage under “Stored inbound keys” and “Re-keying the stored keys”.

What your hooks see

A row an inbound key added runs the table’s pre-save and post-save hooks, built-in and function, with context["actor"] == "inbound". A function hook woken this way gets the row and the business, but no Workpeg token. The caller is a server outside Workpeg, so treat the row as outside input.

In short

  • An inbound key adds rows to one of your peg’s tables, or with "*" to any of its own tables, and does nothing else. It writes as the person who allowed it.
  • Only that person’s Allow, on Workpeg’s screen, makes one. Workpeg sends it to your registered callback, never to your page. Page code that makes keys fails the build, and the api answers 410 page_keys_closed.
  • Each owner or admin who allows gets their own key. Hold one per grant, route by holder, and drop only the key a notice names.
  • Declare one inbound permission, ask Workpeg to approve it and set your callback, and let Workpeg ask the person.
  • Verify the signature, timestamp and delivery id, confirm with whoami, store encrypted, and only then answer 2xx.
  • Send rows with an Idempotency-Key, act on code, and pin a retry to its key.
  • Renew and rotation keep the old key working until the new one is confirmed. Keep yours until you hear replaced.
  • Hooks see actor: "inbound" and get no token.