Skip to content

Поточний код, міграція та самоперевірка ​

Історичний проєкт

Ця сторінка фіксує попередній проєкт, а не поточний стан випуску. Підготовка ресурсів, scoped authorization і trusted MCP уже реалізовані в комітах Agentfy; див. контракт серверного чату та межі доказів. Браузерні/BONSITE протоколи й ширші пропозиції щодо оплати/життєвого циклу зберігають власні умови випуску. Бойовий запуск партнера не мається на увазі.

Факти поточного коду ​

Скорочені шляхи від api/src/slices/, якщо повний префікс api/ не вказано; прочитані в checkout AGNT2-424. Не плутати потрібні зміни з наявною поведінкою.

Поточний доказНаслідок / міграція
api/src/slices/user/user/user.prisma: required unique email, optional password, platformRoleCredential-independent actor; nullable/non-applicable email для partner без fake addresses; direct credential uniqueness лишається
user/auth/domain/auth.types.ts: email в IAuthUser/JWT, union access/refresh/sessionScoped principal/source/audience, version DTO/SDK; не розширити global guard одним type
user/auth/domain/auth.service.ts: email-stub claim, new team, foundingDedicated credential-only/link/bootstrap; без stub takeover/extra team/partner founder; exclude external actors from founding
user/auth/guards/jwtAuth.guard.ts: signature/type, sub/email requestState revocation, explicit endpoint opt-in; account/platform/financial-consent лише direct proof
user/auth/domain/auth.service.ts: refresh type + user lookup, new tokensPersisted rotating families/source/epoch/version/reuse detection; нині цього немає
user/team/domain/team.service.ts: separate team/key, seat, provisioningTransactional allocation gateway + durable outbox; поточний метод не atomic
user/team/domain/teamProvision.port.ts: handler errors logged/swallowedPersist readiness/retry; signup success не доводить concierge readiness
user/userTeam/userTeam.prisma, domain/userTeam.service.ts: unique actor/team, several owners, count before writeRole — source ownership; lock/transaction last-owner/transfer/inactive actor
agent/agent/agent.prisma: Agent(ownerId, teamId) FK→UserTeam(userId, teamId)Stable IDs; reassign або retain inactive membership/stop jobs
billing/{subscription,invoice,payment,paymentMethod}/*.prisma: team scope, invoice unique subscription/period, cascadePayer timeline/retained invoice lines, без переносу history/subscriptions; remove financial cascade risk
billing/invoice/domain/invoice.service.ts, billing/payment/domain/payment.service.ts: invoice on completed paymentPayPal subscription flow не usage-invoicing; certify consent/cancel/callbacks обох modes
system/usage/meter/meter.prisma: frozen costUsdPico, no resource FK, rollupsPreserve ledger/precision; historical commercial attribution events/aggregates перед payer switches

Розміщення за CleanSlice ​

Прочитано MCP get-started, list-categories, виконано пошуки cross-slice authentication/organization і transactions/idempotency/billing, прочитано docs/architecture/dependency-flow.md. Другий пошук не знайшов transaction guide: транзакція тут — явна пропозиція, не вигадане правило MCP. Додаткові обмеження — шари і constitution.

Organization/identity/membership — singular user-group slices, user auth owns browser/link contexts. Billing L6 координує provisioning user allocation L2 + payer state через domain gateway, data implementation якого тримає спільну local transaction. План має визначити цей boundary, не назвати незалежні service calls атомарними. Agent L5 споживає durable operation через downward contracts; remote effects поза транзакцією.

System usage L1 не імпортує user/billing: upper consumers передають immutable attribution через lower-layer domain ports/snapshots; stale snapshots перевіряються до paid dispatch. Domain без Prisma; DTO validation — presentation, persistence/mapping — data, cross-slice — aliases/barrels. Prisma sources/SDK змінюються лише під час реалізації, не цього docs task.

Expand, backfill, gate, contract ​

ФазаУмова переходу
1. Expand, flags вимкненіOrg/external/link/session/operation/outbox/payer tables; compatible direct auth, partner default deny
2. BackfillExisting IDs/owners/plans/payments/subscriptions unchanged; teams→Agentfy; attribution лише з evidence, ambiguous history quarantined
3. Auth/allocationNo-email end-to-end, dual proof, endpoint opt-in, versioned lifecycle sync, atomic bootstrap/owner guard; executable A cases
4. BillingОбидва v1 modes, provider consent/cutover/reconciliation, retention, hard budget, sponsorship; без paid pilot до passing
5. PilotTest namespace потім limited production; measured cancellation/lease, serializers, EN/RU/UK UX/recovery
6. ContractRetire legacy email assumptions після old clients/tokens і compatible rollback readers

Окремі flags для provisioning, browser/link, paid billing. Rollback зупиняє issuance/paid dispatch, зберігає actors/links/tombstones/ledger/assignments; committed outbox/provider effects reconciled idempotently. Старі binaries, що не розуміють no-email actor, небезпечні після їх появи: compatible readers або roll forward. Не rollback через merge users/delete history/reuse external IDs.

Нумерований розбір атак і гонок ​

Очікування дизайну та майбутні executable tests, не passed runtime report.

IDУмови / діяОчікуваний результатEnforcement / майбутній тест
A01Два bootstrap, same keyОдин actor/team/owner/assignment/operationUnique receipt/transaction; concurrent HTTP
A02Різні keys/expired receipt, same external teamSame fingerprint resumes, changed conflicts; creator не regrantPermanent mapping; rotation/expiry/retry
A03Crash після commit до response/outboxSame operation, без orphan charged team/duplicate agentOutbox/step idempotency; crash injection
A04BONSITE key з foreign org/team/agentНерозкривна відмова, no read/writeWhole-chain namespace; routes/jobs/search/export
A05Malicious issuer як linked subjectЛише свої partner rights, без direct/private/other-org/link metadataSource-bound principal; routes/serializers
A06Provision key→browser issuance/payer acceptDenied навіть із known IDsScopes/independent proof; negative API
A07Два direct accounts link same subjectОдин winner, no account disclosureLock/unique; concurrent confirm
A08Email collision invite/direct/partnerNo auto-link/credential claim/retargetIndependent proof/fixed target; forwarded invite
A09Unsolicited callback/code, wrong browser/PKCENo session/account replacementBinding/state/nonce; login-CSRF/leak
A10Two-tab code redemption/replay/expiry/cancelОдин winner, no other context mutationAtomic consume/tab context; browser race
A11Unlink→stale JWT/refresh/socket/downloadDerived denied, unrelated independent sessions intactEpoch/family/proxy; refresh/stream
A12D→P→other link або partner refresh→directNo union/source wideningOne-hop/immutable source; token/graph
A13Два owners одночасно demote/removeActive owner лишаєтьсяTeam lock/version; transaction race
A14Revoke last external owner with live agentsRevoke succeeds, team/jobs stop, no arbitrary promoteLifecycle/owner checks; live cancel
A15Remove agent owner/transfer без payer consentExplicit reassign/suspend, payer unchangedFK/workflow; background/ownership
A16Cutoff + late usage + duplicate callbackOne historical assignment, no duplicate money/invoiceTimeline/occurredAt/dedup; boundary/reorder
A17Concurrent last-budget reserves/provider timeoutNo overspend/premature releaseAtomic reservation/reconcile; fault
A18Sponsor removed while pending payerPaid only with valid coverage; no owner autochargeActivation revalidate; sponsor removal
A19Deleted subject then stale active eventNo activation/lease extension by duplicate/stale revisionMonotonic revision/tombstone; replay/reorder
A20Deleted team bootstrap retryTombstone/unavailable, no new team/sessionPermanent ID/current state; delete/retry
A21BONSITE outage/closure, team-paid teamOrg work denied, other direct/private intact, no auto-moveStatus/subject lease; outage/closure
A22Issuer compromise with pending codes/linksRevoke proofs, quarantine links, direct credentials intactCredential/epoch/provenance; incident interval
A23Old payer lost membership, opens billInvoice-only, no team contentSeparate payer ACL; invoice auth
A24Add credentials in empty installationNo extra team/agent/founderDedicated flow/founding exclusion; empty install
A25Delete direct vs unlink vs partner deprovisionDistinct effects, preserve other actor/team/debt, no grant resurrectionLifecycle/relink integration
A26Test key/worker/guest token→production user routeDenied despite signature/known IDEnvironment/audience/type; matrix
A27Accept owner transfer after membership/policy changeReject, no partial demotionProof/version; accept/revoke race
A28State store unavailable/subject lease expiredFail closed; heartbeat/stale event не поновлює leaseAction gate/fresh subject proof; outage/replay
A29External owner invites own direct accountDenied, same-namespace external customer actors onlyTarget policy; deprovision bypass
A30Org A30+B70, team-paid C20, internal sponsorshipOrg invoice100, C20 separately, sponsorship не revenue; same direct payer не об’єднує team billsMode/team grouping key; mixed-payer invoice test

Знайдені та виправлені проблеми ​

Відкрите питання payer mode замінено вимогою обох у v1. Global merge замінено stable actors. Provisioning відділено від browser issuance; issuer impersonation power визнано явно. Direct invites у partner customer teams заборонені проти deprovision bypass. Last owner не блокує security revoke. Idempotency переживає rotation/expiry без resurrection. Contact/ownership/financial consent розділені; local allocation atomic, remote readiness async. Уточнено service initiator проти owner, subject/code freeze, compromise quarantine, per-subject fresh lease та billable sell-price budget, mixed-payer invoice grouping.

TTL/cutoff/lease — рекомендації, не нові підтверджені рішення. Release gates: provider обох modes, виміряна cancellation/lease, identity verification recovery, retention/legal policy, protocol interoperability. Failed gate блокує capability; «потім» не дозволяє unsafe paid/login path. Cross-org migration, privacy from identity issuer, nested resellers поза v1; closure — authorized export/support, не auto-transfer.

Після виправлень walkthrough не виявляє взаємних суперечностей інваріантів. Дизайн готовий до review з названими gates, не є доказом безпеки чи дозволом випуску runtime.

Перевірка документації ​

VitePress build, local links/anchors, navigation, EN/RU/UK section/scenario parity. Фактичні make check, app/admin builds, current HTTP startup results записуються в PR. API/app source не змінено, нових runtime test results немає. Пройти direct signup, external-only BONSITE, existing direct link та A01–A30 за контрактами.