@marinoscar/platform-db 0.1.0-next.34 → 0.1.0-next.36

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @marinoscar/platform-db
2
2
 
3
+ ## 0.1.0-next.36
4
+
5
+ ## 0.1.0-next.35
6
+
7
+ ### Minor Changes
8
+
9
+ - fc11c39: Add the OAuth server's database schema (#1180, PP-15.2). `@marinoscar/platform-db` adds the `oauth.prisma` fragment and migration `0043_add_oauth_server` (`oauth_clients`, `oauth_authorization_requests`, `oauth_grants`, `oauth_authorization_codes`, `oauth_tokens` and the raw-SQL partial unique index `oauth_grants_active_uniq_idx`, at most one active grant per user, client and resource). The tables are user-owned and carry no row-level security. `@marinoscar/platform-api` classifies the five models in the manifest ownership and user-owned inventories (a grant is deleted with its user and exported presentation-safe; a client is kept) and adds their user-data purge hints. No route or service reads the tables yet.
10
+
3
11
  ## 0.1.0-next.34
4
12
 
5
13
  ## 0.1.0-next.33
package/README.md CHANGED
@@ -188,6 +188,7 @@ The migration tooling adds no row to the catalog. How an app extends the migrati
188
188
  | `sharing.prisma` | `Group` (`@extensible`), `GroupMember`, `GroupInvite` |
