中文版

Partner API — Enquiry and Offer Webhooks

Authorised partners receive signed, minimal notifications for viewing requests, thread messages and offers, then fetch current details through the existing Partner API. Transactional capture, frozen consent and enrollment references, fresh key authority and bounded HTTPS delivery preserve privacy and prevent delayed work from following newly granted access.

  • Predecessor Partner API foundation, shared landlord scope/consent primitives, and the enquiries-and-offers API contract
  • Status Approved

View source markdown ↗ generated by openai-codex/gpt-6.1-sol · diagrams mermaid

Summary

Authorised partners receive signed notifications when viewing requests, messages or offers change, then fetch current details through the existing Partner API. A Go transactional outbox captures every eligible business occurrence; a background worker delivers only while the original enrollment, consent and current read access remain valid.

  • AudienceExisting managed partners
  • SurfaceExisting partner admin detail page
  • CaptureGo + PostgreSQL transaction
  • AuthorityBun key metadata + landlord consent

Success is an atomic durable capture, signed minimal delivery outside the business request, bounded retries, partner event-ID deduplication and an authorised API fetch. Landlord consent, key ceilings, live-mode isolation and the partner-created-property boundary remain mandatory. Notifications cover tenants, landlords, partners (including their own actions) and automation; they are not an audit feed or event-time snapshots.

Decisions and tradeoffs

DecisionLocked-in choice
Scope and payloadEnquiries and offers only; minimal versioned identifiers, API reads for details.
Actor coverageAll actors, including the subscribing partner and automated business changes.
ConfigurationOne admin-managed callback per partner; no event filters.
AccessDesignated enquiries:read key, current landlord read consent and existing resource visibility.
DeliveryGo worker with bounded at-least-once attempts, public HTTPS, HMAC-SHA256 and encrypted secrets.
Recovery and inspectionAutomatic retries only; terminal work never revives. Recent outcomes retained for 30 days; pending/leased work protected.

Durable capture without a new broker

Use PostgreSQL transactional outbox records and a bounded Go worker.

The mutation and event commit together, avoiding lost notifications between commit and enqueue without operating another messaging service.

Rejected: post-commit enqueue (crash-loss gap); outbox plus external broker (additional service and operational burden). The rental email queue is not the ledger: NotificationEventRepository.Enqueue deduplicates by subject type, subject ID, kind and recipient, while repeated business occurrences need distinct IDs. Bun’s in-memory event bus is not durable capture for Go mutations.

Foundations and dependencies

Depends on Partner API foundation, shared landlord scope/consent primitives and the enquiries-and-offers design with its backend/frontend OpenSpec changes. Planning artifacts do not prove those prerequisites are implemented. Reuse their delivered scope/visibility interfaces and non-goals; offers remain read-only on the Partner API.

Observed integration boundaries and exact code references
States and messages
backend/go/internal/modules/rental/domain/entity/viewing_request.go defines viewing states/transitions and thread messages; offer.go defines offer states/transitions and terms.
Mutation ownership
backend/go/internal/modules/rental/application/usecase/viewing_request.go owns request creation/actions and ordinary messages; WithTx already accepts the rental transaction runner for creation. Persisted system messages and bulk business-change paths are also in scope; HTTP-only hooks are insufficient.
Partner scope
backend/go/internal/modules/rental/adapter/inbound/http/partner_routes.go combines partner authentication, key ceilings, grants and live landlord scope.
Key authority
backend/go/internal/api/http/middleware/better_auth_validator.go delegates key verification to Bun, never reading hashes or the API-key table directly. backend/bun/apps/monolith/src/api-gateway/routes/admin-partner-keys.routes.ts owns partner-key administration and sanitised metadata; use the internal boundary, not duplicate Better Auth ownership.
Secret encryption
backend/go/internal/shared/infrastructure/crypto/aes_gcm.go supplies shared AES-256-GCM.
Network safety
backend/go/internal/shared/infrastructure/safefetch/dial.go supplies public-address checks, checked-IP dialing and proxy-free transport. Reuse its dial policy, not the image-fetch wrapper in fetch.go.

Public event contract

EventResourceCapture trigger
viewing_request.createdviewing_requestA new viewing request persists.
viewing_request.updatedviewing_requestBusiness state or proposed/confirmed times change, even without a status change.
message.createdmessageAn ordinary, initial or system-generated thread message persists.
offer.createdofferA new offer persists.
offer.updatedofferStatus or terms change, even without a status change.

One event per changed resource occurrence, not per HTTP request: a request plus initial message emits two creation events; a viewing action plus system message emits an update and a message event. Bulk operations emit only for actually changed resources. No new transitions or message generation are introduced.

