@marinoscar/platform-db 0.1.0-next.3 → 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 (125) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +156 -13
  3. package/dist/baseline/deps.d.ts.map +1 -1
  4. package/dist/baseline/deps.js +2 -0
  5. package/dist/baseline/deps.js.map +1 -1
  6. package/dist/baseline/errors.d.ts +3 -1
  7. package/dist/baseline/errors.d.ts.map +1 -1
  8. package/dist/baseline/errors.js.map +1 -1
  9. package/dist/baseline/report.d.ts +3 -1
  10. package/dist/baseline/report.d.ts.map +1 -1
  11. package/dist/baseline/report.js +4 -0
  12. package/dist/baseline/report.js.map +1 -1
  13. package/dist/baseline/run.d.ts +12 -1
  14. package/dist/baseline/run.d.ts.map +1 -1
  15. package/dist/baseline/run.js +19 -0
  16. package/dist/baseline/run.js.map +1 -1
  17. package/dist/bin/db-commands.d.ts +1 -1
  18. package/dist/bin/db-commands.d.ts.map +1 -1
  19. package/dist/bin/db-commands.js +40 -5
  20. package/dist/bin/db-commands.js.map +1 -1
  21. package/dist/drift/app-objects.d.ts +107 -0
  22. package/dist/drift/app-objects.d.ts.map +1 -0
  23. package/dist/drift/app-objects.js +193 -0
  24. package/dist/drift/app-objects.js.map +1 -0
  25. package/dist/drift/db-conformance.d.ts +3 -0
  26. package/dist/drift/db-conformance.d.ts.map +1 -1
  27. package/dist/drift/db-conformance.js +24 -0
  28. package/dist/drift/db-conformance.js.map +1 -1
  29. package/dist/drift/index.d.ts +5 -2
  30. package/dist/drift/index.d.ts.map +1 -1
  31. package/dist/drift/index.js +18 -1
  32. package/dist/drift/index.js.map +1 -1
  33. package/dist/drift/raw-sql-tripwire.d.ts +44 -3
  34. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -1
  35. package/dist/drift/raw-sql-tripwire.js +39 -11
  36. package/dist/drift/raw-sql-tripwire.js.map +1 -1
  37. package/dist/drift/rls-policies.d.ts +226 -0
  38. package/dist/drift/rls-policies.d.ts.map +1 -0
  39. package/dist/drift/rls-policies.js +317 -0
  40. package/dist/drift/rls-policies.js.map +1 -0
  41. package/dist/drift/run.d.ts +24 -0
  42. package/dist/drift/run.d.ts.map +1 -1
  43. package/dist/drift/run.js +52 -1
  44. package/dist/drift/run.js.map +1 -1
  45. package/dist/drift/sql-expression.d.ts +27 -0
  46. package/dist/drift/sql-expression.d.ts.map +1 -0
  47. package/dist/drift/sql-expression.js +64 -0
  48. package/dist/drift/sql-expression.js.map +1 -0
  49. package/dist/lock/index.d.ts +1 -1
  50. package/dist/lock/index.d.ts.map +1 -1
  51. package/dist/lock/index.js.map +1 -1
  52. package/dist/lock/lock.d.ts +37 -0
  53. package/dist/lock/lock.d.ts.map +1 -1
  54. package/dist/lock/lock.js +11 -0
  55. package/dist/lock/lock.js.map +1 -1
  56. package/dist/lock/manifest.d.ts +8 -0
  57. package/dist/lock/manifest.d.ts.map +1 -1
  58. package/dist/lock/manifest.js +1 -0
  59. package/dist/lock/manifest.js.map +1 -1
  60. package/dist/seed/index.d.ts +1 -0
  61. package/dist/seed/index.d.ts.map +1 -1
  62. package/dist/seed/index.js +7 -1
  63. package/dist/seed/index.js.map +1 -1
  64. package/dist/seed/seed-platform.d.ts +16 -3
  65. package/dist/seed/seed-platform.d.ts.map +1 -1
  66. package/dist/seed/seed-platform.js +37 -5
  67. package/dist/seed/seed-platform.js.map +1 -1
  68. package/dist/seed/steps.d.ts +172 -0
  69. package/dist/seed/steps.d.ts.map +1 -0
  70. package/dist/seed/steps.js +136 -0
  71. package/dist/seed/steps.js.map +1 -0
  72. package/dist/seed/types.d.ts +12 -2
  73. package/dist/seed/types.d.ts.map +1 -1
  74. package/dist/sync/app-migrations.d.ts +52 -0
  75. package/dist/sync/app-migrations.d.ts.map +1 -0
  76. package/dist/sync/app-migrations.js +62 -0
  77. package/dist/sync/app-migrations.js.map +1 -0
  78. package/dist/sync/apply.d.ts.map +1 -1
  79. package/dist/sync/apply.js +1 -0
  80. package/dist/sync/apply.js.map +1 -1
  81. package/dist/sync/check.d.ts +5 -2
  82. package/dist/sync/check.d.ts.map +1 -1
  83. package/dist/sync/check.js +8 -1
  84. package/dist/sync/check.js.map +1 -1
  85. package/dist/sync/errors.d.ts +2 -1
  86. package/dist/sync/errors.d.ts.map +1 -1
  87. package/dist/sync/errors.js.map +1 -1
  88. package/dist/sync/index.d.ts +1 -0
  89. package/dist/sync/index.d.ts.map +1 -1
  90. package/dist/sync/index.js +3 -1
  91. package/dist/sync/index.js.map +1 -1
  92. package/dist/sync/plan.d.ts +3 -1
  93. package/dist/sync/plan.d.ts.map +1 -1
  94. package/dist/sync/plan.js +9 -2
  95. package/dist/sync/plan.js.map +1 -1
  96. package/dist/sync/promote.d.ts +4 -0
  97. package/dist/sync/promote.d.ts.map +1 -1
  98. package/dist/sync/promote.js +2 -0
  99. package/dist/sync/promote.js.map +1 -1
  100. package/migrations/0025_org_scoped_rls/migration.sql +215 -0
  101. package/migrations/0026_add_groups/migration.sql +165 -0
  102. package/migrations/0027_add_grants/migration.sql +117 -0
  103. package/migrations/0028_add_org_settings/migration.sql +49 -0
  104. package/migrations/0029_add_org_credentials/migration.sql +54 -0
  105. package/migrations/0030_add_jobs_org_id/migration.sql +18 -0
  106. package/migrations/0031_add_jobs_org_id_status_index/migration.sql +6 -0
  107. package/migrations/0032_add_broadcast_target_org/migration.sql +21 -0
  108. package/migrations/0033_add_android_app/migration.sql +60 -0
  109. package/migrations/0034_open_job_reason/migration.sql +16 -0
  110. package/migrations/0035_ai_usage_feature/migration.sql +37 -0
  111. package/migrations/0036_add_app_metadata/migration.sql +49 -0
  112. package/migrations/0037_open_sharing_vocabularies/migration.sql +97 -0
  113. package/migrations/manifest.json +139 -0
  114. package/package.json +5 -2
  115. package/raw-sql-indexes.json +45 -0
  116. package/rls-policies.json +74 -0
  117. package/schema/ai.prisma +59 -2
  118. package/schema/android-app.prisma +47 -0
  119. package/schema/credentials.prisma +62 -0
  120. package/schema/identity.prisma +33 -1
  121. package/schema/jobs.prisma +36 -7
  122. package/schema/notifications.prisma +40 -1
  123. package/schema/settings.prisma +25 -0
  124. package/schema/sharing.prisma +223 -0
  125. package/schema/storage.prisma +28 -1