189
189
  | `webhooks.prisma` | `WebhookEndpoint`, `WebhookDelivery` (#1046: outbound webhook destinations and delivery attempts; nullable `org_id` under forced row-level security, NULL only for system scope; no secret column, the signing secret is in `credentials`) |
190
190
  | `android-app.prisma` | `AndroidAppRelease` (#746: the hosted Android APKs; `sizeBytes` BigInt; at most one current release through the raw-SQL index `android_app_releases_one_current_uniq_idx`) |
191
+ | `oauth.prisma` | `OAuthClient`, `OAuthAuthorizationRequest`, `OAuthGrant`, `OAuthAuthorizationCode`, `OAuthToken` (PP-15.2: the OAuth server's state; user-owned, no row-level security; at most one active grant per user, client and resource through the raw-SQL index `oauth_grants_active_uniq_idx`) |
191
192
 
192
193
  A slice declares the back-relations that point **into** another slice as `extend model` blocks in its own fragment (the 17 `User` fields that leave identity, and `Job.backupRun` in `db-backup.prisma`). Every block comment of the original schema is kept verbatim: they are the design documentation.
193
194
 
@@ -0,0 +1,161 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "OAuthClientKind" AS ENUM ('cimd', 'dynamic', 'registered');
3
+
4
+ -- CreateEnum
5
+ CREATE TYPE "OAuthRequestStatus" AS ENUM ('pending', 'approved', 'denied', 'expired');
6
+
7
+ -- CreateEnum
8
+ CREATE TYPE "OAuthTokenKind" AS ENUM ('access', 'refresh');
9
+
10
+ -- CreateTable
11
+ CREATE TABLE "oauth_clients" (
12
+ "id" UUID NOT NULL,
13
+ "client_id" TEXT NOT NULL,
14
+ "kind" "OAuthClientKind" NOT NULL,
15
+ "name" TEXT NOT NULL,
16
+ "client_uri" TEXT,
17
+ "logo_uri" TEXT,
18
+ "redirect_uris" JSONB NOT NULL,
19
+ "token_endpoint_auth_method" TEXT NOT NULL,
20
+ "secret_hash" TEXT,
21
+ "application_type" TEXT,
22
+ "host" TEXT NOT NULL,
23
+ "metadata_fetched_at" TIMESTAMPTZ,
24
+ "metadata_expires_at" TIMESTAMPTZ,
25
+ "created_by_user_id" UUID,
26
+ "disabled_at" TIMESTAMPTZ,
27
+ "last_used_at" TIMESTAMPTZ,
28
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
29
+
30
+ CONSTRAINT "oauth_clients_pkey" PRIMARY KEY ("id")
31
+ );
32
+
33
+ -- CreateTable
34
+ CREATE TABLE "oauth_authorization_requests" (
35
+ "id" UUID NOT NULL,
36
+ "client_id" UUID NOT NULL,
37
+ "redirect_uri" TEXT NOT NULL,
38
+ "scope" TEXT NOT NULL,
39
+ "state" TEXT,
40
+ "resource" TEXT NOT NULL,
41
+ "code_challenge" TEXT NOT NULL,
42
+ "code_challenge_method" TEXT NOT NULL,
43
+ "user_id" UUID,
44
+ "status" "OAuthRequestStatus" NOT NULL DEFAULT 'pending',
45
+ "expires_at" TIMESTAMPTZ NOT NULL,
46
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
47
+
48
+ CONSTRAINT "oauth_authorization_requests_pkey" PRIMARY KEY ("id")
49
+ );
50
+
51
+ -- CreateTable
52
+ CREATE TABLE "oauth_grants" (
53
+ "id" UUID NOT NULL,
54
+ "user_id" UUID NOT NULL,
55
+ "org_id" UUID,
56
+ "client_id" UUID NOT NULL,
57
+ "resource" TEXT NOT NULL,
58
+ "scopes" TEXT[],
59
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
60
+ "updated_at" TIMESTAMPTZ NOT NULL,
61
+ "last_used_at" TIMESTAMPTZ,
62
+ "revoked_at" TIMESTAMPTZ,
63
+ "revoked_reason" TEXT,
64
+
65
+ CONSTRAINT "oauth_grants_pkey" PRIMARY KEY ("id")
66
+ );
67
+
68
+ -- CreateTable
69
+ CREATE TABLE "oauth_authorization_codes" (
70
+ "id" UUID NOT NULL,
71
+ "code_hash" TEXT NOT NULL,
72
+ "grant_id" UUID NOT NULL,
73
+ "redirect_uri" TEXT NOT NULL,
74
+ "code_challenge" TEXT NOT NULL,
75
+ "scope" TEXT NOT NULL,
76
+ "resource" TEXT NOT NULL,
77
+ "expires_at" TIMESTAMPTZ NOT NULL,
78
+ "consumed_at" TIMESTAMPTZ,
79
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
80
+
81
+ CONSTRAINT "oauth_authorization_codes_pkey" PRIMARY KEY ("id")
82
+ );
83
+
84
+ -- CreateTable
85
+ CREATE TABLE "oauth_tokens" (
86
+ "id" UUID NOT NULL,
87
+ "kind" "OAuthTokenKind" NOT NULL,
88
+ "token_hash" TEXT NOT NULL,
89
+ "token_prefix" TEXT NOT NULL,
90
+ "grant_id" UUID NOT NULL,
91
+ "scopes" TEXT[],
92
+ "expires_at" TIMESTAMPTZ NOT NULL,
93
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
94
+ "last_used_at" TIMESTAMPTZ,
95
+ "rotated_at" TIMESTAMPTZ,
96
+ "replaced_by_id" UUID,
97
+ "revoked_at" TIMESTAMPTZ,
98
+
99
+ CONSTRAINT "oauth_tokens_pkey" PRIMARY KEY ("id")
100
+ );
101
+
102
+ -- CreateIndex
103
+ CREATE UNIQUE INDEX "oauth_clients_client_id_key" ON "oauth_clients"("client_id");
104
+
105
+ -- CreateIndex
106
+ CREATE INDEX "oauth_authorization_requests_client_id_idx" ON "oauth_authorization_requests"("client_id");
107
+
108
+ -- CreateIndex
109
+ CREATE INDEX "oauth_authorization_requests_expires_at_idx" ON "oauth_authorization_requests"("expires_at");
110
+
111
+ -- CreateIndex
112
+ CREATE INDEX "oauth_grants_user_id_idx" ON "oauth_grants"("user_id");
113
+
114
+ -- CreateIndex
115
+ CREATE INDEX "oauth_grants_client_id_idx" ON "oauth_grants"("client_id");
116
+
117
+ -- CreateIndex
118
+ CREATE INDEX "oauth_grants_org_id_idx" ON "oauth_grants"("org_id");
119
+
120
+ -- CreateIndex
121
+ CREATE UNIQUE INDEX "oauth_authorization_codes_code_hash_key" ON "oauth_authorization_codes"("code_hash");
122
+
123
+ -- CreateIndex
124
+ CREATE INDEX "oauth_authorization_codes_grant_id_idx" ON "oauth_authorization_codes"("grant_id");
125
+
126
+ -- CreateIndex
127
+ CREATE INDEX "oauth_authorization_codes_expires_at_idx" ON "oauth_authorization_codes"("expires_at");
128
+
129
+ -- CreateIndex
130
+ CREATE UNIQUE INDEX "oauth_tokens_token_hash_key" ON "oauth_tokens"("token_hash");
131
+
132
+ -- CreateIndex
133
+ CREATE INDEX "oauth_tokens_grant_id_idx" ON "oauth_tokens"("grant_id");
134
+
135
+ -- CreateIndex
136
+ CREATE INDEX "oauth_tokens_expires_at_idx" ON "oauth_tokens"("expires_at");
137
+
138
+ -- AddForeignKey
139
+ ALTER TABLE "oauth_clients" ADD CONSTRAINT "oauth_clients_created_by_user_id_fkey" FOREIGN KEY ("created_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
140
+
141
+ -- AddForeignKey
142
+ ALTER TABLE "oauth_authorization_requests" ADD CONSTRAINT "oauth_authorization_requests_client_id_fkey" FOREIGN KEY ("client_id") REFERENCES "oauth_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE;
143
+
144
+ -- AddForeignKey
145
+ ALTER TABLE "oauth_grants" ADD CONSTRAINT "oauth_grants_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
146
+
147
+ -- AddForeignKey
148
+ ALTER TABLE "oauth_grants" ADD CONSTRAINT "oauth_grants_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
149
+
150
+ -- AddForeignKey
151
+ ALTER TABLE "oauth_grants" ADD CONSTRAINT "oauth_grants_client_id_fkey" FOREIGN KEY ("client_id") REFERENCES "oauth_clients"("id") ON DELETE CASCADE ON UPDATE CASCADE;
152
+
153
+ -- AddForeignKey
154
+ ALTER TABLE "oauth_authorization_codes" ADD CONSTRAINT "oauth_authorization_codes_grant_id_fkey" FOREIGN KEY ("grant_id") REFERENCES "oauth_grants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
155
+
156
+ -- AddForeignKey
157
+ ALTER TABLE "oauth_tokens" ADD CONSTRAINT "oauth_tokens_grant_id_fkey" FOREIGN KEY ("grant_id") REFERENCES "oauth_grants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
158
+
159
+ -- At most one ACTIVE grant per (user, client, resource): a partial unique index
160
+ -- Prisma cannot express. Listed in packages/platform-db/raw-sql-indexes.json.
161
+ CREATE UNIQUE INDEX "oauth_grants_active_uniq_idx" ON "oauth_grants"("user_id", "client_id", "resource") WHERE "revoked_at" IS NULL;
@@ -421,5 +421,13 @@
421
421
  "sha256": "8d37841523a5b4737379df567d5ad3feb37abb0f29dcef416cd34f20167ba181",
422
422
  "since": "1.0.0",
423
423
  "slice": "storage"
424
+ },
425
+ {
426
+ "dir": "0043_add_oauth_server",
427
+ "id": "0043_add_oauth_server",
428
+ "requires": [],
429
+ "sha256": "cc1c32e853e0b559f27cdd2049862f3c5d7062a65506207b20fd3c24f1147d3e",
430
+ "since": "1.0.0",
431
+ "slice": "identity"
424
432
  }
425
433
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marinoscar/platform-db",
3
- "version": "0.1.0-next.34",
3
+ "version": "0.1.0-next.36",
4
4
  "description": "Prisma schema fragments, SQL migrations and seed functions of the platform (CommonJS).",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
@@ -116,6 +116,15 @@
116
116
  "reason": "At most one pending or running storage provider migration run deployment-wide: a constant-expression partial unique index Prisma cannot express. A concurrent second start loses on the index (409 with details.activeRunId), never a findFirst pre-check.",
117
117
  "doc": "docs/specs/storage-providers.md",
118
118
  "createdIn": "0042_add_storage_migrations"
119
+ },
120
+ {
121
+ "name": "oauth_grants_active_uniq_idx",
122
+ "table": "oauth_grants",
123
+ "unique": true,
124
+ "definition": "CREATE UNIQUE INDEX oauth_grants_active_uniq_idx ON public.oauth_grants USING btree (user_id, client_id, resource) WHERE (revoked_at IS NULL)",
125
+ "reason": "At most one ACTIVE (not revoked) OAuth grant per user, client and resource: a partial unique index Prisma cannot express. Consent upserts the active grant and treats a unique violation as 'already granted'; a revoked grant frees the slot for a new consent.",
126
+ "doc": "docs/specs/oauth-server.md",
127
+ "createdIn": "0043_add_oauth_server"
119
128
  }
120
129
  ]
121
130
  }
