@marinoscar/platform-db 0.1.0-next.3 → 0.1.0-next.30

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 (132) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +158 -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/0038_add_worker_node_events/migration.sql +21 -0
  114. package/migrations/0039_add_webhooks/migration.sql +125 -0
  115. package/migrations/0040_add_alerts/migration.sql +66 -0
  116. package/migrations/0041_notifications_state_counted/migration.sql +19 -0
  117. package/migrations/0042_add_storage_migrations/migration.sql +130 -0
  118. package/migrations/manifest.json +185 -0
  119. package/package.json +5 -2
  120. package/raw-sql-indexes.json +72 -0
  121. package/rls-policies.json +102 -0
  122. package/schema/ai.prisma +59 -2
  123. package/schema/alerts.prisma +75 -0
  124. package/schema/android-app.prisma +47 -0
  125. package/schema/credentials.prisma +62 -0
  126. package/schema/identity.prisma +34 -1
  127. package/schema/jobs.prisma +69 -7
  128. package/schema/notifications.prisma +84 -5
  129. package/schema/settings.prisma +25 -0
  130. package/schema/sharing.prisma +223 -0
  131. package/schema/storage.prisma +143 -4
  132. package/schema/webhooks.prisma +108 -0
@@ -0,0 +1,102 @@
1
+ {
2
+ "policies": [
3
+ {
4
+ "name": "storage_objects_org_isolation",
5
+ "table": "storage_objects",
6
+ "reason": "Organization isolation: a row is visible only when org_id equals the transaction-local app.org_id (or the transaction carries app.rls_bypass). Prisma cannot express policies.",
7
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
8
+ "createdIn": "0025_org_scoped_rls"
9
+ },
10
+ {
11
+ "name": "storage_object_chunks_org_isolation",
12
+ "table": "storage_object_chunks",
13
+ "reason": "Organization isolation of upload parts; the chunk carries its own org_id because a policy cannot join through its parent.",
14
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
15
+ "createdIn": "0025_org_scoped_rls"
16
+ },
17
+ {
18
+ "name": "ai_runs_org_isolation",
19
+ "table": "ai_runs",
20
+ "reason": "Organization isolation of background AI runs, whose request column holds the full prompt.",
21
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
22
+ "createdIn": "0025_org_scoped_rls"
23
+ },
24
+ {
25
+ "name": "ai_usage_events_org_isolation",
26
+ "table": "ai_usage_events",
27
+ "reason": "Organization isolation of AI usage accounting; a row with a NULL org_id is visible to the bypass (system) client only.",
28
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
29
+ "createdIn": "0025_org_scoped_rls"
30
+ },
31
+ {
32
+ "name": "groups_org_isolation",
33
+ "table": "groups",
34
+ "reason": "Organization isolation of sharing groups (PP-7.1): a group lives inside one organization and is never a tenant.",
35
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
36
+ "createdIn": "0026_add_groups"
37
+ },
38
+ {
39
+ "name": "group_members_org_isolation",
40
+ "table": "group_members",
41
+ "reason": "Organization isolation of group memberships; the row carries the group's org_id (composite key to groups) because a policy cannot join through its parent.",
42
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
43
+ "createdIn": "0026_add_groups"
44
+ },
45
+ {
46
+ "name": "group_invites_org_isolation",
47
+ "table": "group_invites",
48
+ "reason": "Organization isolation of group invitations, which hold invitee e-mail addresses.",
49
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
50
+ "createdIn": "0026_add_groups"
51
+ },
52
+ {
53
+ "name": "grants_org_isolation",
54
+ "table": "grants",
55
+ "reason": "Organization isolation of grants (PP-7.2): a grant shares one record inside its organization and can never name another organization's user or group.",
56
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
57
+ "createdIn": "0027_add_grants"
58
+ },
59
+ {
60
+ "name": "org_settings_org_isolation",
61
+ "table": "org_settings",
62
+ "reason": "Organization isolation of an organization's settings overrides (PP-8.1): one row per organization, read and written only inside runInOrg.",
63
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
64
+ "createdIn": "0028_add_org_settings"
65
+ },
66
+ {
67
+ "name": "org_credentials_org_isolation",
68
+ "table": "org_credentials",
69
+ "reason": "Organization isolation of organization-owned encrypted credentials (PP-8.8): an org's key is visible only inside that organization's scope.",
70
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
71
+ "createdIn": "0029_add_org_credentials"
72
+ },
73
+ {
74
+ "name": "webhook_endpoints_org_isolation",
75
+ "table": "webhook_endpoints",
76
+ "reason": "Organization isolation of outbound webhook endpoints (#1046); a system-scope endpoint has a NULL org_id and is visible to the bypass (system) client only.",
77
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
78
+ "createdIn": "0039_add_webhooks"
79
+ },
80
+ {
81
+ "name": "webhook_deliveries_org_isolation",
82
+ "table": "webhook_deliveries",
83
+ "reason": "Organization isolation of webhook delivery attempts, whose payload is the event body sent; the row carries the endpoint's org_id because a policy cannot join through its parent.",
84
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
85
+ "createdIn": "0039_add_webhooks"
86
+ },
87
+ {
88
+ "name": "storage_migration_runs_org_isolation",
89
+ "table": "storage_migration_runs",
90
+ "reason": "Organization isolation of copy-only storage provider migration runs (#1093); a deployment-wide run has a NULL org_id and is visible to the bypass (system) client only.",
91
+ "doc": "docs/specs/storage-providers.md",
92
+ "createdIn": "0042_add_storage_migrations"
93
+ },
94
+ {
95
+ "name": "storage_migration_items_org_isolation",
96
+ "table": "storage_migration_items",
97
+ "reason": "Organization isolation of the per-object rows of a storage migration run; the row carries its object's org_id because a policy cannot join through its parent.",
98
+ "doc": "docs/specs/storage-providers.md",
99
+ "createdIn": "0042_add_storage_migrations"
100
+ }
101
+ ]
102
+ }
package/schema/ai.prisma CHANGED
@@ -224,6 +224,11 @@ model UserAiKey {
224
224
  // the record `#432`'s job handler(s) read from and write progress/output to.
225
225
  // This issue is schema only, matching every other table in this section: no
226
226
  // enqueue path, no job handler and no controller exists yet.
227
+ // @extensible — back-relations only, added with "extend model AiRun { ... }" in a fragment
228
+ // (an app's own annotation of a run, for example a review verdict). The table is org-owned
229
+ // with row-level security forced, so a table of the app's that holds `org_id` links to a run
230
+ // with a composite foreign key `(ai_run_id, org_id)` -> `ai_runs (id, org_id)`; the
231
+ // `@@unique([id, orgId])` below exists for it.
227
232
  model AiRun {
228
233
  id String @id @default(uuid()) @db.Uuid
229
234
 
@@ -271,17 +276,39 @@ model AiRun {
271
276
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
272
277
  completedAt DateTime? @map("completed_at") @db.Timestamptz
273
278
 
279
+ // The organization the run belongs to (#725). NOT NULL, row-level security
280
+ // forced (policy `ai_runs_org_isolation`). `Restrict`, not `SetNull`: the
281
+ // column is NOT NULL, so history cannot survive an organization's deletion
282
+ // by nulling it; deleting an organization first purges its runs.
283
+ orgId String @map("org_id") @db.Uuid
284
+
285
+ // The registered AI feature the run was started for (`registerAiFeature`,
286
+ // PP-14.17, #935): a bounded id the feature registry validated, NEVER free
287
+ // text. Nullable (a run started without a feature, and every row written
288
+ // before this column existed), and a plain string rather than a reference:
289
+ // a feature is code, not data, and a row must outlive the feature that
290
+ // wrote it. Carried onto the run's usage rows, so per-feature usage is
291
+ // answerable from the database.
292
+ feature String?
293
+
274
294
  // Relations
275
295
  //
276
296
  // SetNull — see the block comment above this section.
277
- user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
297
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
298
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Restrict)
278
299
 
279
300
  // "This user's run history, most recent first" — the one query this table
280
301
  // is known to need today (a user's own run list).
281
302
  @@index([userId, createdAt])
303
+ // The same query behind the policy filter `org_id = X`.
304
+ @@index([orgId, userId, createdAt])
282
305
  // The retention sweep (`ai.runs.purge`, #681): "oldest first, older than
283
306
  // the cutoff" across every user, which `[userId, createdAt]` cannot serve.
284
307
  @@index([createdAt])
308
+ // The target of an app table's composite foreign key (id, org_id), like
309
+ // `Group` and `StorageObject`: a plain FK on `id` would let a row of one
310
+ // organization point at another's (an FK check bypasses row-level security).
311
+ @@unique([id, orgId])
285
312
  @@map("ai_runs")
286
313
  }
287
314
 
@@ -353,12 +380,35 @@ model AiUsageEvent {
353
380
 
354
381
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
355
382
 
383
+ // The organization that incurred the call (#725). Nullable on purpose: a
384
+ // deployment-wide event (a catalogue sync) has none, and `SetNull` keeps the
385
+ // history of a deleted organization. Row-level security forced (policy
386
+ // `ai_usage_events_org_isolation`): a NULL row is visible to the system
387
+ // client only.
388
+ orgId String? @map("org_id") @db.Uuid
389
+
390
+ // The registered AI feature the call was made for (`registerAiFeature`,
391
+ // PP-14.17, #935), so usage can be filtered and grouped per feature from
392
+ // the database. Nullable: a call made without a feature, a catalogue sync,
393
+ // and every row written before this column existed have none. A plain
394
+ // string, never a reference, and never free text: only an id the feature
395
+ // registry validated is written.
396
+ feature String?
397
+
356
398
  // Relations
357
- user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
399
+ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
400
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: SetNull)
358
401
 
359
402
  // "This user's usage history, most recent first" — mirrors `AiRun`'s own
360
403
  // index for the identical reason.
361
404
  @@index([userId, createdAt])
405
+ // The same query behind the policy filter `org_id = X`, and the per-org
406
+ // usage window.
407
+ @@index([orgId, userId, createdAt])
408
+ @@index([orgId, createdAt])
409
+ // "This organization's usage of one feature in a window" (PP-14.17, #935):
410
+ // the per-feature filter and group-by of the usage report.
411
+ @@index([orgId, feature, createdAt])
362
412
  // "Usage across all users in a time window" — the deployment-wide
363
413
  // accounting/billing query, independent of any one user.
364
414
  @@index([createdAt])
@@ -385,3 +435,10 @@ extend model User {
385
435
  aiRuns AiRun[]
386
436
  aiUsageEvents AiUsageEvent[]
387
437
  }
438
+
439
+ extend model Organization {
440
+ // AI runs and usage events (#725): see `AiRun.orgId` and `AiUsageEvent.orgId`
441
+ // for why one is `Restrict` and the other `SetNull`.
442
+ aiRuns AiRun[]
443
+ aiUsageEvents AiUsageEvent[]
444
+ }
@@ -0,0 +1,75 @@
1
+ // =============================================================================
2
+ // Alerts (issue #1047)
3
+ // =============================================================================
4
+ //
5
+ // DEPLOYMENT-LEVEL tables: a rule watches the deployment's telemetry and its
6
+ // worker-node fleet, which no organization owns, so there is NO row-level
7
+ // security on either table in v1. `org_id` is reserved on `alert_rules` for a
8
+ // later organization-scoped rule (NULL = a deployment rule, the only kind v1
9
+ // creates); it is not a foreign key yet, for the same reason.
10
+ //
11
+ // `created_by_id` and `acknowledged_by_id` are plain user ids with no relation:
12
+ // an incident outlives the administrator who acknowledged it, and deleting a
13
+ // user must not delete (or null) alert history through a cascade.
14
+ //
15
+ // ONE OPEN INCIDENT PER RULE AND LABEL SET is a raw-SQL partial unique index
16
+ // that exists only in the migration (listed in raw-sql-indexes.json):
17
+ // alert_incidents_open_uniq_idx ON alert_incidents (rule_id, labels_key)
18
+ // WHERE state IN ('pending', 'firing')
19
+ // Never "fix" it with @@unique or a findFirst pre-check.
20
+
21
+ /// An alert rule. `kind` is an open registry id (`registerAlertRuleKind`),
22
+ /// `config` is validated by that kind's schema in the API. `key` is the stable
23
+ /// key of a seeded starter rule (NULL for an administrator's own rule).
24
+ model AlertRule {
25
+ id String @id @default(uuid()) @db.Uuid
26
+ orgId String? @map("org_id") @db.Uuid
27
+ key String? @unique @db.VarChar(64)
28
+ name String @db.VarChar(120)
29
+ description String? @db.VarChar(500)
30
+ enabled Boolean @default(false)
31
+ kind String @db.VarChar(32)
32
+ severity String @db.VarChar(16)
33
+ config Json
34
+ forSeconds Int @default(0) @map("for_seconds")
35
+ cooldownSeconds Int @default(900) @map("cooldown_seconds")
36
+ notifyChannels String[] @default([]) @map("notify_channels")
37
+ webhook Boolean @default(true)
38
+ createdById String? @map("created_by_id") @db.Uuid
39
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
40
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
41
+ lastEvaluatedAt DateTime? @map("last_evaluated_at") @db.Timestamptz
42
+ lastError String? @map("last_error") @db.VarChar(500)
43
+
44
+ incidents AlertIncident[]
45
+
46
+ @@index([enabled, kind])
47
+ @@map("alert_rules")
48
+ }
49
+
50
+ /// One rule breached for one label set. `labels_key` is the canonical sorted
51
+ /// `k=v,k=v` of `labels` ('' when unlabelled), the identity within a rule.
52
+ model AlertIncident {
53
+ id String @id @default(uuid()) @db.Uuid
54
+ ruleId String @map("rule_id") @db.Uuid
55
+ labelsKey String @map("labels_key") @db.VarChar(512)
56
+ labels Json
57
+ state String @db.VarChar(16)
58
+ severity String @db.VarChar(16)
59
+ pendingSince DateTime? @map("pending_since") @db.Timestamptz
60
+ firedAt DateTime? @map("fired_at") @db.Timestamptz
61
+ resolvedAt DateTime? @map("resolved_at") @db.Timestamptz
62
+ lastValue Float? @map("last_value")
63
+ lastSeenAt DateTime @map("last_seen_at") @db.Timestamptz
64
+ summary String @db.VarChar(500)
65
+ acknowledgedAt DateTime? @map("acknowledged_at") @db.Timestamptz
66
+ acknowledgedById String? @map("acknowledged_by_id") @db.Uuid
67
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
68
+
69
+ rule AlertRule @relation(fields: [ruleId], references: [id], onDelete: Cascade)
70
+
71
+ @@index([ruleId, state])
72
+ @@index([state, firedAt])
73
+ @@index([resolvedAt])
74
+ @@map("alert_incidents")
75
+ }
@@ -0,0 +1,47 @@
1
+ /// An Android APK this deployment hosts (#746, PP-9.4; merged from EvoPath and
2
+ /// MemoriaHub). Uploaded by an administrator (the admin Android app page, or
3
+ /// `appctl android publish`), streamed into object storage under the
4
+ /// `android-releases/` key prefix, downloaded by signed-in users through a
5
+ /// short-lived signed link (`/api/android-app/download/<token>`).
6
+ ///
7
+ /// AT MOST ONE RELEASE IS CURRENT deployment-wide: the raw-SQL partial unique
8
+ /// index `android_app_releases_one_current_uniq_idx` (migration SQL only;
9
+ /// Prisma cannot express a partial unique index). Never declare it as
10
+ /// @@unique and never replace it with a findFirst pre-check: make-current
11
+ /// clears the old flag and sets the new one in one transaction, and the
12
+ /// database rejects a second current row (P2002, mapped to 409
13
+ /// RELEASE_CURRENT_CONFLICT).
14
+ ///
15
+ /// `sizeBytes` is BigInt (MemoriaHub's choice; EvoPath used Int): the API
16
+ /// returns it as a decimal string. `storageProvider` and `bucket` record where
17
+ /// the bytes were written (the DatabaseBackupRun precedent), so a doctor check
18
+ /// can tell a release stranded by a provider switch. A deployment artifact:
19
+ /// kept by the user-data reset (uploader SetNull) and by the factory reset
20
+ /// (its prefix is registered `survivesFactoryReset: true`).
21
+ model AndroidAppRelease {
22
+ id String @id @default(uuid()) @db.Uuid
23
+ packageName String @map("package_name")
24
+ versionName String @map("version_name") @db.VarChar(50)
25
+ versionCode Int @map("version_code")
26
+ signingSha256 String @map("signing_sha256")
27
+ fileSha256 String @map("file_sha256") @db.Char(64)
28
+ sizeBytes BigInt @map("size_bytes")
29
+ storageKey String @map("storage_key")
30
+ storageProvider String? @map("storage_provider")
31
+ bucket String?
32
+ notes String? @db.VarChar(2000)
33
+ isCurrent Boolean @default(false) @map("is_current")
34
+ uploadedById String? @map("uploaded_by_id") @db.Uuid
35
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
36
+
37
+ uploadedBy User? @relation("AndroidAppReleaseUploader", fields: [uploadedById], references: [id], onDelete: SetNull)
38
+
39
+ @@unique([packageName, versionCode])
40
+ @@index([createdAt])
41
+ @@index([uploadedById])
42
+ @@map("android_app_releases")
43
+ }
44
+
45
+ extend model User {
46
+ androidAppReleases AndroidAppRelease[] @relation("AndroidAppReleaseUploader")
47
+ }
@@ -19,6 +19,11 @@
19
19
  // enforces that split (a plaintext-returning method for server-side
20
20
  // consumers, a metadata-only method for presentation) — this comment is the
21
21
  // signpost, not the guarantee.
22
+ // @extensible — back-relations only, added with "extend model Credential { ... }" in a
23
+ // fragment, so an app can hang its own NON-SECRET bookkeeping on a deployment credential
24
+ // (which feature uses it, when it was last rotated). The `secret` column is never the
25
+ // app's to read or relate to: an app reads plaintext only through `CredentialsService`,
26
+ // and no app table may copy ciphertext or plaintext of it.
22
27
  model Credential {
23
28
  id String @id @default(uuid()) @db.Uuid
24
29
  purpose String
@@ -106,3 +111,60 @@ extend model User {
106
111
  // secret has no meaning once its owner is gone — see `UserCredential`.
107
112
  userCredentials UserCredential[] @relation("UserCredentials")
108
113
  }
114
+
115
+ // =============================================================================
116
+ // Organization-Owned Encrypted Credentials (issue #735, PP-8.8)
117
+ // =============================================================================
118
+ //
119
+ // The third tier: secrets OWNED BY ONE ORGANIZATION (an org's own AI provider
120
+ // key, an org's own storage or e-mail account), addressed by
121
+ // (orgId, purpose, name). It mirrors `UserCredential` exactly, with the owner
122
+ // an organization instead of a user.
123
+ //
124
+ // `secret` is the opaque [iv][authTag][ciphertext] payload `encryptSecret()`
125
+ // produces under the ORG-BOUND sub-key domain `org:<orgId>:<purpose>`
126
+ // (`orgCredentialPurpose()` in `@marinoscar/platform-api/core`): a ciphertext
127
+ // copied from one organization's row into another's fails GCM
128
+ // authentication.
129
+ //
130
+ // A plain composite unique suffices (no raw-SQL index): all three columns are
131
+ // NOT NULL. Its leading column serves every by-org lookup.
132
+ //
133
+ // TENANT DATA: `org_credentials` is an `org` table under FORCEd row-level
134
+ // security (`org_credentials_org_isolation`, as in 0025/0026), so every read
135
+ // and write runs in the owning organization's scope. Cascade with the
136
+ // organization; the last editor is provenance only (SetNull), as on
137
+ // `Credential`. `OrgCredentialsService` is the sole reader/writer; NEVER
138
+ // select `secret` into anything that reaches an API response or a log line.
139
+ // =============================================================================
140
+ model OrgCredential {
141
+ id String @id @default(uuid()) @db.Uuid
142
+ orgId String @map("org_id") @db.Uuid
143
+ purpose String
144
+ name String
145
+ // @db.Text for the same reason as `Credential.secret`: never truncate.
146
+ secret String @db.Text
147
+ // Non-secret display aid, derived from the plaintext on write.
148
+ hint String?
149
+ // Human-readable description. Admin-entered, non-secret.
150
+ label String?
151
+ updatedByUserId String? @map("updated_by_user_id") @db.Uuid
152
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
153
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
154
+
155
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
156
+ updatedByUser User? @relation("OrgCredentialUpdatedBy", fields: [updatedByUserId], references: [id], onDelete: SetNull)
157
+
158
+ @@unique([orgId, purpose, name])
159
+ @@map("org_credentials")
160
+ }
161
+
162
+ extend model User {
163
+ // Provenance on an organization's credential (issue #735). SetNull: an
164
+ // org's key outlives the administrator who last typed it in.
165
+ orgCredentialUpdates OrgCredential[] @relation("OrgCredentialUpdatedBy")
166
+ }
167
+
168
+ extend model Organization {
169
+ orgCredentials OrgCredential[]
170
+ }
@@ -13,6 +13,13 @@ model User {
13
13
  isActive Boolean @default(true) @map("is_active")
14
14
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
15
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
16
23
 
17
24
  // Relations
18
25
  identities UserIdentity[]
@@ -62,6 +69,10 @@ enum RoleScope {
62
69
  org
63
70
  }
64
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.
65
76
  model Role {
66
77
  id String @id @default(uuid()) @db.Uuid
67
78
  name String @unique
@@ -77,6 +88,12 @@ model Role {
77
88
  @@map("roles")
78
89
  }
79
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.
80
97
  model Permission {
81
98
  id String @id @default(uuid()) @db.Uuid
82
99
  name String @unique
@@ -124,14 +141,21 @@ model AuditEvent {
124
141
  targetType String @map("target_type")
125
142
  targetId String @map("target_id")
126
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
127
149
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
128
150
 
129
151
  // Relations
130
- actorUser User? @relation("ActorEvents", fields: [actorUserId], references: [id], onDelete: SetNull)
152
+ actorUser User? @relation("ActorEvents", fields: [actorUserId], references: [id], onDelete: SetNull)
153
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: SetNull)
131
154
 
132
155
  @@index([actorUserId])
133
156
  @@index([targetType, targetId])
134
157
  @@index([createdAt])
158
+ @@index([orgId, createdAt])
135
159
  @@map("audit_events")
136
160
  }
137
161
 
@@ -179,6 +203,7 @@ enum PatDurationUnit {
179
203
  months
180
204
  }
181
205
 
206
+ // @extensible — back-relations only, added with "extend model PersonalAccessToken { ... }" in a fragment
182
207
  model PersonalAccessToken {
183
208
  id String @id @default(uuid()) @db.Uuid
184
209
  userId String @map("user_id") @db.Uuid
@@ -329,6 +354,7 @@ enum InviteStatus {
329
354
  expired
330
355
  }
331
356
 
357
+ // @extensible — back-relations only, added with "extend model Organization { ... }" in a fragment
332
358
  model Organization {
333
359
  id String @id @default(uuid()) @db.Uuid
334
360
  name String
@@ -339,6 +365,11 @@ model Organization {
339
365
  createdById String? @map("created_by_id") @db.Uuid
340
366
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
341
367
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
368
+ // App-owned, namespaced fields (`registerOrganizationMetadataSchema`, PP-14.27); same
369
+ // contract as `User.metadata`: validated per namespace, no secrets, 16 KiB per row
370
+ // (32 KiB backstop `organizations_metadata_size_check`), never returned by the
371
+ // platform's routes.
372
+ metadata Json @default("{}") @db.JsonB
342
373
 
343
374
  // Relations
344
375
  createdBy User? @relation("OrganizationCreatedBy", fields: [createdById], references: [id], onDelete: SetNull)
@@ -347,6 +378,8 @@ model Organization {
347
378
  refreshTokens RefreshToken[]
348
379
  personalAccessTokens PersonalAccessToken[]
349
380
  deviceCodes DeviceCode[]
381
+ // Audit history outlives the organization (`SetNull`); system events have none (#725).
382
+ auditEvents AuditEvent[]
350
383
 
351
384
  @@map("organizations")
352
385
  }
@@ -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
  // =============================================================================
@@ -511,6 +535,10 @@ model WorkerNode {
511
535
  // this list from ever forcing a `Job` deletion.
512
536
  claimedJobs Job[] @relation("NodeClaimedJobs")
513
537
 
538
+ // Events the node reported about itself (power source changes, ...). Cascades
539
+ // with the node: an event has no meaning once its node is gone.
540
+ events WorkerNodeEvent[]
541
+
514
542
  // THE register-or-reattach anchor (#268's own words: "existing exactly
515
543
  // this way"). A node identifies itself to `/nodes/register` by
516
544
  // `(callerId, name)`; this is what lets that endpoint find-or-create
@@ -532,6 +560,35 @@ model WorkerNode {
532
560
  @@map("worker_nodes")
533
561
  }
534
562
 
563
+ // -----------------------------------------------------------------------------
564
+ // WorkerNodeEvent — an event a worker node reported about itself (#1045)
565
+ // -----------------------------------------------------------------------------
566
+ // `type` is an open registry key (e.g. `power.source_changed`), a plain string
567
+ // for the same reason `Job.type` is: a new event type costs zero migrations.
568
+ // `severity` is `info | warning | critical`, validated in the API. `attrs` is
569
+ // opaque node-supplied JSON, displayed and never filtered. `occurredAt` is the
570
+ // node's clock; `receivedAt` is the server's, so skew is visible. Cascades with
571
+ // the node. No row-level security (worker_nodes has none).
572
+ model WorkerNodeEvent {
573
+ id String @id @default(uuid()) @db.Uuid
574
+
575
+ nodeId String @map("node_id") @db.Uuid
576
+ node WorkerNode @relation(fields: [nodeId], references: [id], onDelete: Cascade)
577
+
578
+ type String @db.VarChar(64)
579
+ severity String @db.VarChar(16)
580
+ attrs Json? @db.JsonB
581
+
582
+ occurredAt DateTime @map("occurred_at") @db.Timestamptz
583
+ receivedAt DateTime @default(now()) @map("received_at") @db.Timestamptz
584
+
585
+ // "This node's newest events" — the fleet page's timeline.
586
+ @@index([nodeId, receivedAt(sort: Desc)])
587
+ // Retention sweeps by age.
588
+ @@index([receivedAt])
589
+ @@map("worker_node_events")
590
+ }
591
+
535
592
  enum NodeStatus {
536
593
  online
537
594
  draining
@@ -729,3 +786,8 @@ extend model User {
729
786
  workerNodes WorkerNode[] @relation("UserWorkerNodes")
730
787
  nodeCredentials NodeCredential[] @relation("UserNodeCredentials")
731
788
  }
789
+
790
+ extend model Organization {
791
+ // The organization's jobs (issue #734): see `Job.orgId` for why `SetNull`.
792
+ jobs Job[]
793
+ }