@marinoscar/platform-db 0.0.0-stage → 0.1.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +525 -2
  4. package/bin/platform.js +28 -0
  5. package/dist/baseline/deps.d.ts +32 -0
  6. package/dist/baseline/deps.d.ts.map +1 -0
  7. package/dist/baseline/deps.js +66 -0
  8. package/dist/baseline/deps.js.map +1 -0
  9. package/dist/baseline/errors.d.ts +36 -0
  10. package/dist/baseline/errors.d.ts.map +1 -0
  11. package/dist/baseline/errors.js +23 -0
  12. package/dist/baseline/errors.js.map +1 -0
  13. package/dist/baseline/fs.d.ts +9 -0
  14. package/dist/baseline/fs.d.ts.map +1 -0
  15. package/dist/baseline/fs.js +39 -0
  16. package/dist/baseline/fs.js.map +1 -0
  17. package/dist/baseline/index.d.ts +8 -0
  18. package/dist/baseline/index.d.ts.map +1 -0
  19. package/dist/baseline/index.js +24 -0
  20. package/dist/baseline/index.js.map +1 -0
  21. package/dist/baseline/mapping.d.ts +43 -0
  22. package/dist/baseline/mapping.d.ts.map +1 -0
  23. package/dist/baseline/mapping.js +80 -0
  24. package/dist/baseline/mapping.js.map +1 -0
  25. package/dist/baseline/normalise.d.ts +42 -0
  26. package/dist/baseline/normalise.d.ts.map +1 -0
  27. package/dist/baseline/normalise.js +133 -0
  28. package/dist/baseline/normalise.js.map +1 -0
  29. package/dist/baseline/plan.d.ts +66 -0
  30. package/dist/baseline/plan.d.ts.map +1 -0
  31. package/dist/baseline/plan.js +105 -0
  32. package/dist/baseline/plan.js.map +1 -0
  33. package/dist/baseline/report.d.ts +127 -0
  34. package/dist/baseline/report.d.ts.map +1 -0
  35. package/dist/baseline/report.js +89 -0
  36. package/dist/baseline/report.js.map +1 -0
  37. package/dist/baseline/run.d.ts +117 -0
  38. package/dist/baseline/run.d.ts.map +1 -0
  39. package/dist/baseline/run.js +358 -0
  40. package/dist/baseline/run.js.map +1 -0
  41. package/dist/bin/db-commands.d.ts +31 -0
  42. package/dist/bin/db-commands.d.ts.map +1 -0
  43. package/dist/bin/db-commands.js +311 -0
  44. package/dist/bin/db-commands.js.map +1 -0
  45. package/dist/bin/fs-io.d.ts +7 -0
  46. package/dist/bin/fs-io.d.ts.map +1 -0
  47. package/dist/bin/fs-io.js +45 -0
  48. package/dist/bin/fs-io.js.map +1 -0
  49. package/dist/bin/platform.d.ts +21 -0
  50. package/dist/bin/platform.d.ts.map +1 -0
  51. package/dist/bin/platform.js +99 -0
  52. package/dist/bin/platform.js.map +1 -0
  53. package/dist/compose/api.d.ts +84 -0
  54. package/dist/compose/api.d.ts.map +1 -0
  55. package/dist/compose/api.js +101 -0
  56. package/dist/compose/api.js.map +1 -0
  57. package/dist/compose/compose.d.ts +51 -0
  58. package/dist/compose/compose.d.ts.map +1 -0
  59. package/dist/compose/compose.js +177 -0
  60. package/dist/compose/compose.js.map +1 -0
  61. package/dist/compose/diff.d.ts +7 -0
  62. package/dist/compose/diff.d.ts.map +1 -0
  63. package/dist/compose/diff.js +68 -0
  64. package/dist/compose/diff.js.map +1 -0
  65. package/dist/compose/errors.d.ts +31 -0
  66. package/dist/compose/errors.d.ts.map +1 -0
  67. package/dist/compose/errors.js +35 -0
  68. package/dist/compose/errors.js.map +1 -0
  69. package/dist/compose/index.d.ts +3 -0
  70. package/dist/compose/index.d.ts.map +1 -0
  71. package/dist/compose/index.js +11 -0
  72. package/dist/compose/index.js.map +1 -0
  73. package/dist/compose/parse.d.ts +65 -0
  74. package/dist/compose/parse.d.ts.map +1 -0
  75. package/dist/compose/parse.js +122 -0
  76. package/dist/compose/parse.js.map +1 -0
  77. package/dist/drift/app-objects.d.ts +107 -0
  78. package/dist/drift/app-objects.d.ts.map +1 -0
  79. package/dist/drift/app-objects.js +193 -0
  80. package/dist/drift/app-objects.js.map +1 -0
  81. package/dist/drift/db-conformance.d.ts +52 -0
  82. package/dist/drift/db-conformance.d.ts.map +1 -0
  83. package/dist/drift/db-conformance.js +89 -0
  84. package/dist/drift/db-conformance.js.map +1 -0
  85. package/dist/drift/index.d.ts +8 -0
  86. package/dist/drift/index.d.ts.map +1 -0
  87. package/dist/drift/index.js +43 -0
  88. package/dist/drift/index.js.map +1 -0
  89. package/dist/drift/raw-sql-indexes.d.ts +106 -0
  90. package/dist/drift/raw-sql-indexes.d.ts.map +1 -0
  91. package/dist/drift/raw-sql-indexes.js +113 -0
  92. package/dist/drift/raw-sql-indexes.js.map +1 -0
  93. package/dist/drift/raw-sql-tripwire.d.ts +191 -0
  94. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -0
  95. package/dist/drift/raw-sql-tripwire.js +422 -0
  96. package/dist/drift/raw-sql-tripwire.js.map +1 -0
  97. package/dist/drift/rls-policies.d.ts +226 -0
  98. package/dist/drift/rls-policies.d.ts.map +1 -0
  99. package/dist/drift/rls-policies.js +317 -0
  100. package/dist/drift/rls-policies.js.map +1 -0
  101. package/dist/drift/run.d.ts +152 -0
  102. package/dist/drift/run.d.ts.map +1 -0
  103. package/dist/drift/run.js +252 -0
  104. package/dist/drift/run.js.map +1 -0
  105. package/dist/drift/sql-expression.d.ts +27 -0
  106. package/dist/drift/sql-expression.d.ts.map +1 -0
  107. package/dist/drift/sql-expression.js +64 -0
  108. package/dist/drift/sql-expression.js.map +1 -0
  109. package/dist/index.d.ts +16 -0
  110. package/dist/index.d.ts.map +1 -0
  111. package/dist/index.js +33 -0
  112. package/dist/index.js.map +1 -0
  113. package/dist/lock/hash.d.ts +13 -0
  114. package/dist/lock/hash.d.ts.map +1 -0
  115. package/dist/lock/hash.js +19 -0
  116. package/dist/lock/hash.js.map +1 -0
  117. package/dist/lock/index.d.ts +5 -0
  118. package/dist/lock/index.d.ts.map +1 -0
  119. package/dist/lock/index.js +20 -0
  120. package/dist/lock/index.js.map +1 -0
  121. package/dist/lock/lock.d.ts +154 -0
  122. package/dist/lock/lock.d.ts.map +1 -0
  123. package/dist/lock/lock.js +151 -0
  124. package/dist/lock/lock.js.map +1 -0
  125. package/dist/lock/manifest.d.ts +68 -0
  126. package/dist/lock/manifest.d.ts.map +1 -0
  127. package/dist/lock/manifest.js +96 -0
  128. package/dist/lock/manifest.js.map +1 -0
  129. package/dist/lock/semver.d.ts +10 -0
  130. package/dist/lock/semver.d.ts.map +1 -0
  131. package/dist/lock/semver.js +13 -0
  132. package/dist/lock/semver.js.map +1 -0
  133. package/dist/seed/index.d.ts +5 -0
  134. package/dist/seed/index.d.ts.map +1 -0
  135. package/dist/seed/index.js +16 -0
  136. package/dist/seed/index.js.map +1 -0
  137. package/dist/seed/input.d.ts +52 -0
  138. package/dist/seed/input.d.ts.map +1 -0
  139. package/dist/seed/input.js +77 -0
  140. package/dist/seed/input.js.map +1 -0
  141. package/dist/seed/seed-platform.d.ts +41 -0
  142. package/dist/seed/seed-platform.d.ts.map +1 -0
  143. package/dist/seed/seed-platform.js +165 -0
  144. package/dist/seed/seed-platform.js.map +1 -0
  145. package/dist/seed/steps.d.ts +172 -0
  146. package/dist/seed/steps.d.ts.map +1 -0
  147. package/dist/seed/steps.js +136 -0
  148. package/dist/seed/steps.js.map +1 -0
  149. package/dist/seed/types.d.ts +287 -0
  150. package/dist/seed/types.d.ts.map +1 -0
  151. package/dist/seed/types.js +5 -0
  152. package/dist/seed/types.js.map +1 -0
  153. package/dist/sync/app-migrations.d.ts +52 -0
  154. package/dist/sync/app-migrations.d.ts.map +1 -0
  155. package/dist/sync/app-migrations.js +62 -0
  156. package/dist/sync/app-migrations.js.map +1 -0
  157. package/dist/sync/apply.d.ts +29 -0
  158. package/dist/sync/apply.d.ts.map +1 -0
  159. package/dist/sync/apply.js +38 -0
  160. package/dist/sync/apply.js.map +1 -0
  161. package/dist/sync/check.d.ts +59 -0
  162. package/dist/sync/check.d.ts.map +1 -0
  163. package/dist/sync/check.js +115 -0
  164. package/dist/sync/check.js.map +1 -0
  165. package/dist/sync/errors.d.ts +32 -0
  166. package/dist/sync/errors.d.ts.map +1 -0
  167. package/dist/sync/errors.js +23 -0
  168. package/dist/sync/errors.js.map +1 -0
  169. package/dist/sync/index.d.ts +10 -0
  170. package/dist/sync/index.d.ts.map +1 -0
  171. package/dist/sync/index.js +27 -0
  172. package/dist/sync/index.js.map +1 -0
  173. package/dist/sync/ledger.d.ts +65 -0
  174. package/dist/sync/ledger.d.ts.map +1 -0
  175. package/dist/sync/ledger.js +49 -0
  176. package/dist/sync/ledger.js.map +1 -0
  177. package/dist/sync/plan.d.ts +63 -0
  178. package/dist/sync/plan.d.ts.map +1 -0
  179. package/dist/sync/plan.js +86 -0
  180. package/dist/sync/plan.js.map +1 -0
  181. package/dist/sync/promote.d.ts +62 -0
  182. package/dist/sync/promote.d.ts.map +1 -0
  183. package/dist/sync/promote.js +95 -0
  184. package/dist/sync/promote.js.map +1 -0
  185. package/dist/sync/timestamps.d.ts +41 -0
  186. package/dist/sync/timestamps.d.ts.map +1 -0
  187. package/dist/sync/timestamps.js +68 -0
  188. package/dist/sync/timestamps.js.map +1 -0
  189. package/dist/sync/version.d.ts +28 -0
  190. package/dist/sync/version.d.ts.map +1 -0
  191. package/dist/sync/version.js +66 -0
  192. package/dist/sync/version.js.map +1 -0
  193. package/migrations/0001_initial/migration.sql +297 -0
  194. package/migrations/0002_add_personal_access_tokens/migration.sql +31 -0
  195. package/migrations/0003_add_credentials/migration.sql +20 -0
  196. package/migrations/0004_add_notification_deliveries/migration.sql +27 -0
  197. package/migrations/0005_drop_stale_uuid_defaults/migration.sql +35 -0
  198. package/migrations/0006_add_notifications/migration.sql +22 -0
  199. package/migrations/0007_add_push_subscriptions/migration.sql +25 -0
  200. package/migrations/0008_add_jobs/migration.sql +110 -0
  201. package/migrations/0009_add_worker_nodes/migration.sql +90 -0
  202. package/migrations/0010_add_database_backup_runs/migration.sql +104 -0
  203. package/migrations/0011_add_notification_broadcasts/migration.sql +57 -0
  204. package/migrations/0012_add_backup_run_job_link/migration.sql +87 -0
  205. package/migrations/0013_add_job_node_secrets/migration.sql +61 -0
  206. package/migrations/0014_add_backup_run_pg_dump_version/migration.sql +26 -0
  207. package/migrations/0015_add_job_claim_token/migration.sql +92 -0
  208. package/migrations/0016_add_ai_platform/migration.sql +108 -0
  209. package/migrations/0017_revoke_viewer_ai_use/migration.sql +32 -0
  210. package/migrations/0018_add_user_credentials/migration.sql +29 -0
  211. package/migrations/0019_add_device_session_credential_link/migration.sql +52 -0
  212. package/migrations/0020_add_worker_node_vitals/migration.sql +3 -0
  213. package/migrations/0021_add_job_trace_context/migration.sql +6 -0
  214. package/migrations/0022_add_retention_created_at_indexes/migration.sql +13 -0
  215. package/migrations/0023_add_organizations/migration.sql +142 -0
  216. package/migrations/0024_split_system_org_roles/migration.sql +131 -0
  217. package/migrations/0025_org_scoped_rls/migration.sql +215 -0
  218. package/migrations/0026_add_groups/migration.sql +165 -0
  219. package/migrations/0027_add_grants/migration.sql +117 -0
  220. package/migrations/0028_add_org_settings/migration.sql +49 -0
  221. package/migrations/0029_add_org_credentials/migration.sql +54 -0
  222. package/migrations/0030_add_jobs_org_id/migration.sql +18 -0
  223. package/migrations/0031_add_jobs_org_id_status_index/migration.sql +6 -0
  224. package/migrations/0032_add_broadcast_target_org/migration.sql +21 -0
  225. package/migrations/0033_add_android_app/migration.sql +60 -0
  226. package/migrations/0034_open_job_reason/migration.sql +16 -0
  227. package/migrations/0035_ai_usage_feature/migration.sql +37 -0
  228. package/migrations/0036_add_app_metadata/migration.sql +49 -0
  229. package/migrations/0037_open_sharing_vocabularies/migration.sql +97 -0
  230. package/migrations/manifest.json +379 -0
  231. package/package.json +78 -4
  232. package/raw-sql-indexes.json +94 -0
  233. package/rls-policies.json +74 -0
  234. package/schema/ai.prisma +444 -0
  235. package/schema/android-app.prisma +47 -0
  236. package/schema/base.prisma +11 -0
  237. package/schema/credentials.prisma +170 -0
  238. package/schema/db-backup.prisma +376 -0
  239. package/schema/identity.prisma +439 -0
  240. package/schema/jobs.prisma +760 -0
  241. package/schema/notifications.prisma +649 -0
  242. package/schema/settings.prisma +60 -0
  243. package/schema/sharing.prisma +223 -0
  244. package/schema/storage.prisma +84 -0