Immutable envelope

Each callback is one UTF-8 JSON object, serialized once and stored as exact bytes for every attempt. Never rebuild it from current state or add attempt-specific body fields.

FieldContract
idUnique event UUID, assigned once and unchanged across retries.
typeOne of the five event names above.
schema_versionInteger 1.
occurred_atUTC RFC 3339 time recorded with the mutation; not send time or an ordering sequence.
landlord_idExisting Partner API landlord user identifier, as a string.
resource.typeviewing_request, message or offer, consistent with type.
resource.idExisting resource identifier, as a string.
resource.viewing_request_idRequired parent for message/offer; omitted for a viewing request.

Exclude tenant identifiers, names, contacts, message bodies, viewing times, offer terms, actor details, internal routing fields and authorisation revisions. Partners fetch viewing/offer detail or the appropriate message thread; there is no new single-message endpoint.

Configuration and authorisation

Each partner has one HTTPS endpoint, enabled state, designated API-key ID and signing secret. The key must belong to that partner, be active/unexpired and permit enquiry reads; write-only authority is insufficient. A monotonic configuration generation identifies enrollment: enable/disable, URL changes, rebinding and rotation invalidate older work. Reusing a URL or key never revives it.

Durable capture never waits for Bun inside the transaction. A frozen candidate is not yet a deliverable callback; current authority must qualify it again before each send
Durable capture never waits for Bun inside the transaction. A frozen candidate is not yet a deliverable callback; current authority must qualify it again before each send.

Capture an active partner, enabled endpoint and active read grant using property origin, landlord and live-mode boundaries. Store endpoint generation, designated key ID, grant ID and grant revision. Never attach a newly enabled enrollment or newly approved grant to an older event. Only eligible candidates become deliveries; definitive denial completes suppression without outbound I/O, while temporary lookup failure leaves durable work due.

Access gates before every attempt

Four narrowing read gates: partner key, landlord consent, live partner-origin resource scope, and message thread membership. Partner key Landlord consent Live origin scope Thread membership
All applicable gates intersect; none replaces another. Message membership adds the captured parent thread. Before these gates, the endpoint must still be enabled with the captured generation/key binding and the partner must be active.
  1. Endpoint enabled, matching captured generation and designated key.
  2. Active partner; fresh Bun-authorised same-partner key, active/unexpired, with enquiries:read.
  3. Captured grant active, with enquiries:read and the identical consent revision.
  4. Resource readable under explicit landlord/live/partner-created-property scope; messages belong to the captured parent thread.

No new webhook consent scope, all-properties grant, write-implies-read or unrestricted-reader fallback. Archived history uses existing enquiry visibility, not a blanket archive exclusion.

Bun returns only key ID/owner/configuration, permissions, enabled state and expiry over an authenticated internal lookup. Distinguish definitive missing/invalid/foreign/non-partner-config keys from service failure. Go receives/stores no raw token/hash and never queries Better Auth tables; background lookups neither impersonate ordinary API-key traffic nor consume request quota.

Persistence and atomicity

Rental-owned recordStored data
EndpointPartner, URL, key ID, enabled state, generation, encrypted secret ciphertext/nonce and normal timestamps.
OutboxEvent ID/type/time, exact payload bytes, resource/landlord/parent visibility identifiers, frozen audience enrollment/consent references, routing outcome and timestamps.
DeliveryEvent/enrollment reference; pending, in-flight, delivered, failed or suppressed state; attempt count; last/next attempt times; lease token/expiry; last HTTP status; sanitised reason and terminal timestamp.

Uniqueness on event/enrollment prevents duplicate deliveries on routing retry. The immutable event UUID is occurrence identity—not a resource/type natural key. Diagnostics belong on the delivery; no separate analytics or response-body store.

Extend the existing rental transaction runner/repository set only as needed to commit selected changes and outbox inserts together. Cover initial and system messages, scheduled transitions and bulk updates alongside ordinary use cases. Outbox persistence failure must roll back the business mutation; no after-commit capture or swallowed enqueue error.

Transport and signature

Public HTTPS only

  • HTTPS POST, verified certificates, absolute URL with host, 10-second total timeout. Reject embedded credentials and fragments.
  • No redirects, API credentials, cookies, environment proxies or disabled TLS verification.
  • Validate hostname on configuration and public addresses on connection. Block private, loopback, link-local, other disallowed addresses and mixed public/private DNS.
  • Dial the checked IP without a second hostname resolution, preserving hostname/certificate verification. Reuse cannot bypass validated endpoint/generation; new connections use the guarded dialer.
  • Use safefetch.Dialer, not the image-fetch API/redirect policy. Controlled test resolvers/transports are allowed; shipped private-network/TLS bypasses are not.
  • Inspect status only; bound any response draining and close the response. Never store/log response bodies, URL credentials, cookies or signing material.

