Partner API — P1: Foundation and Supply Side

A separate Partner API (/api/partner/v1) lets white-label sites, and later external portals and CRMs, create landlord accounts and manage their properties and listings under per-landlord grants. P1 covers partner identity and keys, account creation with an email-only Claim, consent for existing accounts, the fourteen v1 supply-side operations mirrored per landlord, and admin tooling.

View source markdown ↗ generated by claude-opus-5-5 · diagrams mermaid

Summary

A separate Partner API at /api/partner/v1 lets our white-label sites, and later external portals and CRMs, create landlord accounts and run those landlords' properties and listings under per-landlord grants. The landlord takes the account over through an email-only Claim; existing accounts are linked only with the landlord's consent; nothing is submitted for review before the Claim.

  • Status Design approved; grill review applied 2026-10-03; written spec awaiting review
  • Areas backend/go, backend/bun, apps/rental, apps/panel
  • Decision record ADR-0072 — claim by platform email only, consent for every existing account, claim before submit
  • Consumers First-party white-label sites first; external portals/CRMs without redesign

Why and scope

Our own channels must create landlord accounts and manage those landlords' properties and listings programmatically; later, external portals and CRMs will too. Landlord Rental API v1 (/api/v1/rental) does not fit: there the key is the landlord, built for a landlord's own AI agent. A partner acts for many landlords and must be able to create them. The Partner API is a separate surface with its own contract; it reuses v1's business logic and infrastructure, not its identity model.

Programme

OrderSub-projectDepends on
P1Foundation and supply side (this document)—
P2Property archive / removalP1
P3Agreements, tenancies, payments, handover, contactsP1
—Deferred: enquiries & offers, webhooks, self-serve partner signup, developer portal, partner sandbox/test mode—

P1 alone lets a white-label site onboard landlords, prepare their properties and listings, and submit them for review once the landlord has claimed the account. P2 and P3 add endpoints without changing P1's contract.

Non-goals

  • No change to /api/v1/rental, landlord keys, v1 source acceptance, AuthMiddleware, or legacy rental routes.
  • No enquiries, offers, archive/delete, agreements or money endpoints.
  • No webhooks, bulk endpoints, or listing search on the partner surface.
  • No partner self-serve signup; partners and keys are admin-issued.
  • No Google sign-in on the claim page (password only).
  • No general "forgot password" feature. Password reset stays unwired (Claim section, F4).
  • No new landlord notification for viewing requests; submit-after-claim (D10) removes the need in P1.

Decisions (product owner, 2026-10-03)

Who receives the claim secret? (D9, Q1)

Only platform email. The partner never receives a claim URL, token or expiry; it sees only claimed and may ask for a rate-limited resend. Consent links stay partner-delivered.

A partner holding the link could set the password and hold a full landlord login — chats, offers, signing — far beyond its grant scopes, and the Claim would prove nothing about the email. With email-only delivery, a successful Claim proves inbox ownership and sets emailVerified = true.

Rejected: partner-delivered link (bypasses scopes); partner link plus an emailed code (extra table, email and UI).

Which existing accounts may POST /landlords recover? (D12, Q3)

Only the account this same provisioning attempt created, proven by a stamp written on the user at creation. Every other existing account needs consent — including an abandoned account of another partner.

"No credential and no grant" also matches partner service users, anonymous users, admin-created users and other partners' abandoned accounts. An allowlist ("this attempt created it") cannot grow new holes the way a denylist can, and keeps D4 for every account the partner did not just create.

Rejected: a denylist of passwordless kinds (misses future kinds; cross-partner recovery without consent).

Can a listing be submitted before the Claim? (D10, Q4)

No. Partners may create and edit while unclaimed; submit returns 409 landlord_unclaimed until the Claim. Publication stays admin review.

Landlords get no email for a new viewing request and pending requests never expire, so a live listing for a landlord who cannot sign in strands Seekers. A mistyped email would also carry a live ownership declaration in a stranger's name.

Rejected: keep D10 and add a viewing-request email (new runtime outside P1; wrong-email risk stays); accept unanswerable live listings.

All decisions D1–D14
#Decision
D1Separate Partner API, not an extension of /api/v1/rental. v1 stays the landlord's own surface.
D2First consumers are first-party channels; the contract must admit external portals/CRMs without redesign.
D3A partner-created landlord is a real platform account: they can log in directly (after the Claim) and be connected to other partners.
D4Linking an existing account always requires the landlord's consent. No silent linking for any partner tier.
D5On listing submit the partner makes the ownership declaration for the landlord, recorded as a partner declaration. Partner terms carry the legal responsibility.
D6Architecture A: partner surface in the Go rental module; partner identity and account creation in Bun.
D7The landlord is named in the request path.
D8No test/sandbox mode in P1; partners integrate against UAT.
D9(amended in review, Q1) Claim secrets travel only by platform email. The partner never receives a claim URL, token or expiry; it sees only whether the landlord has claimed, and may ask for a rate-limited resend. Consent links are delivered by the partner. We also email the landlord security notices through the existing rental mailer.
D10(amended in review, Q4) Partners may create and edit for a landlord who has not yet claimed. Submit returns 409 landlord_unclaimed until the Claim. Publication stays the existing admin review; partners never publish directly.
D11Every photo and external ref the partner writes has source = partner.slug; a body source is ignored. This includes single multipart uploads, which v1 leaves unowned. Partner writes set origin_channel = 'partner'.
D12(new in review, Q3) POST /landlords may recover only an account that this same provisioning attempt created, proven by a stamp written at account creation. Every other existing account needs consent, including an abandoned account created by another partner.
D13(new in review) The right to claim belongs to the landlord account (D3). A suspended partner or a revoked grant does not remove it. Partner service users can never claim.
D14(new in review) Revoking a grant keeps the partner's photos and their Source ownership unchanged (ADR-0065).

Architecture

Partner API components: Go owns the partner surface and rental writes; Bun owns keys and every Better Auth account write; the claim secret reaches the landlord only by email
Partner API components: Go owns the partner surface and rental writes; Bun owns keys and every Better Auth account write; the claim secret reaches the landlord only by email.

Bun