@@ -0,0 +1,439 @@
1
+ // =============================================================================
2
+ // User & Identity
3
+ // =============================================================================
4
+
5
+ // @extensible — back-relations only, added with "extend model User { ... }" in a fragment
6
+ model User {
7
+ id String @id @default(uuid()) @db.Uuid
8
+ email String @unique
9
+ displayName String? @map("display_name")
10
+ providerDisplayName String? @map("provider_display_name")
11
+ profileImageUrl String? @map("profile_image_url")
12
+ providerProfileImageUrl String? @map("provider_profile_image_url")
13
+ isActive Boolean @default(true) @map("is_active")
14
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
15
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
16
+ // App-owned, namespaced fields (`registerUserMetadataSchema`, PP-14.27): one top-level
17
+ // key per registered namespace, each validated against its zod schema on write.
18
+ // NOT a secret store (a secret-named field is refused at registration; secrets go
19
+ // in `user_credentials`). At most 16 KiB per row, enforced by the writer and, as a
20
+ // 32 KiB backstop, by `users_metadata_size_check`. Never returned by the platform's
21
+ // routes: an app exposes a namespace only through a route it writes.
22
+ metadata Json @default("{}") @db.JsonB
23
+
24
+ // Relations
25
+ identities UserIdentity[]
26
+ userRoles UserRole[]
27
+ auditEvents AuditEvent[] @relation("ActorEvents")
28
+ refreshTokens RefreshToken[] @relation("UserRefreshTokens")
29
+ allowlistEntriesAdded AllowedEmail[] @relation("AllowlistAddedBy")
30
+ allowlistEntry AllowedEmail? @relation("AllowlistClaimedBy")
31
+ deviceCodes DeviceCode[] @relation("UserDeviceCodes")
32
+ personalAccessTokens PersonalAccessToken[] @relation("UserPersonalAccessTokens")
33
+ memberships Membership[]
34
+ organizationsCreated Organization[] @relation("OrganizationCreatedBy")
35
+ invitesSent Invite[] @relation("InviteInvitedBy")
36
+ invitesAccepted Invite[] @relation("InviteAcceptedBy")
37
+
38
+ @@map("users")
39
+ }
40
+
41
+ model UserIdentity {
42
+ id String @id @default(uuid()) @db.Uuid
43
+ userId String @map("user_id") @db.Uuid
44
+ provider String
45
+ providerSubject String @map("provider_subject")
46
+ providerEmail String? @map("provider_email")
47
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
48
+
49
+ // Relations
50
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
51
+
52
+ @@unique([provider, providerSubject])
53
+ @@map("user_identities")
54
+ }
55
+
56
+ // =============================================================================
57
+ // RBAC - Roles & Permissions
58
+ // =============================================================================
59
+ //
60
+ // Two kinds of role (PP-6.3): SYSTEM roles operate the deployment and are held
61
+ // in `user_roles`; ORG roles operate one organization and are held on a
62
+ // membership (`memberships.role_id`). A role is granted only permissions of its
63
+ // own scope (enforced by the app's permission registry, seeded by
64
+ // `seedPlatform`). Roles stay global rows; per-organization custom roles are a
65
+ // later seam.
66
+
67
+ enum RoleScope {
68
+ system
69
+ org
70
+ }
71
+
72
+ // @extensible — back-relations only, added with "extend model Role { ... }" in a fragment
73
+ // (a table of the app's own that points at a role, such as per-role settings). The
74
+ // role's own columns and the `role_permissions` grants stay the platform's: `seedPlatform`
75
+ // refreshes them from the registry on every run.
76
+ model Role {
77
+ id String @id @default(uuid()) @db.Uuid
78
+ name String @unique
79
+ description String?
80
+ scope RoleScope @default(system)
81
+
82
+ // Relations
83
+ rolePermissions RolePermission[]
84
+ userRoles UserRole[]
85
+ memberships Membership[]
86
+ invites Invite[]
87
+
88
+ @@map("roles")
89
+ }
90
+
91
+ // Deliberately NOT `@extensible` (PP-14.27). A permission is a string owned by code:
92
+ // the registry (`registerPermissions`) is the source of truth, `seedPlatform` upserts
93
+ // the rows by `name` and never deletes one, and a removed permission is retired by an
94
+ // explicit expand/contract migration. A foreign key from an app table would make that
95
+ // retirement fail and would tie app data to a row id that no registry declares. An app
96
+ // refers to a permission by its name string in code, never by a relation.
97
+ model Permission {
98
+ id String @id @default(uuid()) @db.Uuid
99
+ name String @unique
100
+ description String?
101
+ scope RoleScope @default(system)
102
+
103
+ // Relations
104
+ rolePermissions RolePermission[]
105
+
106
+ @@map("permissions")
107
+ }
108
+
109
+ model RolePermission {
110
+ roleId String @map("role_id") @db.Uuid
111
+ permissionId String @map("permission_id") @db.Uuid
112
+
113
+ // Relations
114
+ role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)
115
+ permission Permission @relation(fields: [permissionId], references: [id], onDelete: Cascade)
116
+
117
+ @@id([roleId, permissionId])
118
+ @@map("role_permissions")
119
+ }
120
+
121
+ model UserRole {
122
+ userId String @map("user_id") @db.Uuid
123
+ roleId String @map("role_id") @db.Uuid
124
+
125
+ // Relations
126
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
127
+ role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)
128
+
129
+ @@id([userId, roleId])
130
+ @@map("user_roles")
131
+ }
132
+
133
+ // =============================================================================
134
+ // Audit
135
+ // =============================================================================
136
+
137
+ model AuditEvent {
138
+ id String @id @default(uuid()) @db.Uuid
139
+ actorUserId String? @map("actor_user_id") @db.Uuid
140
+ action String
141
+ targetType String @map("target_type")
142
+ targetId String @map("target_id")
143
+ meta Json?
144
+ // The organization the action happened in (#725). NULL for a system event
145
+ // (settings, backups, restores, the allowlist): see the backfill in
146
+ // `0025_org_scoped_rls`. `SetNull`: history outlives the organization. No
147
+ // row-level security on this table in this release (`org-optional`).
148
+ orgId String? @map("org_id") @db.Uuid
149
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
150
+
151
+ // Relations
152
+ actorUser User? @relation("ActorEvents", fields: [actorUserId], references: [id], onDelete: SetNull)
153
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: SetNull)
154
+
155
+ @@index([actorUserId])
156
+ @@index([targetType, targetId])
157
+ @@index([createdAt])
158
+ @@index([orgId, createdAt])
159
+ @@map("audit_events")
160
+ }
161
+
162
+ // =============================================================================
163
+ // Refresh Tokens (for token rotation)
164
+ // =============================================================================
165
+
166
+ model RefreshToken {
167
+ id String @id @default(uuid()) @db.Uuid
168
+ userId String @map("user_id") @db.Uuid
169
+ tokenHash String @unique @map("token_hash")
170
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
171
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
172
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
173
+ // The device-authorization session that minted this refresh token, if any
174
+ // (issue #518). Lets revoking a `DeviceCode` session reach the refresh
175
+ // token it handed out. Nullable: most refresh tokens come from the
176
+ // interactive login flow, not the device flow. `SetNull` because a device
177
+ // code can be purged independently of the token lifecycle it kicked off.
178
+ deviceCodeId String? @map("device_code_id") @db.Uuid
179
+ // The organization this session is active in (PP-6.1). Nullable (expand
180
+ // step); backfilled to the default organization. Carried by the active-org
181
+ // token (PP-6.4). `Cascade`: a credential has no meaning once its org is gone.
182
+ orgId String? @map("org_id") @db.Uuid
183
+
184
+ // Relations
185
+ user User @relation("UserRefreshTokens", fields: [userId], references: [id], onDelete: Cascade)
186
+ deviceCode DeviceCode? @relation(fields: [deviceCodeId], references: [id], onDelete: SetNull)
187
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)
188
+
189
+ @@index([userId])
190
+ @@index([expiresAt])
191
+ @@index([deviceCodeId])
192
+ @@index([orgId])
193
+ @@map("refresh_tokens")
194
+ }
195
+
196
+ // =============================================================================
197
+ // Personal Access Tokens (PAT)
198
+ // =============================================================================
199
+
200
+ enum PatDurationUnit {
201
+ minutes
202
+ days
203
+ months
204
+ }
205
+
206
+ model PersonalAccessToken {
207
+ id String @id @default(uuid()) @db.Uuid
208
+ userId String @map("user_id") @db.Uuid
209
+ name String
210
+ tokenHash String @unique @map("token_hash")
211
+ tokenPrefix String @map("token_prefix")
212
+ durationValue Int @map("duration_value")
213
+ durationUnit PatDurationUnit @map("duration_unit")
214
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
215
+ lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz
216
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
217
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
218
+ // The organization the token acts in (PP-6.1). Nullable (expand step);
219
+ // backfilled to the default organization. `Cascade`: see `RefreshToken.orgId`.
220
+ orgId String? @map("org_id") @db.Uuid
221
+
222
+ // Relations
223
+ user User @relation("UserPersonalAccessTokens", fields: [userId], references: [id], onDelete: Cascade)
224
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)
225
+ // The device-authorization sessions that issued this PAT (issue #518).
226
+ // Almost always at most one, but not constrained `@unique` here — see
227
+ // `DeviceCode.patId`.
228
+ deviceCodes DeviceCode[]
229
+
230
+ @@index([userId])
231
+ @@index([expiresAt])
232
+ @@index([orgId])
233
+ @@map("personal_access_tokens")
234
+ }
235
+
236
+ // =============================================================================
237
+ // Allowlist (Email Access Control)
238
+ // =============================================================================
239
+
240
+ model AllowedEmail {
241
+ id String @id @default(uuid()) @db.Uuid
242
+ email String @unique
243
+ addedById String? @map("added_by_id") @db.Uuid
244
+ addedAt DateTime @default(now()) @map("added_at") @db.Timestamptz
245
+ claimedById String? @unique @map("claimed_by_id") @db.Uuid
246
+ claimedAt DateTime? @map("claimed_at") @db.Timestamptz
247
+ notes String?
248
+
249
+ // Relations
250
+ addedBy User? @relation("AllowlistAddedBy", fields: [addedById], references: [id], onDelete: SetNull)
251
+ claimedBy User? @relation("AllowlistClaimedBy", fields: [claimedById], references: [id], onDelete: SetNull)
252
+
253
+ @@map("allowed_emails")
254
+ }
255
+
256
+ // =============================================================================
257
+ // Device Authorization Flow (RFC 8628)
258
+ // =============================================================================
259
+
260
+ enum DeviceCodeStatus {
261
+ pending
262
+ approved
263
+ denied
264
+ expired
265
+ }
266
+
267
+ model DeviceCode {
268
+ id String @id @default(uuid()) @db.Uuid
269
+ deviceCode String @unique @map("device_code")
270
+ userCode String @unique @map("user_code")
271
+ userId String? @map("user_id") @db.Uuid
272
+ status DeviceCodeStatus @default(pending)
273
+ clientInfo Json? @map("client_info")
274
+ scopes String[]
275
+ // The code's own expiry (RFC 8628 `expires_in`) — when the user/device
276
+ // codes stop being redeemable if never approved. Distinct from
277
+ // `credentialExpiresAt`, which is the lifetime of what got issued once
278
+ // approval happened (issue #518).
279
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
280
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
281
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
282
+
283
+ // The PAT minted for this device once the polling client collected it
284
+ // (issue #518). Nullable until collection; `SetNull` so deleting the PAT
285
+ // (or the PAT row aging out) never cascades into deleting the device-code
286
+ // history. This is what lets "revoke this device session" reach the
287
+ // credential the device is actually holding.
288
+ patId String? @map("pat_id") @db.Uuid
289
+
290
+ // When the polling client (`POST /api/auth/device/token`) collected the
291
+ // credential above. Null until collection. Distinguishes "approved,
292
+ // waiting to be picked up" from "picked up and in active use" for the
293
+ // sessions list.
294
+ collectedAt DateTime? @map("collected_at") @db.Timestamptz
295
+
296
+ // The collected credential's own expiry, copied from the PAT at
297
+ // collection time so the sessions list can filter "still valid" without a
298
+ // join. Null until collection.
299
+ credentialExpiresAt DateTime? @map("credential_expires_at") @db.Timestamptz
300
+
301
+ // Set when this device session (and the credential it issued, if any) is
302
+ // revoked — from the code itself if revoked before collection, from the
303
+ // session-revocation endpoint after. Null means still active.
304
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
305
+
306
+ // The organization the approved device session acts in (PP-6.1). Nullable
307
+ // (expand step); backfilled to the default organization. `Cascade`: see
308
+ // `RefreshToken.orgId`.
309
+ orgId String? @map("org_id") @db.Uuid
310
+
311
+ // Relations
312
+ user User? @relation("UserDeviceCodes", fields: [userId], references: [id], onDelete: Cascade)
313
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)
314
+ pat PersonalAccessToken? @relation(fields: [patId], references: [id], onDelete: SetNull)
315
+
316
+ // Back-relation: refresh tokens minted through this device-authorization
317
+ // session (issue #518). See `RefreshToken.deviceCodeId`.
318
+ refreshTokens RefreshToken[]
319
+
320
+ @@index([deviceCode])
321
+ @@index([userCode])
322
+ @@index([status, expiresAt])
323
+ @@index([userId])
324
+ // Serves the sessions list (`GET /api/auth/device/sessions`, issue #518):
325
+ // "this user's device sessions that are not revoked" —
326
+ // approved-but-uncollected and collected-unexpired both live under
327
+ // `revokedAt IS NULL`; the remaining collected/expiry filtering happens
328
+ // in the query predicate, not a second index.
329
+ @@index([userId, revokedAt])
330
+ @@index([orgId])
331
+ @@map("device_codes")
332
+ }
333
+
334
+ // =============================================================================
335
+ // Organizations (tenancy foundation, PP-6.1)
336
+ // =============================================================================
337
+ //
338
+ // Identity tables, read across organizations at login and guarded by service
339
+ // code: no RLS here (ADR 0002). The default organization is unique by the
340
+ // raw-SQL partial index `organizations_default_uniq_idx` (migration SQL only;
341
+ // Prisma cannot express it). A membership carries its org role (PP-6.3); an
342
+ // invite may name the org role the invitee will get.
343
+
344
+ enum MembershipStatus {
345
+ active
346
+ suspended
347
+ }
348
+
349
+ enum InviteStatus {
350
+ pending
351
+ accepted
352
+ revoked
353
+ expired
354
+ }
355
+
356
+ // @extensible — back-relations only, added with "extend model Organization { ... }" in a fragment
357
+ model Organization {
358
+ id String @id @default(uuid()) @db.Uuid
359
+ name String
360
+ // Lower-case [a-z0-9-], 2..63 characters (validated by the service).
361
+ slug String @unique
362
+ // Exactly one row is true: organizations_default_uniq_idx.
363
+ isDefault Boolean @default(false) @map("is_default")
364
+ createdById String? @map("created_by_id") @db.Uuid
365
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
366
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
367
+ // App-owned, namespaced fields (`registerOrganizationMetadataSchema`, PP-14.27); same
368
+ // contract as `User.metadata`: validated per namespace, no secrets, 16 KiB per row
369
+ // (32 KiB backstop `organizations_metadata_size_check`), never returned by the
370
+ // platform's routes.
371
+ metadata Json @default("{}") @db.JsonB
372
+
373
+ // Relations
374
+ createdBy User? @relation("OrganizationCreatedBy", fields: [createdById], references: [id], onDelete: SetNull)
375
+ memberships Membership[]
376
+ invites Invite[]
377
+ refreshTokens RefreshToken[]
378
+ personalAccessTokens PersonalAccessToken[]
379
+ deviceCodes DeviceCode[]
380
+ // Audit history outlives the organization (`SetNull`); system events have none (#725).
381
+ auditEvents AuditEvent[]
382
+
383
+ @@map("organizations")
384
+ }
385
+
386
+ model Membership {
387
+ id String @id @default(uuid()) @db.Uuid
388
+ orgId String @map("org_id") @db.Uuid
389
+ userId String @map("user_id") @db.Uuid
390
+ status MembershipStatus @default(active)
391
+ // Picks the default active organization at login (PP-6.4).
392
+ lastActiveAt DateTime? @map("last_active_at") @db.Timestamptz
393
+ // The member's org-scoped role (PP-6.3). `Restrict`: a role in use cannot be
394
+ // deleted out from under its members.
395
+ roleId String @map("role_id") @db.Uuid
396
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
397
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
398
+
399
+ // Relations
400
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
401
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
402
+ role Role @relation(fields: [roleId], references: [id], onDelete: Restrict)
403
+
404
+ @@unique([orgId, userId])
405
+ @@index([userId])
406
+ @@index([roleId])
407
+ @@map("memberships")
408
+ }
409
+
410
+ model Invite {
411
+ id String @id @default(uuid()) @db.Uuid
412
+ orgId String @map("org_id") @db.Uuid
413
+ // Stored lower-cased.
414
+ email String
415
+ status InviteStatus @default(pending)
416
+ // sha256 of an emailed accept token, if one is used.
417
+ tokenHash String? @unique @map("token_hash")
418
+ expiresAt DateTime? @map("expires_at") @db.Timestamptz
419
+ invitedById String? @map("invited_by_id") @db.Uuid
420
+ acceptedById String? @map("accepted_by_id") @db.Uuid
421
+ acceptedAt DateTime? @map("accepted_at") @db.Timestamptz
422
+ notes String?
423
+ // The org role the invitee gets on acceptance (PP-6.3). NULL means the
424
+ // default org role (`viewer`). `Restrict`, as on `Membership.roleId`.
425
+ roleId String? @map("role_id") @db.Uuid
426
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
427
+
428
+ // Relations
429
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
430
+ role Role? @relation(fields: [roleId], references: [id], onDelete: Restrict)
431
+ invitedBy User? @relation("InviteInvitedBy", fields: [invitedById], references: [id], onDelete: SetNull)
432
+ acceptedBy User? @relation("InviteAcceptedBy", fields: [acceptedById], references: [id], onDelete: SetNull)
433
+
434
+ // Re-inviting updates the row.
435
+ @@unique([orgId, email])
436
+ @@index([email])
437
+ @@index([roleId])
438
+ @@map("org_invites")
439
+ }