Exact-byte signing contract

Content type
Content-Type: application/json
Event identity
Webhook-Id: envelope event UUID.
Attempt time
Webhook-Timestamp: decimal Unix seconds for this attempt.
Signature
Webhook-Signature: v1=<lowercase hexadecimal HMAC-SHA256 digest>
Signed bytes
Raw 32-byte secret over <timestamp>.<exact JSON body>; timestamp matches the header. Retries preserve body/ID and refresh time/signature.
  1. Verify before accepting. Decode the base64 secret; compare HMAC in constant time; require matching header/body IDs and a timestamp within five minutes of the receiver clock. Both sides need working UTC clocks.
  2. Deduplicate durably. Use the event ID; the same event may arrive again after a lost acknowledgement or worker crash.
  3. Acknowledge durable acceptance. Return success only after durable acceptance; business processing can continue asynchronously afterwards.

Signing secret lifecycle

Generate 32 cryptographically random bytes and disclose their base64 encoding once on creation or rotation. Encrypt raw bytes using shared AES-256-GCM with fresh nonces and a wrapping key configured through backend secret/configuration mechanisms.

Ordinary reads expose secret presence only. No signing values in URLs, logs/audit, diagnostics or history; audit the admin action/actor without recording the secret. Rotation immediately replaces the secret while disabled: no dual-secret overlap and no reveal endpoint.

Worker, retries and outcomes

Sweep
Every five seconds, bounded batches and concurrency; callback I/O holds no transaction.
Claim
60-second lease with unique token; expiry permits recovery and completion must match the current token, rejecting stale workers.
Deadline
24 hours from occurred_at, including routing/authority outages; never extended.
Attempt ceiling
Eight outbound attempts maximum; first eligible committed work sends when picked up.
Retry delay lengths proportional to time: 30 seconds, 2 minutes, 10 minutes, 1 hour, 3 hours, 6 hours and 12 hours. Retry 1 · 30s Retry 2 · 2m Retry 3 · 10m Retry 4 · 1h Retry 5 · 3h Retry 6 · 6h Retry 7 · 12h 0h12h
Uneven retry delays share one time scale: 30 seconds, 2 minutes, 10 minutes, 1 hour, 3 hours, 6 hours, 12 hours. Each delay begins at the preceding attempt’s completion, not at event capture. Attempt exhaustion or 24-hour age expiry fails the work, whichever comes first; these are fixed policy values.
Observed outcomeResult
Any 2xxTerminal delivered; ignore response content.
Timeout, transient network failure, 408, 429, 5xxRetry within attempt/age limits.
Other 4xx or any 3xxTerminal failed; never follow redirects.
Unsafe destinationTerminal failed without opening the blocked connection.
Definitive access/enrollment lossTerminal suppressed without sending.
Temporary authority/database failureDefer the check 30 seconds; no outbound attempt consumed, original deadline still applies.

Durably increment the attempt count before sender invocation—including DNS/connect/response failures—so a crash never resets the ceiling. Local eligibility-service failures do not count. Pending work expiring before its first send fails with an expiry reason.

Terminal states do not return to pending. Claim tokens reject stale completion, but a lost acknowledgement can still lead to another accepted delivery; access is rechecked before sending
Terminal states do not return to pending. Claim tokens reject stale completion, but a lost acknowledgement can still lead to another accepted delivery; access is rechecked before sending.

Admin lifecycle and retention

Add a webhook section to the existing partner detail page using its admin permissions, styling, localisation, key selection and request conventions—not a new dashboard or portal.

  1. Save disabled configuration. Validate HTTPS URL and select an active, unexpired, same-partner read-capable key.
  2. Disclose once. Generate/store the secret, display its base64 encoding once; the endpoint starts disabled.
  3. Install, then enable explicitly. Share the secret with the partner and enable only when its receiver is ready.
  4. Disable before changing enrollment. URL edits, key rebinding and rotation require disablement. Rotate/share/install, then explicitly re-enable.

Safe paginated history

Scope recent history to the partner and bound/paginate it. Show event type/ID, status, outbound attempt count, creation/last-attempt/terminal times, pending next-retry time, last HTTP status and sanitised failure/suppression reason. Never show response bodies or secrets. No redelivery button, synthetic test events or analytics.

Terminal retention

