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.
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.
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
| Order | Sub-project | Depends on |
|---|---|---|
| P1 | Foundation and supply side (this document) | — |
| P2 | Property archive / removal | P1 |
| P3 | Agreements, tenancies, payments, handover, contacts | P1 |
| — | 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, v1sourceacceptance,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 |
|---|---|
| D1 | Separate Partner API, not an extension of /api/v1/rental. v1 stays the landlord's own surface. |
| D2 | First consumers are first-party channels; the contract must admit external portals/CRMs without redesign. |
| D3 | A partner-created landlord is a real platform account: they can log in directly (after the Claim) and be connected to other partners. |
| D4 | Linking an existing account always requires the landlord's consent. No silent linking for any partner tier. |
| D5 | On listing submit the partner makes the ownership declaration for the landlord, recorded as a partner declaration. Partner terms carry the legal responsibility. |
| D6 | Architecture A: partner surface in the Go rental module; partner identity and account creation in Bun. |
| D7 | The landlord is named in the request path. |
| D8 | No 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. |
| D11 | Every 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
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)
| Fact | Where |
|---|---|
Better Auth api-key plugin with per-configId configs; landlord config has enableSessionForAPIKeys: false, enableMetadata: true, plugin rate limit off | backend/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 data | node_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 one | routes.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 queueAfterTransactionHook | better-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 bans | di-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 routes | api-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_policy | middleware/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/rental | rental/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 value | rental/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_roles | middleware/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 create | persistence/postgresql/listing_repository.go:171, property_repository.go:203 |
ListingUseCase.Submit requires declarationAccepted, a live ownership proof, then stamps the declaration on the property | rental/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 mismatch | persistence/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_id | persistence/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 actor | migrations/migrator.go:95-125 (ADR-0002, ADR-0007) |
rental_contacts holds full_name, phone, nric, address_line per user | migrator_rental.go:233-241 |
Admin review queue item exposes origin_channel | rental/application/usecase/admin_queue.go:84 |
Rental schema migrations; origin_channel and declaration_source have no CHECK constraint | internal/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 supported | rental/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 expire | ports.go:555-616, usecase/viewing_request.go:511 |
Landlord self-promotion POST /api/rental/landlord/promote; staff roles are rejected | rental/adapter/inbound/http/landlord_promotion_test.go:118-188 |
| Rental email base URL setting exists only for the panel | internal/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', prefixgrp_,enableSessionForAPIKeys: false,enableMetadata: true,rateLimit.enabled: false(Go's limiter is the only one, as forlandlord). - Issued only by an admin through Bun
POST /api/admin/partners/:partnerId/keys(admin role required). Bun setsconfigIdandreferenceIdon the server —referenceIdis the partner's service user, read fromrental_partners— and ignores any such fields in the body. List:GET; revoke:DELETE /api/admin/partners/:partnerId/keys/:keyId. public-api-key-guard.middleware.tsblocksconfigId: 'partner'on public create/update/delete exactly as it blockslandlord.- Key
permissionsare the partner's ceiling. Scope names are fixed (table below) and mirror v1's route scopes (v1_routes.go:79-94). There is nomedia:read: listing photos isproperties:read, as in v1. - Per-key hourly allowance and
KeyRateLimitMiddlewarereused unchanged. One key's allowance covers all landlords that partner serves. - Partner keys carry no mode. Partner rows are always live (
is_test = false).
| Resource | Actions |
|---|---|
landlords | read, write (partner-level only, never in a grant) |
properties | read, write |
listings | read, write |
media | write |
proofs | read, 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.
-
PartnerKeyAuth(new,internal/api/http/middleware)Reads
x-api-key, callsValidateAPIKeywithconfig_id: "partner", resolves the partner byservice_user_id, refusesstatus = suspendedwith403 partner_suspended. Setspartner_id,partner_slug,api_key_id,api_key_name,key_permissions,rate_limit_policy,actor_type = "partner". It does not setuser_id. -
AuditContextMiddleware(changed)Copies
partner_idfrom the Echo field into request context under a newKeyPartnerID, and treatsactor_type = "partner"like"api_key": no generated session id (audit_context.go:122-130). It runs beforeRequireGrant, so on partner routes it puts nouser_idinto request context. -
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 andRequireLandlord; - request context: a derived context with
KeyUserID = landlord_idand a newKeyGrantID, installed withc.SetRequest(c.Request().WithContext(ctx))— read by use cases,AuditLogger.Recordand the context getters (audit_context.go:252-282).KeyActorType,KeyAPIKeyID,KeyAPIKeyName,KeyPartnerIDand the trace id are already there fromAuditContextMiddleware.
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.
- Echo fields:
-
Handlers
Call the existing use cases with
ownerUserID = landlord_id. A property or listing owned by someone else surfaces as the existing concealed404 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 path | Scope | Result |
|---|---|---|
GET /me | — | { id, name, slug, tier, permissions, rate_limit } |
POST /landlords | landlords:write | Create a landlord. 201 new, 200 replay by partner_landlord_ref |
GET /landlords | landlords:read | Active 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:write | Claim-email resend. 202; 409 already_claimed; 429 rate_limited |
DELETE /landlords/{landlord_id}/grant | landlords:write | Partner releases the grant; 204 |
POST /connect-requests | landlords:write | Connect 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 path | Scope | Note |
|---|---|---|
GET /properties | properties:read | |
POST /properties | properties:write | |
GET /properties/{id} | properties:read | |
PUT /properties/{id} | properties:write | |
GET /properties/{id}/photos | properties:read | |
POST /properties/{id}/photos | media:write | Single upload; owned by the partner slug (D11; v1 leaves it unowned) |
PUT /properties/{id}/photos | media:write | Gallery sync; Source = partner slug; governs the partner's single uploads too |
POST /properties/{id}/proofs | proofs:write | |
GET /properties/{id}/proofs | proofs:read | |
GET /listings/{id} | listings:read | |
POST /listings | listings:write | |
PUT /listings/{id} | listings:write | |
POST /listings/{id}/submit | listings:write | 409 landlord_unclaimed until the Claim (D10) |
POST /listings/{id}/withdraw | listings:write |
Contract differences from v1
| Topic | v1 | Partner v1 |
|---|---|---|
| Identity | key = landlord | key = partner; landlord from path, must be granted |
source (external refs, gallery sync) | caller-chosen | always partner.slug; a body source is ignored |
| Single photo upload | unowned | owned by partner.slug |
origin_channel on creates | api | partner (+ origin_partner_id) |
| Submit declaration | declaration_source = 'api' | declaration_source = 'partner' |
| Submit precondition | — | landlord has claimed, else 409 landlord_unclaimed |
Idempotency-Key scope | per key | per key + landlord |
| No grant | n/a | 404 landlord_not_found |
| Test mode | key_mode = test | none 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_idandkey_modefrom context and know nopartnervalue (property.go:139-153). Planned: a new branch readsactor_typeandpartner_idfrom request context; whenactor_type = "partner"it setsorigin_channel = 'partner',origin_partner_id,origin_key_id,origin_key_name. Without it, partner rows would be stampedapi. Other callers behave as before. Signatures do not change. Origin stays write-once: repository updates never writeorigin_*. - 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"].
-
Replay check
A grant of this partner with this
partner_landlord_refand statusactiveorprovisioning:- stored
requested_emailor 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 with200. No email is sent; the partner uses the resend route if needed;provisioning→ resume at step 3 with the same row.
- stored
-
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 onrequested_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.
- same partner →
-
Account
Call Bun
POST /api/internal/partner/landlords(x-service-secret) with{ email, name, provisioning_id: <grant id> }:- email free →
admin.createUserwith rolelandlord, no password,emailVerified = false, anddata.partnerProvisioningId = provisioning_id; returns{ user_id, created: true }; - email taken → returns
{ user_id, created: false, provisioning_id }with the stamp stored on that user (ornull). Bun reports facts; Go decides.
- email free →
-
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: setlandlord_user_id,status = active; upsertrental_contactsfull_nameandphoneonly; issue a claim token; write business audit rows. After commit, send the claim email. Return201(or200on 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.
-
Bun unreachable
503 auth_unavailable; the reservation stays and a retry with the samepartner_landlord_refresumes.
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:
| Trigger | Who | Notes |
|---|---|---|
| Account created or recovered | Create-landlord outcome step | |
| Resend | Partner, POST /landlords/{id}/claim-email | 409 already_claimed once claimed |
| Setup email | Signed-out visitor on a connect page | Generic 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 apartnerProvisioningId. Grant state and partner state do not matter (D13). - Claimed
- The landlord has at least one Better Auth
accountsrow (credential or OAuth). Go reads it through a read-only query onaccounts, alongside its existingusersreads (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, orunused → superseded. Anin_progresstoken returns tounusedonly on a definite no-write. Expiry isexpires_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
unusedtokenssuperseded; it never touches anin_progresstoken, so a resend cannot invalidate a claim whose result is still unknown.
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).
-
Begin (Go, locked)
The token must be
unused, orin_progresswith 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 tokenused(used_atset,attempt_started_atNULL), return409 already_claimed. Otherwise setin_progressand a newattempt_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. -
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
DBAdapterwhosetransaction(cb)opens one Drizzle transaction on the app's existingdb, takespg_advisory_xact_lock(<key of user id>)on it, and passescban adapter bound to that same transaction (drizzleAdapter(tx, { provider: 'pg', schema })(auth.options)) — the same binding the Drizzle adapter's owntransaction: truepath makes (drizzle-adapter/dist/index.mjs:465-473). The route callsrunWithTransaction(localAdapter, fn)from@better-auth/core/context. Insidefn, Better Auth's internal adapter resolves the transaction adapter throughgetCurrentAdapter, so every step runs on the locked transaction:- read the user's
accounts(internalAdapter.findAccounts). Any row → returnhas_account. No identity write happens: no account, no password, noemailVerifiedchange; - authorization point: in the same transaction, compare
clock_timestamp()withnot_after(clock_timestamp(), notnow():now()is the transaction start time, before the lock wait). Past it → returnexpired, nothing written; internalAdapter.createAccount({ userId, providerId: 'credential', accountId: userId, password: hash })(userIdis required by theaccountsschema,user_id NOT NULL) andinternalAdapter.updateUser(userId, { emailVerified: true })— the callsresetPasswordmakes →linked.
Any error rolls back the lock, the read, the credential row and the verification flag together. Better Auth
beforehooks run inside the transaction;afterhooks are queued and run only after commit (transaction.mjs,with-hooks.mjs). Nothing changes globally: the app'sauthinstance keepstransaction: false; only this route uses the local adapter. No raw writes tousersoraccounts(Bun AGENTS.md). The lock makes "read, then create" safe althoughaccountshas no unique index. - read the user's
-
Finish (Go, locked)
Applies the outcome table below, conditional on the lease generation.
| Bun outcome | Go action | Response |
|---|---|---|
linked | token used (used_at set, attempt_started_at NULL); other unused tokens superseded; audit row | 204 |
has_account | token used (used_at set, attempt_started_at NULL); other unused tokens superseded | 409 already_claimed |
expired | token stays as is; it can never write again | 410 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_progress | 503 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 generic202, 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" }
scopesrequired: known names, nolandlords:*, all inside the calling key's ceiling; else400 validation_failedwithfields: ["scopes"].redirect_urimust exactly match an entry inrental_partners.redirect_uris, else400 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.
Rental app /connect/{token}
-
Sign-in required
The sign-in redirect returns only to this same-origin path.
-
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 }toPOST /api/rental/connect/{token}/setup-email(provisional path), no session. A dead connect token →410 connect_link_invalid. Otherwise the answer is always202with 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. -
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. -
Approve —
POST /api/rental/connect/{token}/approve, one transaction- request must be
pendingand not expired (conditional update); else410 connect_link_invalid— single use under replay and concurrent clicks; - partner
suspended→403 partner_suspended, request stayspending; - approver is a service user →
403; not a landlord → the existing promotion rule first (staff roles refused with403); - 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_refalready used by this partner's active grant for a different landlord →409shown on the page; nothing changes and the request stayspending;- mark the request
approvedwithlandlord_user_id; audit row.
After commit: send
NotifyPartnerConnected; redirect toredirect_uriwithconnect_request_idandstatus=approvedadded 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. - request must be
-
Decline —
POST /api/rental/connect/{token}/declineSame conditional update →
declined; redirect withstatus=declinedunder 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
APIDELETE /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.
| Method | When | Key | Content |
|---|---|---|---|
NotifyPartnerClaim | Every 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." |
NotifyPartnerConnected | Connect approve | rental:partner-connected:{grant_id}:{connect_request_id} | Partner name now manages the listed scopes; link to Connected apps |
NotifyPartnerRevoked | Winning revoke | rental: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;PATCHdoes 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 …/photosstoressource = 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: addorigin_partner_id UUID NULL REFERENCES rental_partners, written on create only.origin_channelgains the valuepartner(no CHECK exists today).- Better Auth
users(Bun schema,packages/auth-adapter/schema.ts): addpartner_provisioning_id TEXT NULL, declared as a Better Authuser.additionalFieldsentry withinput: false, so public sign-up cannot set it. It is a Gremlin-specific field written only throughadmin.createUser'sdata(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.
GETlist,GET /{id},PATCH /{id}(name,status,redirect_uris; neverslug).POSTcreate: calls Bun internalPOST /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.goitem gainspartner_name(nullable). The panel shows a Partner badge with the name and "Declared by partner {name}" whendeclaration_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
| Code | Status | When |
|---|---|---|
partner_suspended | 403 | Partner status = suspended (any partner route) |
landlord_not_found | 404 | No active grant, revoked grant, or grant lacks the scope |
landlord_exists | 409 | POST /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_unclaimed | 409 | Submit before the Claim (D10) |
already_claimed | 409 | Claim-email resend for a claimed landlord |
idempotency_conflict | 409 | (reused) POST /landlords replay with a different email or scope set; any Idempotency-Key replay with a different body |
rate_limited | 429 | (reused) key allowance, or claim-email resend over the limit |
connect_request_not_found | 404 | Unknown or another partner's connect request |
invalid_redirect_uri | 400 | redirect_uri not on the allowlist |
auth_unavailable | 503 | Bun 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.
| Code | Status | When |
|---|---|---|
claim_link_invalid | 410 | Unknown, superseded, used, or expired claim token |
claim_in_progress | 409 | Same token inside a live lease |
already_claimed | 409 | Account already has a sign-in method |
connect_link_invalid | 410 | Unknown, decided, or expired connect token |
partner_suspended | 403 | Approve for a suspended partner |
forbidden | 403 | Service user or staff approver |
auth_unavailable | 503 | Claim 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.yamlmatches mounted routes and the scope table, thex-api-keyscheme, 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_progressclaim does not supersede it; ambiguous Bun result then retry →already_claimed, password not rewritten; a request reaching the authorization point afternot_afterwrites nothing; a failure aftercreateAccountrolls back both the credential row andemailVerified;has_accountmakes no identity write (emailVerifiedunchanged);afterhooks run only after commit; expiredin_progresstoken → 410; definite no-write → token usable again;emailVerifiedtrue 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
202for 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.slugand is read-only in the panel; the partner's gallery PUT that omits it removes it; a v1 single upload stays unowned; a bodysourceon partner routes is ignored. - Attribution
- Partner creates store
origin_channel = 'partner',origin_partner_id; updates do not change origin; submit storesdeclaration_source = 'partner'; business audit rows carryactor_type = 'partner',partner_id, anduser_id= landlord (read from request context afterRequireGrant); partner requests get no generated session id. - Idempotency
- The same
Idempotency-Keyunder 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
partnerconfig verifies only partner keys; public guard blocks partner key create/update/delete; admin key routes require admin and ignore bodyconfigId/referenceId; internal partner endpoints reject missing or wrongx-service-secret;partner_provisioning_idcannot be set by public sign-up.- Frontend
- Claim, setup email, consent, Connected apps (rental app) and Partners (panel) exercised in the browser with
egoperfrontend/AGENTS.md.
Review decisions (grill, 2026-10-03)
| # | Question | Decision | Rejected |
|---|---|---|---|
| Q1 | Who 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). |
| Q1b | How 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. |
| Q2 | How 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. |
| Q3 | Which 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). |
| Q4 | Can 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. |
| F1 | Concurrent creates | Partial unique reservation index; atomic conflict handling; stale-reservation cleanup only on collision. | Check-then-insert. |
| F2 | Origin | Actor-aware branch in use cases; signatures unchanged. | |
| F3 | Idempotency | {landlord_id}:{key} under the partner key id. | |
| F4 | Password reset | Not wired in P1; any future reset must respect the Claim. | |
| G4 | Revocation races | Atomic active → revoked; one email; in-flight window documented. | |
| G6 | Source collisions | Immutable validated slug; collision warning at creation; v1 unchanged. | Blocking the slug in v1 (changes v1; a landlord may use it on purpose). |
| G7 | Photos after revoke | Ownership kept (D14). | Releasing ownership on revoke. |
| D11 | Partner single uploads | Owned 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_URLbesideRENTAL_PANEL_BASE_URLoncfg.RentalEmail(config.go:47-50,611-612), defaulthttp://localhost:3003(the rental app dev port,apps/rental/vite.config.ts:21). It buildsclaim_url(email only) andapprove_url.
-
claim token TTLClaim email link lifetime design value 7 d -
connect token TTLapprove_urllifetime design value 24 h -
claim leaseAt least twice Go's Bun call timeout provisional 60 s -
claim email limitPer landlord, resend and setup shared provisional 1 / 10 min -
claim email limitPer landlord, resend and setup shared provisional 5 / 24 h -
stale reservationAnother 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.