@@ -0,0 +1,184 @@
1
+ // =============================================================================
2
+ // OAuth server (PP-15.2, epic #1178)
3
+ // =============================================================================
4
+ //
5
+ // USER-OWNED tables, NOT row-level-security tables (same posture as
6
+ // `personal_access_tokens`): a client, a pending authorization request and a
7
+ // token are resolved BEFORE any organization scope exists (at /authorize and at
8
+ // the token endpoint, from a bearer value), so a policy on `org_id` could not
9
+ // be satisfied there. Access is guarded by service code. Do not add these
10
+ // tables to rls-policies.json.
11
+ //
12
+ // `oauth_clients` is deployment data (a client outlives the administrator who
13
+ // registered it: `created_by_user_id` is SET NULL). `oauth_grants` is one
14
+ // consent; its codes and tokens go with it (CASCADE), and a grant goes with its
15
+ // user, its client and its organization.
16
+ //
17
+ // NO SECRET MATERIAL: `secret_hash`, `code_hash` and `token_hash` are SHA-256 /
18
+ // hash values, never the secret, code or token itself.
19
+ //
20
+ // ONE ACTIVE GRANT PER (user, client, resource) is a raw-SQL partial unique
21
+ // index that exists only in the migration (listed in raw-sql-indexes.json):
22
+ // oauth_grants_active_uniq_idx ON oauth_grants (user_id, client_id, resource)
23
+ // WHERE revoked_at IS NULL
24
+ // Never "fix" it with @@unique or a findFirst pre-check.
25
+
26
+ enum OAuthClientKind {
27
+ cimd
28
+ dynamic
29
+ registered
30
+ }
31
+
32
+ enum OAuthRequestStatus {
33
+ pending
34
+ approved
35
+ denied
36
+ expired
37
+ }
38
+
39
+ enum OAuthTokenKind {
40
+ access
41
+ refresh
42
+ }
43
+
44
+ /// An OAuth client. `clientId` is the HTTPS metadata URL for a `cimd` client and
45
+ /// a generated `oc_...` id otherwise. `host` is the lower-cased host the trust
46
+ /// policy and the consent page use. `secretHash` is set for confidential clients
47
+ /// only and is never the secret.
48
+ model OAuthClient {
49
+ id String @id @default(uuid()) @db.Uuid
50
+ clientId String @unique @map("client_id")
51
+ kind OAuthClientKind
52
+ name String
53
+ clientUri String? @map("client_uri")
54
+ logoUri String? @map("logo_uri")
55
+ redirectUris Json @map("redirect_uris")
56
+ tokenEndpointAuthMethod String @map("token_endpoint_auth_method")
57
+ secretHash String? @map("secret_hash")
58
+ applicationType String? @map("application_type")
59
+ host String
60
+ metadataFetchedAt DateTime? @map("metadata_fetched_at") @db.Timestamptz
61
+ metadataExpiresAt DateTime? @map("metadata_expires_at") @db.Timestamptz
62
+ createdByUserId String? @map("created_by_user_id") @db.Uuid
63
+ disabledAt DateTime? @map("disabled_at") @db.Timestamptz
64
+ lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz
65
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
66
+
67
+ // Relations
68
+ createdBy User? @relation("OAuthClientCreatedBy", fields: [createdByUserId], references: [id], onDelete: SetNull)
69
+ authRequests OAuthAuthorizationRequest[]
70
+ grants OAuthGrant[]
71
+
72
+ @@map("oauth_clients")
73
+ }
74
+
75
+ /// An authorization request waiting for consent (short-lived, 10 minutes).
76
+ /// `userId` is set when a signed-in user first opens it; a request is bound to
77
+ /// one user. It is a plain id with no relation: the row is purged by expiry and
78
+ /// by the user-data purge, not by a cascade.
79
+ model OAuthAuthorizationRequest {
80
+ id String @id @default(uuid()) @db.Uuid
81
+ clientId String @map("client_id") @db.Uuid
82
+ redirectUri String @map("redirect_uri")
83
+ scope String
84
+ state String?
85
+ resource String
86
+ codeChallenge String @map("code_challenge")
87
+ codeChallengeMethod String @map("code_challenge_method")
88
+ userId String? @map("user_id") @db.Uuid
89
+ status OAuthRequestStatus @default(pending)
90
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
91
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
92
+
93
+ // Relations
94
+ client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
95
+
96
+ @@index([clientId])
97
+ @@index([expiresAt])
98
+ @@map("oauth_authorization_requests")
99
+ }
100
+
101
+ /// One consent: a user let a client act on a resource with these scopes.
102
+ /// `orgId` is nullable (expand step, like `PersonalAccessToken.orgId`).
103
+ model OAuthGrant {
104
+ id String @id @default(uuid()) @db.Uuid
105
+ userId String @map("user_id") @db.Uuid
106
+ orgId String? @map("org_id") @db.Uuid
107
+ clientId String @map("client_id") @db.Uuid
108
+ resource String
109
+ scopes String[]
110
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
111
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
112
+ lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz
113
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
114
+ /// user, admin, reuse_detected, client_disabled or offboarding.
115
+ revokedReason String? @map("revoked_reason")
116
+
117
+ // Relations
118
+ user User @relation("UserOAuthGrants", fields: [userId], references: [id], onDelete: Cascade)
119
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)
120
+ client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade)
121
+ codes OAuthAuthorizationCode[]
122
+ tokens OAuthToken[]
123
+
124
+ @@index([userId])
125
+ @@index([clientId])
126
+ @@index([orgId])
127
+ @@map("oauth_grants")
128
+ }
129
+
130
+ /// A single-use authorization code (60 s). Only the SHA-256 of the `oac_` code is
131
+ /// stored. A second use revokes the grant.
132
+ model OAuthAuthorizationCode {
133
+ id String @id @default(uuid()) @db.Uuid
134
+ codeHash String @unique @map("code_hash")
135
+ grantId String @map("grant_id") @db.Uuid
136
+ redirectUri String @map("redirect_uri")
137
+ codeChallenge String @map("code_challenge")
138
+ scope String
139
+ resource String
140
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
141
+ consumedAt DateTime? @map("consumed_at") @db.Timestamptz
142
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
143
+
144
+ // Relations
145
+ grant OAuthGrant @relation(fields: [grantId], references: [id], onDelete: Cascade)
146
+
147
+ @@index([grantId])
148
+ @@index([expiresAt])
149
+ @@map("oauth_authorization_codes")
150
+ }
151
+
152
+ /// An access or refresh token. Only the hash is stored; `tokenPrefix` is the
153
+ /// first 8 characters after `oat_` / `ort_`, for display and logs. A refresh
154
+ /// rotation chain is `rotatedAt` plus `replacedById`.
155
+ model OAuthToken {
156
+ id String @id @default(uuid()) @db.Uuid
157
+ kind OAuthTokenKind
158
+ tokenHash String @unique @map("token_hash")
159
+ tokenPrefix String @map("token_prefix")
160
+ grantId String @map("grant_id") @db.Uuid
161
+ scopes String[]
162
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
163
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
164
+ lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz
165
+ rotatedAt DateTime? @map("rotated_at") @db.Timestamptz
166
+ replacedById String? @map("replaced_by_id") @db.Uuid
167
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
168
+
169
+ // Relations
170
+ grant OAuthGrant @relation(fields: [grantId], references: [id], onDelete: Cascade)
171
+
172
+ @@index([grantId])
173
+ @@index([expiresAt])
174
+ @@map("oauth_tokens")
175
+ }
176
+
177
+ extend model User {
178
+ oauthClientsCreated OAuthClient[] @relation("OAuthClientCreatedBy")
179
+ oauthGrants OAuthGrant[] @relation("UserOAuthGrants")
180
+ }
181
+
182
+ extend model Organization {
183
+ oauthGrants OAuthGrant[]
184
+ }