Retain terminal records for 30 days from their terminal timestamp. Safely remove terminal delivery/routing records and unreferenced immutable events; protect pending, leased and still-referenced work. No-audience events receive a terminal routing outcome rather than accumulating forever. Retention is separate from the 24-hour deadline and does not change endpoint configuration or audit policy.

Ownership and delivery boundaries

Go rental backend

Atomic capture, endpoint/admin APIs, candidate/delivery persistence, worker/leases/retries, access checks, signing, guarded transport, retention and backend proof. Reuse rental ports/adapters and module lifecycle; no standalone webhook service.

Bun authority

Authoritative partner-key metadata through existing authenticated internal-listener conventions: owner, configuration, permissions, enabled state and expiry. No public webhook management or raw-key sharing.

Panel and documentation

Endpoint/key form, secret disclosure, explicit lifecycle actions, warnings and recent history. Document envelope, signing, acknowledgement/deduplication, retry/expiry, consent/origin boundaries, onboarding/rotation and reconciliation.

Verification and acceptance

Permanent coverage tests consumer-visible behaviour, boundaries, transitions and errors—not source strings, copied scope arrays, helper forwarding or UI wording.

  1. Capture. Prove all five types across all actors, initial/system messages and bulk changes; resource/outbox atomic commit and forced-outbox-failure rollback. Replays, no-ops, bookkeeping, rejected and rolled-back writes emit nothing.
  2. Audience/consent. Own-partner live resources enroll; wrong landlord/mode/origin, missing read consent or disabled/unconfigured endpoints do not. New endpoints/grants never acquire older events.
  3. Current access. Foreign, write-only, expired, disabled or missing keys cannot send. Grant replacement/revocation, key loss, generation change and invisible resource suppress pending work permanently. Scoped readers enforce resource/thread membership.
  4. Bun isolation. Authenticated internal lookups return no token/hash; foreign/non-partner-config keys reject. Outages leave mutations committed and events deferred, never grant access or consume attempts.
  5. Security. Verify an actual signature over exact bytes; detect tampering, ID mismatch, stale timestamps and duplicate processing. Exercise TLS, refused redirects, private/mixed DNS, rebinding, proxy disablement and bounded responses using controlled transports/resolvers.
  6. Delivery. Deterministic clocks and persisted state prove schedule, eight-attempt ceiling, 24-hour expiry, classification, concurrent claims, crash recovery, stale-token rejection and accepted-before-crash duplicates.
  7. Lifecycle/history. Verify encryption/tamper handling and one-time disclosure; reads/logs/history never reveal secrets. Disable/rotate/rebind invalidate old work. Thirty-day cleanup removes only terminal/unreferenced data, never pending/leased work.
  8. Browser proof. Exercise actual panel form, key selection, disclosure, controls/warnings and paginated history at normal/narrow widths using the approved browser workflow; verify representative rendered localisation without wording-only tests.
  9. Runtime proof. With a real approved read grant and receiver, trigger an enquiry change, observe signed HTTPS receipt and authorised API fetch, demonstrate transient retry, then revoke access before a pending send and observe suppression. Inspect persisted outcomes, not mock forwarding.
  10. Regression/docs. Preserve rental workflows, v1/Partner privacy/idempotency and admin/Bun auth. Document five types/fields, exact signature bytes/headers, deduplication/acknowledgement, bounded failure, disabled-interval reconciliation and access limits.

Risks, non-goals and review gate

  • Lost acknowledgements yield duplicates: receiver deduplication is mandatory.
  • Consent revisions/enrollment cutoffs prevent old work following new permissions or URLs; active state alone is insufficient.
  • Cross-service authority outages defer durable work; Go must not bypass Bun by reading Better Auth tables.
  • Disable/rotate suppress old work and lose interval notifications; API reconciliation is intentional.
  • Bulk/system-message mutations need atomic capture; HTTP-only hooks miss coverage.
  • Fresh access checks cannot retract in-flight sends or disclosed identifiers; minimal payloads reduce, not remove, risk.
  • Long receiver/worker/authority outages exhaust fixed retries or age bounds; history exposes failure, not a hidden eventual-delivery promise.
  • Wrapping-key configuration and a functioning receiver are prerequisites to enablement; no plaintext/unsigned fallback.

Explicit non-goals

Developer portal/self-service; property/listing/tenancy/payment/handover event families; full resource snapshots; actor suppression; event filters; multiple or per-landlord endpoints; private callbacks; TLS bypass; external broker; strict ordering; exactly-once delivery; historical backfill/replay; manual redelivery; synthetic test tooling; analytics dashboards; new offer writes; unrelated refactoring.