identity
  • Partner keys (configId: 'partner')
  • Every Better Auth account write: create the landlord user, link the credential at the Claim, create partner service users

Go

rental module
  • Partners, grants, claim tokens, connect requests
  • The partner HTTP surface
  • All rental writes through the existing use cases — same ownership check and audit logging as a panel or v1 write

What exists (read from the repository)

Facts the design builds on, each cited to the code. Key ones: admin.setUserPassword cannot create a credential; accounts has no unique index on (provider_id, account_id); the app runs Better Auth without transactions; the trigger audit stores no actor.

Full evidence table (§3)
FactWhere
Better Auth api-key plugin with per-configId configs; landlord config has enableSessionForAPIKeys: false, enableMetadata: true, plugin rate limit offbackend/bun/apps/monolith/src/config/di-container.ts:50-67
Plugins installed: anonymous(), admin(), organization(), deviceAuthorization(), apiKey(), bearer(), jwt(); emailAndPassword enabled; Google with accountLinking.trustedProviders: ['google']di-container.ts:224-246,340-342
Better Auth tables are users and accounts; accounts has no unique index on (provider_id, account_id)backend/bun/packages/auth-adapter/schema.ts:14,46-64
Better Auth 1.6.11 admin.createUser without a password creates no accounts row; it accepts extra user fields in datanode_modules/better-auth/dist/plugins/admin/routes.mjs:107-113,129-170
admin.setUserPassword only updates an existing credential row (internalAdapter.updatePassword → UPDATE accounts … WHERE provider_id='credential'); it cannot create oneroutes.mjs:601-636, dist/db/internal-adapter.mjs:517-525
Better Auth resetPassword creates a missing credential row (createAccount with providerId: 'credential', accountId: userId); not wired in this app (no sendResetPassword)dist/api/routes/password.mjs:147-158
OAuth sign-in links to an existing user only if the local user has emailVerified = true (requireLocalEmailVerified defaults to true)dist/oauth2/link-account.mjs:19-28
Drizzle adapter runs without Better Auth transactions unless transaction: true is set; this app does not set it, so adapter.transaction(cb) falls back to running cb without a transaction@better-auth/drizzle-adapter/dist/index.mjs:465-473, @better-auth/core/dist/db/adapter/factory.mjs:402-409, di-container.ts:217-218
@better-auth/core/context exports runWithTransaction(adapter, fn): calls adapter.transaction(trx => …), makes trx the current adapter for fn, and runs queued after-hooks only after the transaction resolves@better-auth/core/dist/context/transaction.mjs:52-77, transaction.d.mts:15-17
Better Auth's internal adapter resolves every read and write through getCurrentAdapter(...); createAccount/updateUser run before hooks inline and queue after hooks with queueAfterTransactionHookbetter-auth/dist/db/internal-adapter.mjs:83-89,495-500,526-527, dist/db/with-hooks.mjs:6-35,43-69
The app's database hooks: user.create.after seeds the auth version; user.update.after acts only on bansdi-container.ts:344-380
API-key validation rejects a key whose configId differs from the config asked for@better-auth/api-key/dist/index.mjs:1635-1638
Public api-key guard blocks create/update/delete of configId: 'landlord' keys via public routesapi-gateway/middleware/public-api-key-guard.middleware.ts:26-111
Internal verify route gated by x-service-secret constant-time compare; hard-requires config_id === 'landlord'api-gateway/routes/internal.routes.ts:63-86,161-164
Go validator sends config_id: "landlord"backend/go/internal/api/http/middleware/better_auth_validator.go:494-496
APIKeyAuthMiddleware sets user_id, roles, api_key_id, api_key_name, actor_type, key_permissions, key_mode, rate_limit_policymiddleware/api_key_auth_middleware.go:104-176
AuditContextMiddleware copies actor type, key id/name, key mode into context; blanks the session id only when actor_type == "api_key"middleware/audit_context.go:74-131
v1 route table: 14 supply-side operations and their key scopes (GET …/photos uses properties:read; no route uses media:read)rental/adapter/inbound/http/v1_routes.go:79-94
v1 mounted at /api/v1/rentalrental/module.go:614-633
Use cases derive origin_channel = 'api' from a non-empty api_key_id in context, and is_test from key_mode == "test"; they do not read actor_type and know no partner valuerental/application/usecase/property.go:139-153
Context getters read request-context values (GetUserIDFromContext → KeyUserID), which only AuditContextMiddleware fills from Echo fields; RequireLandlord reads the Echo field user_rolesmiddleware/audit_context.go:171-175,252-282, rental/adapter/inbound/http/require_landlord.go:26-61
Repository updates write fixed column lists that never include origin_*; origin is set only on createpersistence/postgresql/listing_repository.go:171, property_repository.go:203
ListingUseCase.Submit requires declarationAccepted, a live ownership proof, then stamps the declaration on the propertyrental/application/usecase/listing.go:258-376
Property declaration and origin columns (DeclarationSource, DeclarationAPIKeyID, DeclarationKeyName, OriginChannel, OriginKeyID, OriginKeyName)rental/domain/entity/property.go:24-33, listing.go:57-60
Photo sync requires a caller-supplied source, validated by ^[a-z0-9][a-z0-9_-]{0,31}$rental/adapter/inbound/http/property_handler.go:159-175, domain/entity/property_external_ref.go:27-36
Idempotency rows keyed by (api_key_id, idempotency_key), both TEXT; v1 returns 409 idempotency_conflict on a fingerprint mismatchpersistence/postgresql/idempotency_repository.go:92-123, migrator_rental.go:1436-1446
Business audit: AuditLogger.Record writes audit_log inside the write transaction with user_id and, in details, actor_type, api_key_id, api_key_name, trace_idpersistence/postgresql/audit_logger.go, application/port/ports.go:651-687
Row audit: fn_audit_trail() stores table, operation, row id, old and new row — no actormigrations/migrator.go:95-125 (ADR-0002, ADR-0007)
rental_contacts holds full_name, phone, nric, address_line per usermigrator_rental.go:233-241
Admin review queue item exposes origin_channelrental/application/usecase/admin_queue.go:84
Rental schema migrations; origin_channel and declaration_source have no CHECK constraintinternal/shared/infrastructure/database/postgresql/migrations/migrator_rental.go
Rental outbound email: port.Mailer implemented by EmailMailer over shared email.Sender (Resend), recipient resolved from the Better Auth user row, idempotency keys supportedrental/application/port/ports.go:551, rental/adapter/outbound/mailer/email_mailer.go:23-96, rental/module.go:218-235
No landlord email exists for a new viewing request; pending viewing requests never expireports.go:555-616, usecase/viewing_request.go:511
Landlord self-promotion POST /api/rental/landlord/promote; staff roles are rejectedrental/adapter/inbound/http/landlord_promotion_test.go:118-188
Rental email base URL setting exists only for the panelinternal/shared/infrastructure/config/config.go:47-50,611-612