@@ -210,7 +210,14 @@ model Job {
210
210
  dedupKey String? @map("dedup_key")
211
211
 
212
212
  status JobStatus @default(pending)
213
- reason JobReason
213
+
214
+ // Why the job was queued: a plain string (an open vocabulary), not a Prisma
215
+ // enum, for the reason `Job.type` is one. The built-ins are `upload`, `rerun`
216
+ // and `backfill`; an app adds its own through `registerJobReason`
217
+ // (`@marinoscar/platform-api/jobs`) at zero migrations. The set a row may
218
+ // carry is bounded by the contract's `jobReasonSchema` pattern at the API
219
+ // edge, not by a CHECK constraint, so a row outlives the reason that wrote it.
220
+ reason String
214
221
 
215
222
  // Ascending = more urgent. See the block comment above.
216
223
  priority Int @default(0)
@@ -292,6 +299,25 @@ model Job {
292
299
  // never a key, never indexed, never read by the claim query's WHERE.
293
300
  traceContext String? @map("trace_context")
294
301
 
302
+ // The organization the work belongs to (issue #734), or NULL for a
303
+ // deployment-wide (system) job: housekeeping, fleet sweeps, backups. Written
304
+ // once at enqueue (`EnqueueJobInput.orgId`, else the app's ambient scope);
305
+ // never updated. `SetNull`: deleting an organization keeps its job history
306
+ // (offboarding cancels the org's pending jobs explicitly first, #743).
307
+ //
308
+ // ⚠ NO ROW-LEVEL SECURITY ON `jobs`, deliberately. The claim is ONE
309
+ // cross-organization statement (`FOR UPDATE SKIP LOCKED` over the whole
310
+ // queue, `job-claim.service.ts`), and a per-org policy would need the bypass
311
+ // connection for every claim, renewal and settle. Isolation is enforced at
312
+ // the API: the admin routes are system routes (`jobs:read` / `jobs:write`).
313
+ // A handler that touches an org table runs under `JobScope.run(job, fn)`.
314
+ //
315
+ // ⚠ NOT PART OF THE DEDUP KEY. `jobs_active_dedup_uniq_idx` is unchanged; an
316
+ // org-scoped job with no natural subject uses `subjectType: 'organization',
317
+ // subjectId: orgId`, so two organizations never collide.
318
+ orgId String? @map("org_id") @db.Uuid
319
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: SetNull)
320
+
295
321
  // See the block comment above ("Prisma-expressible indexes...") for why
296
322
  // these eight are declared here and three more exist only in
297
323
  // migration.sql.
@@ -315,6 +341,10 @@ model Job {
315
341
  // this index — status, type and id are all it needs to project — so
316
342
  // Postgres never has to visit the heap for them (index-only scan).
317
343
  @@index([status, type, id])
344
+ // "This organization's jobs by status" (the admin list's `orgId` filter,
345
+ // offboarding's pending-job cancel; #734). Built CONCURRENTLY in a migration
346
+ // of its own (`0031_add_jobs_org_id_status_index`): `jobs` is a big table.
347
+ @@index([orgId, status])
318
348
  @@map("jobs")
319
349
  }
320
350
 
@@ -325,12 +355,6 @@ enum JobStatus {
325
355
  failed
326
356
  }
327
357
 
328
- enum JobReason {
329
- upload
330
- rerun
331
- backfill
332
- }
333
-
334
358
  // =============================================================================
335
359
  // Job Stats Rollup (issue #255, epic #254)
336
360
  // =============================================================================
@@ -729,3 +753,8 @@ extend model User {
729
753
  workerNodes WorkerNode[] @relation("UserWorkerNodes")
730
754
  nodeCredentials NodeCredential[] @relation("UserNodeCredentials")
731
755
  }
756
+
757
+ extend model Organization {
758
+ // The organization's jobs (issue #734): see `Job.orgId` for why `SetNull`.
759
+ jobs Job[]
760
+ }
@@ -79,6 +79,9 @@
79
79
  // filter on both columns, from an account's delivery history view.
80
80
  // - [status, createdAt]: "what failed recently?" — status = 'failed'
81
81
  // filtered and ordered by recency, for on-call triage.
82
+ // @extensible — back-relations only, added with "extend model NotificationDelivery { ... }" in a
83
+ // fragment (an app's own delivery annotations, for example a provider-specific receipt).
84
+ // The delivery ledger itself (status, error, provider id) stays the platform's.
82
85
  model NotificationDelivery {
83
86
  id String @id @default(uuid()) @db.Uuid
84
87
  eventKey String @map("event_key")
@@ -153,6 +156,11 @@ enum NotificationDeliveryStatus {
153
156
  // different questions for different audiences and are kept apart.
154
157
  // =============================================================================
155
158
 
159
+ // @extensible — back-relations only, added with "extend model Notification { ... }" in a
160
+ // fragment (an app's own side table keyed by a notification, for example a per-notification
161
+ // follow-up). A user-owned row: the table has no organization column, so a plain foreign
162
+ // key on `id` is the right shape. `onDelete: Cascade` on the app side keeps the retention
163
+ // sweep (`notifications.inbox.purge`) working.
156
164
  model Notification {
157
165
  id String @id @default(uuid()) @db.Uuid
158
166
  // NOT NULL, unlike NotificationDelivery.userId. An inbox belongs to an
@@ -334,6 +342,18 @@ model PushSubscription {
334
342
  // subscription has never had one.
335
343
  lastSuccessAt DateTime? @map("last_success_at") @db.Timestamptz
336
344
 
345
+ // Which surface registered this subscription (#746, PP-9.4; harvested from
346
+ // EvoPath #312): `browser` (a browser tab or installed PWA) or `android_app`
347
+ // (the Android companion's Trusted Web Activity). The `android_app`
348
+ // notification channel pushes to these rows alone; `push` keeps meaning
349
+ // every subscription. A re-post of the same endpoint as `android_app`
350
+ // re-tags a `browser` row, a `browser` re-post never downgrades an
351
+ // `android_app` row (push-subscription.service.ts). The CHECK constraint
352
+ // `push_subscriptions_platform_check` lives in the migration SQL only
353
+ // (Prisma cannot express one; see PUSH_SUBSCRIPTION_PLATFORMS in the
354
+ // notifications contract).
355
+ platform String @default("browser")
356
+
337
357
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
338
358
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
339
359
 
@@ -583,11 +603,26 @@ model NotificationBroadcast {
583
603
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
584
604
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
585
605
 
606
+ // The audience's organization (#738, PP-8.5). NULL = every active user of
607
+ // the deployment (a system broadcast, as before #738); set = the ACTIVE
608
+ // members of that organization only. Read by the start and chunk handlers
609
+ // from the row (the job payloads carry only the broadcast id, unchanged), so
610
+ // `audienceWhere(cutoff, targetOrgId)` and the keyset cursor stay one query.
611
+ // No row-level security on this table: a system broadcast belongs to no
612
+ // organization, and RLS would hide it from the job that delivers it; the
613
+ // API authorizes `targetOrgId` instead (`broadcasts:*` may name any org,
614
+ // `org_broadcasts:*` only the caller's active org). CASCADE: an
615
+ // organization's broadcasts have no audience once it is deleted.
616
+ targetOrgId String? @map("target_org_id") @db.Uuid
617
+
586
618
  // Relations
587
- createdBy User? @relation("BroadcastAuthor", fields: [createdById], references: [id], onDelete: SetNull)
619
+ createdBy User? @relation("BroadcastAuthor", fields: [createdById], references: [id], onDelete: SetNull)
620
+ targetOrg Organization? @relation("BroadcastTargetOrg", fields: [targetOrgId], references: [id], onDelete: Cascade)
588
621
 
589
622
  @@index([status, scheduledFor])
590
623
  @@index([createdAt(sort: Desc)])
624
+ // A holder of only `org_broadcasts:read` lists its organization's broadcasts.
625
+ @@index([targetOrgId])
591
626
  @@map("notification_broadcasts")
592
627
  }
593
628
 
@@ -608,3 +643,7 @@ extend model User {
608
643
  pushSubscriptions PushSubscription[] @relation("UserPushSubscriptions")
609
644
  broadcastsCreated NotificationBroadcast[] @relation("BroadcastAuthor")
610
645
  }
646
+
647
+ extend model Organization {
648
+ notificationBroadcasts NotificationBroadcast[] @relation("BroadcastTargetOrg")
649
+ }
@@ -29,7 +29,32 @@ model UserSettings {
29
29
  @@map("user_settings")
30
30
  }
31
31
 
32
+ // One organization's overrides of the org-overridable system settings
33
+ // namespaces (#733): `{ "<namespace>": { "<field>": value } }`, only the fields
34
+ // each namespace's `org.schema` allows. An org table: FORCEd row-level security
35
+ // on org_id (`org_settings_org_isolation`, migration 0028_add_org_settings),
36
+ // reached only through `runInOrg`. Its own `version` for If-Match.
37
+ model OrgSettings {
38
+ id String @id @default(uuid()) @db.Uuid
39
+ orgId String @unique @map("org_id") @db.Uuid
40
+ value Json @db.JsonB
41
+ version Int @default(1)
42
+ updatedByUserId String? @map("updated_by_user_id") @db.Uuid
43
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
44
+
45
+ // Relations
46
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
47
+ updatedByUser User? @relation("OrgSettingsUpdater", fields: [updatedByUserId], references: [id], onDelete: SetNull)
48
+
49
+ @@map("org_settings")
50
+ }
51
+
32
52
  extend model User {
33
53
  userSettings UserSettings?
34
54
  settingsUpdates SystemSettings[] @relation("SettingsUpdater")
55
+ orgSettingsUpdates OrgSettings[] @relation("OrgSettingsUpdater")
56
+ }
57
+
58
+ extend model Organization {
59
+ settings OrgSettings?
35
60
  }
@@ -0,0 +1,223 @@
1
+ // =============================================================================
2
+ // Sharing: groups (PP-7.1, issue #728) and grants (PP-7.2, issue #729)
3
+ // =============================================================================
4
+ //
5
+ // A GROUP is a set of users INSIDE ONE ORGANIZATION that can own and share
6
+ // content (spec decision D6: groups are sharing groups, never tenants). Every
7
+ // row carries `org_id` and falls under the organization row-level-security
8
+ // model of `0025_org_scoped_rls`: the three tables `ENABLE` and `FORCE ROW
9
+ // LEVEL SECURITY` with one `<table>_org_isolation` policy each (migration
10
+ // `0026_add_groups`, listed in `rls-policies.json`).
11
+ //
12
+ // A member row and an invite row reach their group through the COMPOSITE key
13
+ // `(group_id, org_id)` -> `groups (id, org_id)`: a foreign-key check bypasses
14
+ // row-level security, so a plain key would let one organization store a
15
+ // reference to another organization's group, and the composite key also
16
+ // guarantees `group_members.org_id = groups.org_id`.
17
+ //
18
+ // `group_invites_pending_uniq_idx` (one PENDING invite per group and address)
19
+ // exists only in migration SQL: it is a partial unique index, which Prisma
20
+ // cannot express. Never "fix" the drift with `@@unique([groupId, email])`: a
21
+ // declined or revoked address must be invitable again.
22
+ //
23
+ // The names below are part of the public contract once released.
24
+ // =============================================================================
25
+
26
+ // The member and invite `role` columns are plain text (migration
27
+ // `0037_open_sharing_vocabularies`): the vocabulary is the API's group-role
28
+ // registry (`registerGroupRole`), which ships `admin` (manage the group, its
29
+ // members and invites; full rights on group-owned resources), `editor` (write
30
+ // on group-owned resources, MemoriaHub "collaborator") and `viewer` (read).
31
+ // A row must outlive the registry that produced it, so there is no CHECK.
32
+
33
+ // @extensible — back-relations only, added with "extend model Group { ... }" in a fragment
34
+ model Group {
35
+ id String @id @default(uuid()) @db.Uuid
36
+ orgId String @map("org_id") @db.Uuid
37
+ name String
38
+ description String?
39
+ /// Apps keep extra fields here (spec: never add columns to package-owned tables).
40
+ metadata Json? @db.JsonB
41
+ createdById String? @map("created_by_id") @db.Uuid
42
+ // Optimistic concurrency for PATCH (If-Match), per docs/API.md.
43
+ version Int @default(1)
44
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
45
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
46
+
47
+ // Relations
48
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
49
+ createdBy User? @relation("GroupCreatedBy", fields: [createdById], references: [id], onDelete: SetNull)
50
+ members GroupMember[]
51
+ invites GroupInvite[]
52
+ grants Grant[]
53
+
54
+ // The target of the members' and invites' composite foreign keys.
55
+ @@unique([id, orgId])
56
+ @@index([orgId])
57
+ @@map("groups")
58
+ }
59
+
60
+ model GroupMember {
61
+ id String @id @default(uuid()) @db.Uuid
62
+ groupId String @map("group_id") @db.Uuid
63
+ userId String @map("user_id") @db.Uuid
64
+ // Denormalised for row-level security; equal to groups.org_id by the
65
+ // composite foreign key below.
66
+ orgId String @map("org_id") @db.Uuid
67
+ /// A registered group role id (`registerGroupRole`). A plain string: a row must outlive the registry that produced it.
68
+ role String @default("viewer")
69
+ addedById String? @map("added_by_id") @db.Uuid
70
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
71
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
72
+
73
+ // Relations
74
+ //
75
+ // Composite: (group_id, org_id) -> groups (id, org_id).
76
+ group Group @relation(fields: [groupId, orgId], references: [id, orgId], onDelete: Cascade)
77
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
78
+ user User @relation("GroupMemberUser", fields: [userId], references: [id], onDelete: Cascade)
79
+ addedBy User? @relation("GroupMemberAddedBy", fields: [addedById], references: [id], onDelete: SetNull)
80
+
81
+ @@unique([groupId, userId])
82
+ @@index([userId])
83
+ @@index([orgId])
84
+ @@map("group_members")
85
+ }
86
+
87
+ model GroupInvite {
88
+ id String @id @default(uuid()) @db.Uuid
89
+ groupId String @map("group_id") @db.Uuid
90
+ orgId String @map("org_id") @db.Uuid
91
+ // Stored lower-cased. At most one PENDING invite per (group, email):
92
+ // group_invites_pending_uniq_idx, raw SQL only.
93
+ email String
94
+ /// The role the invitee gets on acceptance: a registered group role id. A plain string.
95
+ role String @default("viewer")
96
+ invitedById String? @map("invited_by_id") @db.Uuid
97
+ // NULL: no expiry. Expiry is evaluated when the invite is read; no sweep.
98
+ expiresAt DateTime? @map("expires_at") @db.Timestamptz
99
+ acceptedAt DateTime? @map("accepted_at") @db.Timestamptz
100
+ acceptedById String? @map("accepted_by_id") @db.Uuid
101
+ declinedAt DateTime? @map("declined_at") @db.Timestamptz
102
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
103
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
104
+
105
+ // Relations
106
+ //
107
+ // Composite: (group_id, org_id) -> groups (id, org_id).
108
+ group Group @relation(fields: [groupId, orgId], references: [id, orgId], onDelete: Cascade)
109
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
110
+ invitedBy User? @relation("GroupInviteInvitedBy", fields: [invitedById], references: [id], onDelete: SetNull)
111
+ acceptedBy User? @relation("GroupInviteAcceptedBy", fields: [acceptedById], references: [id], onDelete: SetNull)
112
+
113
+ @@index([email])
114
+ @@index([groupId])
115
+ @@index([orgId])
116
+ @@map("group_invites")
117
+ }
118
+
119
+ // =============================================================================
120
+ // Sharing: grants (PP-7.2, issue #729)
121
+ // =============================================================================
122
+ //
123
+ // A GRANT shares ONE record of a registered resource type with a user, a
124
+ // group of the same organization or (#730) a link, with a role and an
125
+ // optional expiry. The resource is POLYMORPHIC, `(resource_type,
126
+ // resource_id)`, with no foreign key: the platform cannot know app tables.
127
+ // Integrity comes from `GrantsService.deleteForResources()` (called inside the
128
+ // app's delete transaction) and the `sharing.grants.prune` job.
129
+ //
130
+ // Revocation is SOFT (`revoked_at`, `revoked_by_id`) so the audit trail
131
+ // survives; the prune job deletes revoked and expired rows after the
132
+ // retention period.
133
+ //
134
+ // Raw SQL only (migration `0027_add_grants`, intentional schema drift):
135
+ // grants_active_user_uniq_idx one ACTIVE grant per (resource, user)
136
+ // grants_active_group_uniq_idx one ACTIVE grant per (resource, group)
137
+ // grants_grantee_consistency_check the grantee columns match grantee_kind
138
+ // grants_active_ref_uniq_idx one ACTIVE grant per (resource, app kind, reference) (0037)
139
+ // Never "fix" the drift with `@@unique`, and never replace the indexes with a
140
+ // `findFirst` pre-check: the service upserts on them.
141
+ //
142
+ // The group grantee reaches its group through the COMPOSITE key
143
+ // `(grantee_group_id, org_id)` -> `groups (id, org_id)`, so a grant can never
144
+ // point at another organization's group (a foreign-key check bypasses
145
+ // row-level security).
146
+ // =============================================================================
147
+
148
+ // `grants.grantee_kind` is plain text (migration `0037_open_sharing_vocabularies`):
149
+ // the platform ships `user` (one user of the resource's organization), `group`
150
+ // (one group of the organization) and `link` (anyone holding the link token,
151
+ // #730), and an app registers more with `registerGranteeKind`. A grant of an
152
+ // app kind stores its reference in `grantee_ref` and leaves the three
153
+ // built-in grantee columns NULL; `grants_grantee_consistency_check` allows
154
+ // exactly those four shapes and `grants_active_ref_uniq_idx` keeps one ACTIVE
155
+ // grant per (resource, kind, reference).
156
+
157
+ // @extensible — back-relations only, added with "extend model Grant { ... }" in a fragment
158
+ // (an app's own annotation of a grant, for example an approval record). The table is
159
+ // org-owned with row-level security forced, so a table of the app's that holds `org_id`
160
+ // links with a composite foreign key `(grant_id, org_id)` -> `grants (id, org_id)`; the
161
+ // `@@unique([id, orgId])` below exists for it. The two partial unique indexes of the
162
+ // table stay raw SQL (never an `@@unique` on their columns).
163
+ model Grant {
164
+ id String @id @default(uuid()) @db.Uuid
165
+ orgId String @map("org_id") @db.Uuid
166
+ /// Registered resource type id. Permanent once rows exist, like a job type string.
167
+ resourceType String @map("resource_type")
168
+ resourceId String @map("resource_id") @db.Uuid
169
+ /// `user`, `group`, `link` or a registered app kind. A plain string: a row must outlive the registry that produced it.
170
+ granteeKind String @map("grantee_kind")
171
+ granteeUserId String? @map("grantee_user_id") @db.Uuid
172
+ granteeGroupId String? @map("grantee_group_id") @db.Uuid
173
+ /// The reference of an app-registered grantee kind (a domain, a team id), as its `validateGrantee` normalised it. NULL for the built-in kinds.
174
+ granteeRef String? @map("grantee_ref")
175
+ /// One of the resource type's registered roles. A plain string: a row must outlive the registry that produced it.
176
+ role String
177
+ /// Link grants only (#730): SHA-256 of the token, and the token encrypted with the platform secret cipher.
178
+ linkTokenHash String? @unique @map("link_token_hash")
179
+ linkTokenCiphertext String? @map("link_token_ciphertext") @db.Text
180
+ linkLabel String? @map("link_label")
181
+ expiresAt DateTime? @map("expires_at") @db.Timestamptz
182
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
183
+ revokedById String? @map("revoked_by_id") @db.Uuid
184
+ grantedById String? @map("granted_by_id") @db.Uuid
185
+ /// Apps keep extra fields here (spec: never add columns to package-owned tables).
186
+ metadata Json? @db.JsonB
187
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
188
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
189
+
190
+ // Relations
191
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
192
+ granteeUser User? @relation("GrantGranteeUser", fields: [granteeUserId], references: [id], onDelete: Cascade)
193
+ // Composite: (grantee_group_id, org_id) -> groups (id, org_id).
194
+ granteeGroup Group? @relation(fields: [granteeGroupId, orgId], references: [id, orgId], onDelete: Cascade)
195
+ revokedBy User? @relation("GrantRevokedBy", fields: [revokedById], references: [id], onDelete: SetNull)
196
+ grantedBy User? @relation("GrantGrantedBy", fields: [grantedById], references: [id], onDelete: SetNull)
197
+
198
+ @@index([resourceType, resourceId])
199
+ @@index([granteeUserId])
200
+ @@index([granteeGroupId])
201
+ @@index([orgId])
202
+ // The target of an app table's composite foreign key (id, org_id); see the note above the model.
203
+ @@unique([id, orgId])
204
+ @@map("grants")
205
+ }
206
+
207
+ extend model User {
208
+ groupsCreated Group[] @relation("GroupCreatedBy")
209
+ groupMemberships GroupMember[] @relation("GroupMemberUser")
210
+ groupMembersAdded GroupMember[] @relation("GroupMemberAddedBy")
211
+ groupInvitesSent GroupInvite[] @relation("GroupInviteInvitedBy")
212
+ groupInvitesClaimed GroupInvite[] @relation("GroupInviteAcceptedBy")
213
+ grantsReceived Grant[] @relation("GrantGranteeUser")
214
+ grantsRevoked Grant[] @relation("GrantRevokedBy")
215
+ grantsGiven Grant[] @relation("GrantGrantedBy")
216
+ }
217
+
218
+ extend model Organization {
219
+ groups Group[]
220
+ groupMembers GroupMember[]
221
+ groupInvites GroupInvite[]
222
+ grants Grant[]
223
+ }
@@ -23,16 +23,30 @@ model StorageObject {
23
23
  s3UploadId String? @map("s3_upload_id") // S3 multipart upload ID
24
24
  metadata Json? // JSONB for flexible metadata
25
25
  uploadedById String? @map("uploaded_by_id") @db.Uuid
26
+ // The organization the object belongs to (#725). NOT NULL, row-level
27
+ // security forced (policy `storage_objects_org_isolation`, see
28
+ // `0025_org_scoped_rls`). `Restrict`: an organization with objects cannot be
29
+ // deleted until they are purged deliberately.
30
+ orgId String @map("org_id") @db.Uuid
26
31
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
27
32
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
28
33
 
29
34
  // Relations
30
35
  uploadedBy User? @relation("UserStorageObjects", fields: [uploadedById], references: [id], onDelete: SetNull)
36
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Restrict)
31
37
  chunks StorageObjectChunk[]
32
38
 
39
+ // The target of the chunks' composite foreign key (object_id, org_id): a
40
+ // reference between two org-owned tables is composite, because a foreign-key
41
+ // check bypasses row-level security (ADR 0002 D5).
42
+ @@unique([id, orgId])
33
43
  @@index([uploadedById])
34
44
  @@index([status])
35
45
  @@index([createdAt])
46
+ // The policy filter `org_id = X` leads every query; these serve the hot paths
47
+ // behind it (a user's list, newest first; the cleanup sweep by status).
48
+ @@index([orgId, uploadedById, createdAt])
49
+ @@index([orgId, status])
36
50
  @@map("storage_objects")
37
51
  }
38
52
 
@@ -42,16 +56,29 @@ model StorageObjectChunk {
42
56
  partNumber Int @map("part_number") // S3 part number (1-10000)
43
57
  eTag String @map("e_tag") // S3 ETag for verification
44
58
  size BigInt // Chunk size in bytes
59
+ // The organization of the parent object (#725), carried here because a policy
60
+ // cannot join through the parent. NOT NULL, row-level security forced.
61
+ orgId String @map("org_id") @db.Uuid
45
62
  uploadedAt DateTime @default(now()) @map("uploaded_at") @db.Timestamptz
46
63
 
47
64
  // Relations
48
- object StorageObject @relation(fields: [objectId], references: [id], onDelete: Cascade)
65
+ //
66
+ // Composite: (object_id, org_id) -> storage_objects (id, org_id), so a chunk
67
+ // can never name another organization's object. Cascade, as before.
68
+ object StorageObject @relation(fields: [objectId, orgId], references: [id, orgId], onDelete: Cascade)
69
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Restrict)
49
70
 
50
71
  @@unique([objectId, partNumber])
51
72
  @@index([objectId])
73
+ @@index([orgId, objectId])
52
74
  @@map("storage_object_chunks")
53
75
  }
54
76
 
55
77
  extend model User {
56
78
  storageObjects StorageObject[] @relation("UserStorageObjects")
57
79
  }
80
+
81
+ extend model Organization {
82
+ storageObjects StorageObject[]
83
+ storageObjectChunks StorageObjectChunk[]
84
+ }