Identity model

Partner and service user

A row in rental_partners. Each partner has a service user in Better Auth: role partner, no credential, email partner+{slug}@partners.invalid (provisional domain; .invalid is reserved and never delivers). Partner keys are owned by that service user, so the existing validator path (ValidateAPIKey → identity.UserID) is reused; Go maps service_user_id → partner.

Partner keys

  • Better Auth configId: 'partner', prefix grp_, enableSessionForAPIKeys: false, enableMetadata: true, rateLimit.enabled: false (Go's limiter is the only one, as for landlord).
  • Issued only by an admin through Bun POST /api/admin/partners/:partnerId/keys (admin role required). Bun sets configId and referenceId on the server — referenceId is the partner's service user, read from rental_partners — and ignores any such fields in the body. List: GET; revoke: DELETE /api/admin/partners/:partnerId/keys/:keyId.
  • public-api-key-guard.middleware.ts blocks configId: 'partner' on public create/update/delete exactly as it blocks landlord.
  • Key permissions are the partner's ceiling. Scope names are fixed (table below) and mirror v1's route scopes (v1_routes.go:79-94). There is no media:read: listing photos is properties:read, as in v1.
  • Per-key hourly allowance and KeyRateLimitMiddleware reused unchanged. One key's allowance covers all landlords that partner serves.
  • Partner keys carry no mode. Partner rows are always live (is_test = false).
ResourceActions
landlordsread, write (partner-level only, never in a grant)
propertiesread, write
listingsread, write
mediawrite
proofsread, write

Grant

A row in rental_partner_grants: one landlord's permission for one partner to act for them, with a set of scopes. Effective permission = key ceiling ∩ grant scopes. Grant scopes use the names above minus landlords:*. grant_type records how the grant was last given: created (the partner created the account) or connected (the landlord approved a connect request). It is not called source — that word is the feed (CONTEXT.md › Source).

Request pipeline

Partner-level routes: WithV1ErrorRenderer → PartnerKeyAuth → KeyRateLimit → AuditContext → RequireKeyScope(scope) → handler. Per-landlord routes add RequireGrant(scope) after RequireKeyScope.

Partner request pipeline. RequireGrant runs after AuditContext and enriches both Echo fields and the request context before the handler
Partner request pipeline. RequireGrant runs after AuditContext and enriches both Echo fields and the request context before the handler.
  1. PartnerKeyAuth (new, internal/api/http/middleware)

    Reads x-api-key, calls ValidateAPIKey with config_id: "partner", resolves the partner by service_user_id, refuses status = suspended with 403 partner_suspended. Sets partner_id, partner_slug, api_key_id, api_key_name, key_permissions, rate_limit_policy, actor_type = "partner". It does not set user_id.

  2. AuditContextMiddleware (changed)

    Copies partner_id from the Echo field into request context under a new KeyPartnerID, and treats actor_type = "partner" like "api_key": no generated session id (audit_context.go:122-130). It runs before RequireGrant, so on partner routes it puts no user_id into request context.

  3. RequireGrant(scope) (new, rental inbound HTTP)

    Loads the active grant for (partner_id, {landlord_id}) and checks the scope. Missing grant, revoked grant, or missing scope → 404 landlord_not_found. On success it enriches both places the code reads from, before the handler runs:

    • Echo fields: user_id = landlord_id, user_roles = ["landlord"], grant_id — read by handlers and RequireLandlord;
    • request context: a derived context with KeyUserID = landlord_id and a new KeyGrantID, installed with c.SetRequest(c.Request().WithContext(ctx)) — read by use cases, AuditLogger.Record and the context getters (audit_context.go:252-282). KeyActorType, KeyAPIKeyID, KeyAPIKeyName, KeyPartnerID and the trace id are already there from AuditContextMiddleware.

    So every business write on a per-landlord route sees the landlord as subject and the partner as actor. Partner-level routes have no landlord subject; their audit rows name the landlord explicitly in the entry.

  4. Handlers

    Call the existing use cases with ownerUserID = landlord_id. A property or listing owned by someone else surfaces as the existing concealed 404 property_not_found / listing_not_found.

API surface

Base path /api/partner/v1. Spec file backend/go/openapi/partner-v1.yaml (x-api-key header scheme). Mounted from rental/module.go beside v1, on its own prefixed group.

Partner-level routes

Method and pathScopeResult
GET /me—{ id, name, slug, tier, permissions, rate_limit }
POST /landlordslandlords:writeCreate a landlord. 201 new, 200 replay by partner_landlord_ref
GET /landlordslandlords:readActive grants, paginated (v1 pagination shape); ?partner_landlord_ref= filter
GET /landlords/{landlord_id}landlords:read{ landlord_id, partner_landlord_ref, scopes, claimed, grant_type, name, phone, created_at }
POST /landlords/{landlord_id}/claim-email (provisional path)landlords:writeClaim-email resend. 202; 409 already_claimed; 429 rate_limited
DELETE /landlords/{landlord_id}/grantlandlords:writePartner releases the grant; 204
POST /connect-requestslandlords:writeConnect an existing landlord. 201 { id, approve_url, expires_at, status }
GET /connect-requests/{id}landlords:read{ id, status, landlord_id?, partner_landlord_ref, scopes, expires_at }

/landlords/{landlord_id} routes require an active grant (any scope) and otherwise return 404 landlord_not_found.

Per-landlord routes (mirror of v1's fourteen operations)

All under /landlords/{landlord_id}. Request and response bodies are the v1 bodies, same field names. Scopes match v1 line for line.

Method and pathScopeNote
GET /propertiesproperties:read
POST /propertiesproperties:write
GET /properties/{id}properties:read
PUT /properties/{id}properties:write
GET /properties/{id}/photosproperties:read
POST /properties/{id}/photosmedia:writeSingle upload; owned by the partner slug (D11; v1 leaves it unowned)
PUT /properties/{id}/photosmedia:writeGallery sync; Source = partner slug; governs the partner's single uploads too
POST /properties/{id}/proofsproofs:write
GET /properties/{id}/proofsproofs:read
GET /listings/{id}listings:read
POST /listingslistings:write
PUT /listings/{id}listings:write
POST /listings/{id}/submitlistings:write409 landlord_unclaimed until the Claim (D10)
POST /listings/{id}/withdrawlistings:write

Contract differences from v1

Topicv1Partner v1
Identitykey = landlordkey = partner; landlord from path, must be granted
source (external refs, gallery sync)caller-chosenalways partner.slug; a body source is ignored
Single photo uploadunownedowned by partner.slug
origin_channel on createsapipartner (+ origin_partner_id)
Submit declarationdeclaration_source = 'api'declaration_source = 'partner'
Submit precondition—landlord has claimed, else 409 landlord_unclaimed
Idempotency-Key scopeper keyper key + landlord
No grantn/a404 landlord_not_found
Test modekey_mode = testnone in P1; partner keys carry no mode

Shared and reused: the error envelope and V1ErrorRenderer, pagination shape, X-Request-ID / X-Trace-ID, the rate limiter, idempotency storage, and the 404 concealment rule.

Attribution and idempotency (no use-case signature change)

Origin
Today the use cases read only api_key_id and key_mode from context and know no partner value (property.go:139-153). Planned: a new branch reads actor_type and partner_id from request context; when actor_type = "partner" it sets origin_channel = 'partner', origin_partner_id, origin_key_id, origin_key_name. Without it, partner rows would be stamped api. Other callers behave as before. Signatures do not change. Origin stays write-once: repository updates never write origin_*.
Declaration
Submit records declaration_source = 'partner', declaration_api_key_id, declaration_key_name, declared IP = request IP.
Idempotency
Rows stay keyed by (api_key_id, idempotency_key). Partner routes store the key as {landlord_id}:{Idempotency-Key}. Landlord ids are Better Auth generated ids with no :, so the first : splits the value unambiguously, and partner key ids never collide with landlord key ids. No schema change. A replay with a different body → 409 idempotency_conflict (v1 behaviour).

Create a new landlord

POST /api/partner/v1/landlords

{ "email": "a@b.com", "name": "Aisha Tan", "phone": "+60123456789",
  "partner_landlord_ref": "crm-8812", "scopes": ["properties:write", "listings:write"] }

email, name, partner_landlord_ref required. scopes optional; default and upper bound is the key ceiling minus landlords:*. An unknown scope or one outside the ceiling → 400 validation_failed with fields: ["scopes"].

Account creation and recovery. Only the account stamped by this exact attempt is recovered; every other existing account goes through consent
Account creation and recovery. Only the account stamped by this exact attempt is recovered; every other existing account goes through consent.
  1. Replay check

    A grant of this partner with this partner_landlord_ref and status active or provisioning:

    • stored requested_email or scope set differs from the request → 409 idempotency_conflict. Name and phone are not compared and a replay never changes contact data;
    • active → return it with 200. No email is sent; the partner uses the resend route if needed;
    • provisioning → resume at step 3 with the same row.
  2. Reservation

    Insert a grant with status = provisioning, grant_type = created, requested_email (lower-cased), partner_landlord_ref, scopes, landlord_user_id = NULL. The partial unique index on requested_email WHERE status = 'provisioning' makes this atomic; there is no check-then-insert. On conflict with an existing reservation:

    • same partner → 409 landlord_exists (its own in-flight attempt under another ref);
    • another partner, younger than 24 hours → 409 landlord_exists, Bun not called;
    • another partner, older than 24 hours → that reservation is abandoned: delete it with a conditional delete (id = ? AND created_at < now() - 24h) and retry the insert once. A reservation is never deleted unless another partner collides with it, so its owner can resume it at any time.
  3. Account

    Call Bun POST /api/internal/partner/landlords (x-service-secret) with { email, name, provisioning_id: <grant id> }:

    • email free → admin.createUser with role landlord, no password, emailVerified = false, and data.partnerProvisioningId = provisioning_id; returns { user_id, created: true };
    • email taken → returns { user_id, created: false, provisioning_id } with the stamp stored on that user (or null). Bun reports facts; Go decides.
  4. Outcome
    • created, or the returned stamp equals this row's id (recovery of this attempt's own account after a crash or timeout) → in one transaction: set landlord_user_id, status = active; upsert rental_contacts full_name and phone only; issue a claim token; write business audit rows. After commit, send the claim email. Return 201 (or 200 on a recovered replay).
    • anything else (no stamp, another attempt's stamp, a service user) → delete the reservation; return 409 landlord_exists. The partner uses the connect flow; the landlord consents.
  5. Bun unreachable

    503 auth_unavailable; the reservation stays and a retry with the same partner_landlord_ref resumes.

Response 201:

{ "landlord_id": "…", "partner_landlord_ref": "crm-8812", "claimed": false,
  "grant_type": "created", "scopes": ["properties:write", "listings:write"] }

Before the Claim, the partner may create, edit, upload, and withdraw for the landlord. Submit returns 409 landlord_unclaimed (D10).

Claim

The Claim is the moment a partner-created landlord proves they own the email and sets a password. There is one claim path. Three triggers issue a claim token, and all send the same email:

TriggerWhoNotes
Account created or recoveredCreate-landlord outcome step
ResendPartner, POST /landlords/{id}/claim-email409 already_claimed once claimed
Setup emailSigned-out visitor on a connect pageGeneric answer always
Eligible account
A token is issued only for a user who is not claimed, not a service user, role landlord, and stamped with a partnerProvisioningId. Grant state and partner state do not matter (D13).
Claimed
The landlord has at least one Better Auth accounts row (credential or OAuth). Go reads it through a read-only query on accounts, alongside its existing users reads (ADR-0006). It says the account can sign in; it does not say which password, if any, a given request set.
Token
32 random bytes, base64url, stored as SHA-256. Valid 7 days (design value). In the email only, as https://<rental-app>/claim/{token}.
Token states
unused → in_progress → used, or unused → superseded. An in_progress token returns to unused only on a definite no-write. Expiry is expires_at; Go checks it when a claim begins, and Bun checks it again at the authorization point.
Serialization
Every issue, begin, and finish step runs in a Go transaction that first takes a transaction-scoped advisory lock keyed on the landlord id, so issuing a token and starting a claim for the same landlord never interleave. Issuing marks only unused tokens superseded; it never touches an in_progress token, so a resend cannot invalidate a claim whose result is still unknown.
Claim token states. Every finish or release update is conditional on the lease generation captured at begin; expired tokens can never begin again
Claim token states. Every finish or release update is conditional on the lease generation captured at begin; expired tokens can never begin again.

Claim request

The rental app page /claim/{token} calls GET /api/rental/claims/{token} (partner name and state, no session), then posts { password } to POST /api/rental/claims/{token} (no session).

Claim sequence: Go begin, Bun link in one locked Better Auth transaction, Go finish
Claim sequence: Go begin, Bun link in one locked Better Auth transaction, Go finish.
  1. Begin (Go, locked)

    The token must be unused, or in_progress with its lease older than 60 s (provisional; at least twice Go's Bun call timeout), and must not be expired. If the landlord is already claimed → mark the token used (used_at set, attempt_started_at NULL), return 409 already_claimed. Otherwise set in_progress and a new attempt_started_at, commit, and keep that value as this attempt's lease generation. Taking over an expired lease is conditional on the old value (… WHERE attempt_started_at = <old>) and writes a value greater than it. A token inside a live lease → 409 claim_in_progress.

  2. Link (Bun POST /api/internal/partner/landlords/{id}/credential, x-service-secret, body { password, not_after: <token expires_at> })

    Before any lock, Bun refuses a service user (forbidden), checks the password against Better Auth's length policy (400), and hashes it with Better Auth's hasher ((await auth.$context).password.hash). Hashing is slow and needs no lock.

    Then one transaction, one connection. The route builds a route-local Better Auth DBAdapter whose transaction(cb) opens one Drizzle transaction on the app's existing db, takes pg_advisory_xact_lock(<key of user id>) on it, and passes cb an adapter bound to that same transaction (drizzleAdapter(tx, { provider: 'pg', schema })(auth.options)) — the same binding the Drizzle adapter's own transaction: true path makes (drizzle-adapter/dist/index.mjs:465-473). The route calls runWithTransaction(localAdapter, fn) from @better-auth/core/context. Inside fn, Better Auth's internal adapter resolves the transaction adapter through getCurrentAdapter, so every step runs on the locked transaction:

    1. read the user's accounts (internalAdapter.findAccounts). Any row → return has_account. No identity write happens: no account, no password, no emailVerified change;
    2. authorization point: in the same transaction, compare clock_timestamp() with not_after (clock_timestamp(), not now(): now() is the transaction start time, before the lock wait). Past it → return expired, nothing written;
    3. internalAdapter.createAccount({ userId, providerId: 'credential', accountId: userId, password: hash }) (userId is required by the accounts schema, user_id NOT NULL) and internalAdapter.updateUser(userId, { emailVerified: true }) — the calls resetPassword makes → linked.

    Any error rolls back the lock, the read, the credential row and the verification flag together. Better Auth before hooks run inside the transaction; after hooks are queued and run only after commit (transaction.mjs, with-hooks.mjs). Nothing changes globally: the app's auth instance keeps transaction: false; only this route uses the local adapter. No raw writes to users or accounts (Bun AGENTS.md). The lock makes "read, then create" safe although accounts has no unique index.

  3. Finish (Go, locked)

    Applies the outcome table below, conditional on the lease generation.

Bun outcomeGo actionResponse
linkedtoken used (used_at set, attempt_started_at NULL); other unused tokens superseded; audit row204
has_accounttoken used (used_at set, attempt_started_at NULL); other unused tokens superseded409 already_claimed
expiredtoken stays as is; it can never write again410 claim_link_invalid
Definite no-write (forbidden, password-policy 400, connection refused before the request was sent)token back to unused with attempt_started_at NULL (if not expired)400 with the reason, or 503 auth_unavailable
Ambiguous (timeout, broken connection, 5xx)token stays in_progress503 auth_unavailable

Within the Partner API, only the linked outcome sets emailVerified = true: the Claim proves email ownership (Q1). This is also what keeps Google linking off an unclaimed account (link-account.mjs).

Rate limits (provisional)
Per landlord, shared by resend and setup email: at most 1 token per 10 minutes and 5 per 24 hours, counted from rental_partner_claim_tokens.created_at. Over the limit: partner resend → 429 rate_limited; setup email → the same generic 202, nothing sent.
Other account-creation paths
Admin tools or other supported Better Auth paths can also create credentials. The Claim does not assume it is the only writer; it only refuses to write when any account row exists.

Connect an existing landlord

POST /api/partner/v1/connect-requests

{ "partner_landlord_ref": "crm-9001", "scopes": ["properties:write"],
  "redirect_uri": "https://site.example/partner/callback" }
  • scopes required: known names, no landlords:*, all inside the calling key's ceiling; else 400 validation_failed with fields: ["scopes"].
  • redirect_uri must exactly match an entry in rental_partners.redirect_uris, else 400 invalid_redirect_uri.
  • The request names no email; whoever signs in approves for their own account, so this flow never reveals whether an account exists.
  • Token in approve_url (https://<rental-app>/connect/{token}) is single-use, stored hashed, valid 24 hours (design value). The partner delivers this link.
  1. Sign-in required

    The sign-in redirect returns only to this same-origin path.

  2. Signed out and no password yet? Setup email

    The sign-in step offers "First time? Get a set-up email" (provisional copy). It posts { email } to POST /api/rental/connect/{token}/setup-email (provisional path), no session. A dead connect token → 410 connect_link_invalid. Otherwise the answer is always 202 with the same "check your inbox" message — for an unknown, claimed, ineligible, or eligible email alike. Only an eligible account within limits gets the claim email. This is not a general "forgot password": it needs a live connect link and reaches only unclaimed partner-created accounts (D3, D4). After the Claim, the landlord opens the partner's link again and signs in.

  3. Show the request

    GET /api/rental/connect/{token} → partner name, tier, requested scopes. The page says the scopes cover all of the landlord's properties and that the partner will see their name and phone.

  4. Approve — POST /api/rental/connect/{token}/approve, one transaction
    • request must be pending and not expired (conditional update); else 410 connect_link_invalid — single use under replay and concurrent clicks;
    • partner suspended → 403 partner_suspended, request stays pending;
    • approver is a service user → 403; not a landlord → the existing promotion rule first (staff roles refused with 403);
    • create the grant, or reactivate this partner's row for this landlord, with the request's scopes and partner_landlord_ref, grant_type = connected;
    • partner_landlord_ref already used by this partner's active grant for a different landlord → 409 shown on the page; nothing changes and the request stays pending;
    • mark the request approved with landlord_user_id; audit row.

    After commit: send NotifyPartnerConnected; redirect to redirect_uri with connect_request_id and status=approved added to its query. If the URI is no longer on the allowlist, the approval stands and the page shows "You can return to {partner}" without redirecting.

  5. Decline — POST /api/rental/connect/{token}/decline

    Same conditional update → declined; redirect with status=declined under the same rule.

A landlord already granted to this partner who approves again gets the scopes and partner_landlord_ref replaced by the new request's. A revoked grant is reactivated on the same row. The claim and consent pages send Referrer-Policy: no-referrer, since their URLs carry tokens.

The partner polls GET /connect-requests/{id}: pending | approved | declined | expired. expired is derived on read when pending and past expires_at, and written back on that read. Another partner's request → 404 connect_request_not_found.

Revocation

Landlord

rental app
  • Connected apps page
  • GET /api/rental/landlord/connected-apps (partner name, scopes, since, grant_type)
  • DELETE /api/rental/landlord/connected-apps/{grant_id}

Partner

API
  • DELETE /api/partner/v1/landlords/{id}/grant

Admin

suspend only
  • Suspending a partner blocks all its keys and approvals
  • Grants and landlords' claim rights are untouched (D13)
  • No admin grant revoke in P1

Revoke is one conditional update: UPDATE … SET status = 'revoked', revoked_by, revoked_at WHERE id = ? AND status = 'active' RETURNING …. Only the request that wins sends NotifyPartnerRevoked; a concurrent second revoke changes nothing and sends nothing (landlord route 204, partner route 404 landlord_not_found). The next partner request for that landlord → 404 landlord_not_found.

Landlord notifications (D9)

New port.Mailer methods in email_mailer.go. Each is sent after the transaction that caused it commits, with an idempotency key.

MethodWhenKeyContent
NotifyPartnerClaimEvery token issue (create/recover, resend, setup email)rental:partner-claim:{token_id}Partner name created an account for you; claim link and its expiry; "Not you? Ignore this email or contact support."
NotifyPartnerConnectedConnect approverental:partner-connected:{grant_id}:{connect_request_id}Partner name now manages the listed scopes; link to Connected apps
NotifyPartnerRevokedWinning revokerental:partner-revoked:{grant_id}:{revoked_at}Partner name no longer has access; who revoked

The claim key is per token, so each resend is a new email; a {grant_id} key would have been dropped as a duplicate. A mailer error is logged and does not fail the API call; the database change is the source of truth. A partner whose landlord got no email uses resend.

Source and slug (D11)

  • The partner slug must match the Source rule ^[a-z0-9][a-z0-9_-]{0,31}$, enforced by a CHECK. It is set at partner creation and never changes, so it survives key rotation; PATCH does not accept it.
  • At partner creation the admin API warns if the slug is already used as a Source on any photo or external ref. The panel shows the warning; the admin may proceed.
  • Single uploads are owned (D11). A partner POST …/photos stores source = partner.slug. This is a partner-surface exception to ADR-0065's "a single multipart API upload is unowned", which still holds for v1 and the panel. Following ADR-0065's ownership rule: the partner's own gallery PUT governs these photos too, so a PUT that omits one removes it; they sit in the partner's ordered block; and they are read-only in the panel. A partner that uploads one by one and also syncs must list those uploads in its PUT.
  • v1 is unchanged: it still accepts any valid Source.

Data model

All Go tables in migrator_rental.go.

rental_partners

id              UUID PK
name            TEXT NOT NULL
slug            TEXT NOT NULL UNIQUE CHECK (slug ~ '^[a-z0-9][a-z0-9_-]{0,31}$')
tier            TEXT NOT NULL CHECK (tier IN ('first_party','external'))
status          TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active','suspended'))
service_user_id TEXT NOT NULL UNIQUE
redirect_uris   TEXT[] NOT NULL DEFAULT '{}'
created_at, updated_at

rental_partner_grants

id                   UUID PK
partner_id           UUID NOT NULL REFERENCES rental_partners
landlord_user_id     TEXT NULL
requested_email      TEXT NULL            -- lower-cased
partner_landlord_ref TEXT NOT NULL
scopes               TEXT[] NOT NULL
status               TEXT NOT NULL CHECK (status IN ('provisioning','active','revoked'))
grant_type           TEXT NOT NULL CHECK (grant_type IN ('created','connected'))
revoked_by           TEXT NULL CHECK (revoked_by IN ('landlord','partner'))
revoked_at           TIMESTAMPTZ NULL
created_at, updated_at

CHECK ((status = 'provisioning') = (landlord_user_id IS NULL))
CHECK ((status = 'revoked') = (revoked_at IS NOT NULL AND revoked_by IS NOT NULL))
CHECK (grant_type = 'connected' OR requested_email IS NOT NULL)
UNIQUE (partner_id, landlord_user_id)                          -- NULLs distinct
UNIQUE (partner_id, partner_landlord_ref) WHERE status <> 'revoked'
UNIQUE (requested_email) WHERE status = 'provisioning'         -- the reservation

A grant's id is also the provisioning stamp on the Bun user. Re-granting reactivates the existing (partner_id, landlord_user_id) row; history lives in the audit trails.

rental_partner_claim_tokens

id                 UUID PK
token_hash         TEXT NOT NULL UNIQUE
landlord_user_id   TEXT NOT NULL
partner_id         UUID NULL REFERENCES rental_partners          -- named in the email
grant_id           UUID NULL REFERENCES rental_partner_grants    -- which grant asked, if any
state              TEXT NOT NULL DEFAULT 'unused'
                   CHECK (state IN ('unused','in_progress','used','superseded'))
attempt_started_at TIMESTAMPTZ NULL
expires_at         TIMESTAMPTZ NOT NULL
used_at            TIMESTAMPTZ NULL
created_at

CHECK ((state = 'in_progress') = (attempt_started_at IS NOT NULL))
CHECK ((state = 'used') = (used_at IS NOT NULL))
INDEX (landlord_user_id, created_at)   -- limits and supersede

The token belongs to the account, not the grant, so a revoked grant or suspended partner does not void it (D13).

rental_partner_connect_requests

id                   UUID PK
partner_id           UUID NOT NULL REFERENCES rental_partners
token_hash           TEXT NOT NULL UNIQUE
partner_landlord_ref TEXT NOT NULL
scopes               TEXT[] NOT NULL
redirect_uri         TEXT NOT NULL
status               TEXT NOT NULL DEFAULT 'pending'
                     CHECK (status IN ('pending','approved','declined','expired'))
landlord_user_id     TEXT NULL
expires_at           TIMESTAMPTZ NOT NULL
created_at, updated_at

CHECK ((status = 'approved') = (landlord_user_id IS NOT NULL))

Changes to existing tables

  • rental_properties, rental_listings: add origin_partner_id UUID NULL REFERENCES rental_partners, written on create only.
  • origin_channel gains the value partner (no CHECK exists today).
  • Better Auth users (Bun schema, packages/auth-adapter/schema.ts): add partner_provisioning_id TEXT NULL, declared as a Better Auth user.additionalFields entry with input: false, so public sign-up cannot set it. It is a Gremlin-specific field written only through admin.createUser's data (Bun AGENTS.md).
  • Better Auth api-key config partner.

Audit

Two audit systems, two different guarantees (ADR-0007):

Business audit (audit_log) — request actor

Written inside the same transaction as the change (ports.go:685-687). On partner routes user_id is the landlord (the subject) and details carries actor_type = 'partner', partner_id, api_key_id, api_key_name, trace_id. AuditLogger.Record adds partner_id from context when present. Grant, connect-request, claim-token, and Claim changes write business audit rows too; landlord-initiated ones carry actor_type = 'user' and the partner_id concerned.

Row audit (audit_trails, ADR-0002) — row history

The four new tables get fn_audit_trail() triggers. This is row-change history only. It stores no request actor, so it is not evidence of who sent a request; actor facts appear there only as row data (origin_*, declaration_*, revoked_by).

Order per write: business change and business audit commit together; emails go after commit; Bun account writes (create-landlord account step, Claim link step) happen between Go transactions, never inside one.

Admin

Go — /api/rental/admin/partners
Existing admin group and role check. GET list, GET /{id}, PATCH /{id} (name, status, redirect_uris; never slug). POST create: calls Bun internal POST /api/internal/partner/service-users (idempotent by the service user's email, so a retry after a failed insert returns the same user), then inserts the row, returning the Source-collision warning. GET /{id}/grants: read-only grant list (landlord id, ref, scopes, status, grant_type, claimed, dates).
Bun — /api/admin/partners/:partnerId/keys
Admin session: issue, list, revoke partner keys.
Panel — frontend/solidstart/apps/panel
Partners list and detail — create (with the slug warning), suspend/reactivate, edit redirect URIs, issue/list/revoke keys (raw key shown once), list grants (read-only).
Review queue
admin_queue.go item gains partner_name (nullable). The panel shows a Partner badge with the name and "Declared by partner {name}" when declaration_source = 'partner'.

Errors

Envelope and renderer from v1. v1 codes keep their meaning (invalid_api_key, key_disabled, key_expired, rate_limited, validation_failed, insufficient_permission, idempotency_conflict, property_not_found, listing_not_found, media_unavailable, internal_error, …).

Partner API codes

CodeStatusWhen
partner_suspended403Partner status = suspended (any partner route)
landlord_not_found404No active grant, revoked grant, or grant lacks the scope
landlord_exists409POST /landlords: email belongs to an account this attempt did not create, or is reserved by another attempt. No extra error data; already-granted landlords are found with GET /landlords?partner_landlord_ref=
landlord_unclaimed409Submit before the Claim (D10)
already_claimed409Claim-email resend for a claimed landlord
idempotency_conflict409(reused) POST /landlords replay with a different email or scope set; any Idempotency-Key replay with a different body
rate_limited429(reused) key allowance, or claim-email resend over the limit
connect_request_not_found404Unknown or another partner's connect request
invalid_redirect_uri400redirect_uri not on the allowlist
auth_unavailable503Bun unreachable during key verification or account calls

Missing key ceiling scope → 403 insufficient_permission (the partner's own key; nothing to conceal). Missing grant scope → 404 landlord_not_found.

Rental app route codes

Claim, setup email, consent and connected-apps routes use the rental module's existing session-route error shape.

CodeStatusWhen
claim_link_invalid410Unknown, superseded, used, or expired claim token
claim_in_progress409Same token inside a live lease
already_claimed409Account already has a sign-in method
connect_link_invalid410Unknown, decided, or expired connect token
partner_suspended403Approve for a suspended partner
forbidden403Service user or staff approver
auth_unavailable503Claim outcome unknown or Bun unreachable

Known risks

Testing

Integration suites run on the disposable pg-test database (:55432).

Contract table
Pattern of contract_table_test.go: every partner route, status and response keys; no partner response contains a claim URL, token, or expiry.
OpenAPI drift
Pattern of openapi_drift_test.go: partner-v1.yaml matches mounted routes and the scope table, the x-api-key scheme, and the error code table.
Authorization
No grant / revoked grant / missing grant scope → 404; missing key scope → 403; suspended partner → 403; landlord key on partner routes → 401; partner key on v1 and legacy routes → 401; partner A cannot read or act on partner B's grants, connect requests, or photo source.
Provisioning
Create then replay with same ref → same landlord; replay with a different email or scopes → 409 idempotency_conflict; existing account without this attempt's stamp → 409; crash after Bun create, retry → recovered by stamp; two partners create the same email concurrently → one reservation wins, the other gets 409; another partner's reservation older than 24 h → removed and the newcomer gets 409 from the stamp check; a service user's or anonymous user's email → 409; Bun outage → 503 then successful retry.
Claim
Two concurrent claims on one token → one credential row; claims on two tokens of one landlord → one credential row; a resend during an in_progress claim does not supersede it; ambiguous Bun result then retry → already_claimed, password not rewritten; a request reaching the authorization point after not_after writes nothing; a failure after createAccount rolls back both the credential row and emailVerified; has_account makes no identity write (emailVerified unchanged); after hooks run only after commit; expired in_progress token → 410; definite no-write → token usable again; emailVerified true after claim and false before; claimed landlord can sign in; revoked grant and suspended partner still allow the Claim; service user never gets a token; resend limits → 429.
Setup email
Generic 202 for unknown, claimed, ineligible and eligible emails; only the eligible one is mailed; dead connect token → 410.
Submit
Unclaimed → 409 landlord_unclaimed; after the Claim → normal submit into admin review.
Consent
Approve, decline, expire; replayed or concurrent approve → one wins, other 410; scopes outside the key ceiling → 400; suspended partner on approve → 403; redirect allowlist; non-landlord approver promoted; staff and service-user approvers refused; re-grant after revoke reactivates the same row with new scopes and ref; ref clash → 409, request stays pending.
Revocation
Two concurrent revokes → one state change, one email; synced and single-upload photos keep their Source after revoke.
Photos
A partner single upload stores source = partner.slug and is read-only in the panel; the partner's gallery PUT that omits it removes it; a v1 single upload stays unowned; a body source on partner routes is ignored.
Attribution
Partner creates store origin_channel = 'partner', origin_partner_id; updates do not change origin; submit stores declaration_source = 'partner'; business audit rows carry actor_type = 'partner', partner_id, and user_id = landlord (read from request context after RequireGrant); partner requests get no generated session id.
Idempotency
The same Idempotency-Key under two landlords of one partner does not collide.
Notifications
Each method sent once per event; each resend sends a new claim email; mailer failure does not fail the API call.
Bun
partner config verifies only partner keys; public guard blocks partner key create/update/delete; admin key routes require admin and ignore body configId/referenceId; internal partner endpoints reject missing or wrong x-service-secret; partner_provisioning_id cannot be set by public sign-up.
Frontend
Claim, setup email, consent, Connected apps (rental app) and Partners (panel) exercised in the browser with ego per frontend/AGENTS.md.

Review decisions (grill, 2026-10-03)

#QuestionDecisionRejected
Q1Who receives the claim secret?Platform email only; partner sees claimed and can resend (D9). emailVerified set only by a successful Claim.Partner-delivered link (partner could set the password and hold a full landlord login beyond its scopes); partner link plus emailed code (extra table, email and UI).
Q1bHow is the credential created?Bun links the credential and sets emailVerified through Better Auth's internal adapter, in one locked transaction via runWithTransaction and a route-local transaction-bound adapter.admin.setUserPassword: only updates an existing row. Lock on one connection with adapter writes on another: not atomic. Raw SQL writes: skip Better Auth hooks. Global transaction: true: changes auth behaviour app-wide.
Q2How does an unclaimed landlord approve another partner?Setup email from the connect page, generic answer, same claim path and limits. landlord_exists keeps its contract; no ids in the error.General forgot-password (second claim path that skips the guard); keep the dead end.
Q3Which existing accounts may POST /landlords recover?Only the one this attempt stamped (D12).Denylist of passwordless kinds (misses future kinds; cross-partner recovery without consent).
Q4Can a listing be submitted before the Claim?No: 409 landlord_unclaimed (D10).Keep D10 and add a viewing-request email (new runtime outside P1; wrong-email risk stays); accept unanswerable live listings.
F1Concurrent createsPartial unique reservation index; atomic conflict handling; stale-reservation cleanup only on collision.Check-then-insert.
F2OriginActor-aware branch in use cases; signatures unchanged.
F3Idempotency{landlord_id}:{key} under the partner key id.
F4Password resetNot wired in P1; any future reset must respect the Claim.
G4Revocation racesAtomic active → revoked; one email; in-flight window documented.
G6Source collisionsImmutable validated slug; collision warning at creation; v1 unchanged.Blocking the slug in v1 (changes v1; a landlord may use it on purpose).
G7Photos after revokeOwnership kept (D14).Releasing ownership on revoke.
D11Partner single uploadsOwned by the partner slug, as D11 states; v1 unchanged.Leaving them unowned as in v1 (narrows D11).

Related decision records: ADR-0072 (new — claim by platform email, consent for existing accounts, claim before submit), ADR-0065 (source-scoped gallery ownership, with the partner single-upload exception), ADR-0002 and ADR-0007 (audit trails), ADR-0006 (Go reads Better Auth tables read-only).

Implementation settings

  • Add RENTAL_APP_BASE_URL beside RENTAL_PANEL_BASE_URL on cfg.RentalEmail (config.go:47-50,611-612), default http://localhost:3003 (the rental app dev port, apps/rental/vite.config.ts:21). It builds claim_url (email only) and approve_url.
  • claim token TTL Claim email link lifetime design value 7 d
  • connect token TTL approve_url lifetime design value 24 h
  • claim lease At least twice Go's Bun call timeout provisional 60 s
  • claim email limit Per landlord, resend and setup shared provisional 1 / 10 min
  • claim email limit Per landlord, resend and setup shared provisional 5 / 24 h
  • stale reservation Another partner's provisioning row counts as abandoned after 24 h

Other provisional values: service-user email domain partners.invalid; route paths …/claim-email and …/setup-email; page copy.