@nathapp/nestjs-iam-prisma 1.0.0 → 1.1.0
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/README.md +25 -13
- package/dist/prisma-identity.repository.js +9 -6
- package/dist/prisma-identity.repository.js.map +1 -1
- package/package.json +10 -8
- package/AGENTS.md +0 -160
- package/CLAUDE.md +0 -158
- package/GEMINI.md +0 -158
- package/codex.md +0 -158
package/README.md
CHANGED
|
@@ -6,8 +6,8 @@ tokens to `AbstractPrismaRepository`-based implementations.
|
|
|
6
6
|
## Install
|
|
7
7
|
|
|
8
8
|
```shell
|
|
9
|
-
npm i @nathapp/nestjs-iam-prisma @prisma/client@
|
|
10
|
-
npm i -D prisma@
|
|
9
|
+
npm i @nathapp/nestjs-iam-prisma @prisma/client@7
|
|
10
|
+
npm i -D prisma@7
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
## Schema
|
|
@@ -38,7 +38,7 @@ adapters together, concatenate their five model-only fragments into one schema
|
|
|
38
38
|
with exactly one generator and datasource. The packages do not publish a schema
|
|
39
39
|
generator or provider-specific copies of these models. This Node recipe writes a
|
|
40
40
|
separate schema file so you can add your application-owned models before running
|
|
41
|
-
Prisma
|
|
41
|
+
Prisma 7:
|
|
42
42
|
|
|
43
43
|
```shell
|
|
44
44
|
mkdir -p scripts
|
|
@@ -66,13 +66,13 @@ if (provider === 'mysql') {
|
|
|
66
66
|
|
|
67
67
|
const schema = [
|
|
68
68
|
'generator client {',
|
|
69
|
-
' provider
|
|
70
|
-
' output
|
|
69
|
+
' provider = "prisma-client"',
|
|
70
|
+
' output = "./client"',
|
|
71
|
+
' moduleFormat = "cjs"',
|
|
71
72
|
'}',
|
|
72
73
|
'',
|
|
73
74
|
'datasource db {',
|
|
74
75
|
` provider = "${provider}"`,
|
|
75
|
-
' url = env("DATABASE_URL")',
|
|
76
76
|
'}',
|
|
77
77
|
'',
|
|
78
78
|
models,
|
|
@@ -84,20 +84,26 @@ NODE
|
|
|
84
84
|
|
|
85
85
|
# PostgreSQL
|
|
86
86
|
PRISMA_PROVIDER=postgresql node ./scripts/assemble-platform-schema.cjs
|
|
87
|
-
|
|
87
|
+
./node_modules/.bin/prisma validate --schema prisma/platform.schema.prisma
|
|
88
88
|
./node_modules/.bin/prisma generate --schema prisma/platform.schema.prisma
|
|
89
89
|
|
|
90
90
|
# MySQL: assemble a fresh schema before validating or generating its client
|
|
91
91
|
PRISMA_PROVIDER=mysql node ./scripts/assemble-platform-schema.cjs
|
|
92
|
-
|
|
92
|
+
./node_modules/.bin/prisma validate --schema prisma/platform.schema.prisma
|
|
93
93
|
./node_modules/.bin/prisma generate --schema prisma/platform.schema.prisma
|
|
94
94
|
```
|
|
95
95
|
|
|
96
|
+
The generated client is written to `prisma/client/` as TypeScript source; import
|
|
97
|
+
`PrismaClient` from `./prisma/client/client` (adjust the relative path), not from
|
|
98
|
+
`@prisma/client`. Migrations and `db push` read the connection URL from your
|
|
99
|
+
`prisma.config.ts` (`datasource.url`), not from the schema. See the
|
|
100
|
+
`@nathapp/nestjs-prisma` README, "Prisma 7 setup".
|
|
101
|
+
|
|
96
102
|
The commands save a testable assembly script and run it for each provider.
|
|
97
103
|
PostgreSQL keeps
|
|
98
104
|
the published `@db.Timestamptz(6)` annotations. MySQL assembly changes only that
|
|
99
105
|
native annotation to `@db.DateTime(6)`; the model bodies and their relations stay
|
|
100
|
-
the same. Validate and generate with the local Prisma
|
|
106
|
+
the same. Validate and generate with the local Prisma 7 CLI installed by your
|
|
101
107
|
application (`./node_modules/.bin/prisma`); these commands do not need an
|
|
102
108
|
`npx` download fallback.
|
|
103
109
|
|
|
@@ -162,7 +168,7 @@ writes; retire every old client before cutting over. This adapter maps one
|
|
|
162
168
|
`scopes` column and does not provide the temporary dual-write path.
|
|
163
169
|
|
|
164
170
|
MySQL consumers can assemble the same `ApiKey` JSON model or update a custom
|
|
165
|
-
model to match it, then regenerate the client. With Prisma
|
|
171
|
+
model to match it, then regenerate the client. With Prisma 7, the generated
|
|
166
172
|
MySQL table has `scopes JSON NOT NULL` but no SQL-level default; Prisma Client
|
|
167
173
|
applies the schema's `[]` default when a create call omits `scopes`. Raw SQL
|
|
168
174
|
inserts must supply the scopes value or add a consumer-owned MySQL default.
|
|
@@ -245,14 +251,19 @@ read.
|
|
|
245
251
|
|
|
246
252
|
```ts
|
|
247
253
|
import { Module } from '@nestjs/common';
|
|
248
|
-
import {
|
|
254
|
+
import { PrismaPg } from '@prisma/adapter-pg'; // MySQL: PrismaMariaDb from '@prisma/adapter-mariadb' (host/port/user/password/database, no connectionString)
|
|
255
|
+
import { PrismaClient } from './generated/prisma/client'; // your generator `output`
|
|
249
256
|
import { ClockModule } from '@nathapp/nestjs-common';
|
|
250
257
|
import { PrismaModule } from '@nathapp/nestjs-prisma';
|
|
251
258
|
import { IamPrismaModule } from '@nathapp/nestjs-iam-prisma';
|
|
252
259
|
|
|
253
260
|
@Module({
|
|
254
261
|
imports: [
|
|
255
|
-
PrismaModule.forRoot({
|
|
262
|
+
PrismaModule.forRoot({
|
|
263
|
+
client: PrismaClient,
|
|
264
|
+
clientOptions: { adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) },
|
|
265
|
+
transaction: true,
|
|
266
|
+
}),
|
|
256
267
|
ClockModule.register(), // provides CLOCK, required by PrismaSessionRepository
|
|
257
268
|
IamPrismaModule.register(),
|
|
258
269
|
],
|
|
@@ -313,7 +324,8 @@ which is exported from this package if you need to name the type.
|
|
|
313
324
|
|
|
314
325
|
## Transactions
|
|
315
326
|
|
|
316
|
-
Multi-write flows need `PrismaModule.forRoot({ client: PrismaClient, transaction: true })
|
|
327
|
+
Multi-write flows need `PrismaModule.forRoot({ client: PrismaClient, transaction: true })`
|
|
328
|
+
with `PrismaClient` imported from your generated client (Prisma 7 `prisma-client` generator).
|
|
317
329
|
Every repository resolves its client per operation from the `TRANSACTION_MANAGER`
|
|
318
330
|
token, and the two `PrismaModule` registration paths fail differently when
|
|
319
331
|
`transaction` is omitted:
|
|
@@ -17,6 +17,7 @@ const common_1 = require("@nestjs/common");
|
|
|
17
17
|
const nestjs_prisma_1 = require("@nathapp/nestjs-prisma");
|
|
18
18
|
const nestjs_data_1 = require("@nathapp/nestjs-data");
|
|
19
19
|
const nestjs_iam_1 = require("@nathapp/nestjs-iam");
|
|
20
|
+
const PRIMARY_IDENTITY_INDEX = 'user_identities_one_primary';
|
|
20
21
|
function isPrimaryIdentityUniqueConstraintViolation(error) {
|
|
21
22
|
var _a;
|
|
22
23
|
if (typeof error !== 'object' || error === null)
|
|
@@ -25,12 +26,14 @@ function isPrimaryIdentityUniqueConstraintViolation(error) {
|
|
|
25
26
|
if (prismaError.code !== 'P2002' || ((_a = prismaError.meta) === null || _a === void 0 ? void 0 : _a.modelName) !== 'UserIdentity') {
|
|
26
27
|
return false;
|
|
27
28
|
}
|
|
28
|
-
const target =
|
|
29
|
-
|
|
30
|
-
(
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
29
|
+
const target = (0, nestjs_prisma_1.getUniqueConstraintTarget)(error);
|
|
30
|
+
if (typeof target === 'string') {
|
|
31
|
+
return target === PRIMARY_IDENTITY_INDEX || target.endsWith('.' + PRIMARY_IDENTITY_INDEX);
|
|
32
|
+
}
|
|
33
|
+
return (Array.isArray(target) &&
|
|
34
|
+
target.length === 2 &&
|
|
35
|
+
target[0] === 'tenant_id' &&
|
|
36
|
+
target[1] === 'user_id');
|
|
34
37
|
}
|
|
35
38
|
let PrismaIdentityRepository = class PrismaIdentityRepository extends nestjs_prisma_1.AbstractPrismaRepository {
|
|
36
39
|
constructor(tx) { super(tx); }
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prisma-identity.repository.js","sourceRoot":"","sources":["../lib/prisma-identity.repository.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAoD;AACpD,
|
|
1
|
+
{"version":3,"file":"prisma-identity.repository.js","sourceRoot":"","sources":["../lib/prisma-identity.repository.ts"],"names":[],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nathapp/nestjs-iam-prisma",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Prisma adapter for @nathapp/nestjs-iam",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"build": "rimraf dist && tsc -p tsconfig.json",
|
|
@@ -25,23 +25,25 @@
|
|
|
25
25
|
"lib": "lib"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@nathapp/nestjs-data": "^3.3.0 || ^4.0.
|
|
28
|
+
"@nathapp/nestjs-data": "^3.3.0 || ^4.0.3",
|
|
29
29
|
"@nathapp/nestjs-iam": "1.0.0"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
32
|
"@nathapp/nestjs-oauth": "1.0.0",
|
|
33
|
-
"@nathapp/nestjs-oauth-prisma": "1.
|
|
34
|
-
"@nathapp/nestjs-prisma": "^4.0
|
|
35
|
-
"@prisma/
|
|
33
|
+
"@nathapp/nestjs-oauth-prisma": "1.1.0",
|
|
34
|
+
"@nathapp/nestjs-prisma": "^4.1.0",
|
|
35
|
+
"@prisma/adapter-mariadb": "7.10.0",
|
|
36
|
+
"@prisma/adapter-pg": "7.10.0",
|
|
37
|
+
"@prisma/client": "7.10.0",
|
|
36
38
|
"eslint": "^8.57.0",
|
|
37
|
-
"prisma": "
|
|
39
|
+
"prisma": "7.10.0",
|
|
38
40
|
"testcontainers": "12.0.3",
|
|
39
41
|
"typescript": "^5"
|
|
40
42
|
},
|
|
41
43
|
"peerDependencies": {
|
|
42
|
-
"@nathapp/nestjs-prisma": "^
|
|
44
|
+
"@nathapp/nestjs-prisma": "^4.1.0",
|
|
43
45
|
"@nestjs/common": "^11.0.0 || ^12.1.0",
|
|
44
46
|
"@nestjs/core": "^11.0.0 || ^12.1.0",
|
|
45
|
-
"@prisma/client": "^
|
|
47
|
+
"@prisma/client": "^7.0.0"
|
|
46
48
|
}
|
|
47
49
|
}
|
package/AGENTS.md
DELETED
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
# Agent Instructions
|
|
2
|
-
|
|
3
|
-
This file is auto-generated from `.nax/context.md`.
|
|
4
|
-
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
-
|
|
6
|
-
These instructions apply to all AI coding agents in this project.
|
|
7
|
-
|
|
8
|
-
---
|
|
9
|
-
|
|
10
|
-
## Project Metadata
|
|
11
|
-
|
|
12
|
-
> Auto-injected by `nax generate`
|
|
13
|
-
|
|
14
|
-
**Project:** `@nathapp/nestjs-iam-prisma`
|
|
15
|
-
|
|
16
|
-
**Language:** TypeScript
|
|
17
|
-
|
|
18
|
-
**Key dependencies:** @nathapp/nestjs-oauth-prisma, @nathapp/nestjs-prisma, @prisma/client, prisma, typescript
|
|
19
|
-
|
|
20
|
-
**Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check`
|
|
21
|
-
|
|
22
|
-
---
|
|
23
|
-
# CLAUDE.md — @nathapp/nestjs-iam-prisma
|
|
24
|
-
|
|
25
|
-
Prisma adapter for `@nathapp/nestjs-iam`. Implements all 8 repository interfaces using `AbstractPrismaRepository` from `@nathapp/nestjs-prisma`.
|
|
26
|
-
|
|
27
|
-
## Status: ✅ Complete
|
|
28
|
-
|
|
29
|
-
## Implemented Repositories
|
|
30
|
-
|
|
31
|
-
All 8 repositories extend `AbstractPrismaRepository` and resolve their Prisma client per-operation from `TRANSACTION_MANAGER`.
|
|
32
|
-
|
|
33
|
-
- `PrismaUserRepository` → `USER_REPOSITORY`
|
|
34
|
-
- `PrismaIdentityRepository` → `USER_IDENTITY_REPOSITORY`
|
|
35
|
-
- `PrismaSessionRepository` → `SESSION_REPOSITORY`
|
|
36
|
-
- `PrismaLoginHistoryRepository` → `LOGIN_HISTORY_REPOSITORY`
|
|
37
|
-
- `PrismaSsoAccountRepository` → `SSO_ACCOUNT_REPOSITORY`
|
|
38
|
-
- `PrismaSsoProviderRepository` → `SSO_PROVIDER_REPOSITORY`
|
|
39
|
-
- `PrismaMfaRepository` → `MFA_REPOSITORY`
|
|
40
|
-
- `PrismaVerificationTokenRepository` → `VERIFICATION_TOKEN_REPOSITORY`
|
|
41
|
-
|
|
42
|
-
`IamPrismaModule` registers all repositories with their DI tokens.
|
|
43
|
-
|
|
44
|
-
## Module Registration
|
|
45
|
-
|
|
46
|
-
`IamPrismaModule.register()` takes no arguments. Consumer wiring:
|
|
47
|
-
|
|
48
|
-
```ts
|
|
49
|
-
PrismaModule.forRoot({ client: PrismaClient, transaction: true, isGlobal: true })
|
|
50
|
-
IamModule.register({...})
|
|
51
|
-
IamPrismaModule.register() // no args
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
> **`transaction: true` is mandatory.** `DefaultUserService.register()` creates a User and an Identity in two separate repository calls. Both are wrapped in `txManager.run()` so they roll back together on failure — but only if `TRANSACTION_MANAGER` is backed by a real Prisma interactive transaction. Without `transaction: true`, `txManager.run()` is a passthrough and a failure between the two writes leaves an orphaned User with no Identity.
|
|
55
|
-
|
|
56
|
-
`PrismaModule.forRoot` (from `@nathapp/nestjs-prisma`) provides both the Prisma client and `TRANSACTION_MANAGER`. All repositories resolve the client from `TRANSACTION_MANAGER` at operation time, enabling automatic transaction propagation.
|
|
57
|
-
|
|
58
|
-
## Dependencies
|
|
59
|
-
|
|
60
|
-
- `@nathapp/nestjs-iam` (workspace)
|
|
61
|
-
- `@nathapp/nestjs-prisma` ^3.2.0 (peer) — provides `AbstractPrismaRepository` and `PrismaModule`
|
|
62
|
-
- `@prisma/client` ^6.0.0 (peer)
|
|
63
|
-
|
|
64
|
-
## Schema conventions
|
|
65
|
-
|
|
66
|
-
For PostgreSQL, `DateTime` fields in the consumer's IAM models (User, Identity, Session, LoginHistory, SsoAccount, Mfa, VerificationToken) MUST use `@db.Timestamptz(6)`:
|
|
67
|
-
|
|
68
|
-
```prisma
|
|
69
|
-
createdAt DateTime @db.Timestamptz(6) @default(now()) @map("created_at")
|
|
70
|
-
updatedAt DateTime @db.Timestamptz(6) @updatedAt @map("updated_at")
|
|
71
|
-
expiresAt DateTime @db.Timestamptz(6) @map("expires_at")
|
|
72
|
-
revokedAt DateTime? @db.Timestamptz(6) @map("revoked_at")
|
|
73
|
-
consumedAt DateTime? @db.Timestamptz(6) @map("consumed_at")
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
This maps to PostgreSQL `timestamptz`, which stores UTC and converts correctly regardless of DB server timezone. Bare `DateTime` (maps to `timestamp without time zone`) is not correct for these PostgreSQL fields.
|
|
77
|
-
|
|
78
|
-
### PostgreSQL and MySQL fragment assembly
|
|
79
|
-
|
|
80
|
-
- The tenant, IAM, account, notify, and OAuth Prisma files are model-only fragments. Assemble them into one schema with one generator and datasource; keep each model body and cross-package relation intact.
|
|
81
|
-
- Published fragments retain `@db.Timestamptz(6)` for PostgreSQL. For a MySQL schema, replace only that native annotation with `@db.DateTime(6)` in the assembled output. Do not edit or publish provider-specific copies of the fragments.
|
|
82
|
-
- MySQL `DateTime(6)` stores a wall-clock value without timezone metadata. Keep application values and MySQL sessions on UTC (`time_zone = '+00:00'`). Existing local wall-clock values need a consumer-specific timezone conversion during migration; do not relabel them all as UTC.
|
|
83
|
-
- The adapter README has a copyable Node / Prisma 6 recipe. Its portability test assembles and validates all five fragments with the local Prisma CLI, and confirms that unreplaced `Timestamptz(6)` is rejected for MySQL.
|
|
84
|
-
|
|
85
|
-
When migrating an existing database:
|
|
86
|
-
```sql
|
|
87
|
-
ALTER TABLE <table> ALTER COLUMN <col> TYPE TIMESTAMPTZ(6) USING <col> AT TIME ZONE 'UTC';
|
|
88
|
-
```
|
|
89
|
-
Run one statement per column. Verify `SHOW timezone;` returns `UTC` before migrating production data.
|
|
90
|
-
|
|
91
|
-
## UserSsoAccount schema contract
|
|
92
|
-
|
|
93
|
-
- `accessTokenEnc` and `refreshTokenEnc` store encrypted OAuth/OIDC token values; `PrismaSsoAccountRepository` reads and writes these fields exclusively.
|
|
94
|
-
- If an existing database still uses `access_token` or `refresh_token`, rename them before regenerating the Prisma client:
|
|
95
|
-
|
|
96
|
-
```sql
|
|
97
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "access_token" TO "access_token_enc";
|
|
98
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "refresh_token" TO "refresh_token_enc";
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
## UserSession schema contract
|
|
102
|
-
|
|
103
|
-
The consumer's `UserSession` Prisma model MUST include a nullable `previousRefreshTokenHash` column, snake-cased via `@map`. `PrismaSessionRepository.rotateRefreshToken` writes it as part of the CAS, and `PrismaSessionRepository.findByPreviousRefreshToken` reads it to detect OAuth refresh-token replay (RFC 6819 §5.2.2.3).
|
|
104
|
-
|
|
105
|
-
```prisma
|
|
106
|
-
model UserSession {
|
|
107
|
-
id String @id @default(uuid())
|
|
108
|
-
// ... other columns ...
|
|
109
|
-
refreshTokenHash String @map("refresh_token_hash")
|
|
110
|
-
previousRefreshTokenHash String? @map("previous_refresh_token_hash")
|
|
111
|
-
// ... other columns ...
|
|
112
|
-
}
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
A composite index on `(previousRefreshTokenHash)` is recommended for replay-detection lookups: replay attempts are rare but latency-sensitive.
|
|
116
|
-
|
|
117
|
-
This follows the SSO-registry-model precedent: the iam-prisma adapter ships no `.prisma` schema or migration, and the consumer's Prisma model is the schema-of-record for fields the adapter reads or writes.
|
|
118
|
-
|
|
119
|
-
## UserIdentity → User relation contract
|
|
120
|
-
|
|
121
|
-
`PrismaUserRepository.findByEmail` resolves the user by joining it from the EMAIL identity via `include: { user: true }`. The consumer's `UserIdentity` Prisma model MUST therefore declare the relation to `User`, and `User` the reverse `identities` field. The shipped `prisma/iam.prisma` fragment declares both, so consumers who assemble their schema from the fragment get a working client out of the box:
|
|
122
|
-
|
|
123
|
-
```prisma
|
|
124
|
-
model User {
|
|
125
|
-
// ...
|
|
126
|
-
identities UserIdentity[]
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
model UserIdentity {
|
|
130
|
-
userId String @map("user_id")
|
|
131
|
-
// ...
|
|
132
|
-
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
|
133
|
-
}
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
The FK column (`user_id`) already exists with valid data, so adopting the relation on an existing database is a single additive migration with no data-loss risk:
|
|
137
|
-
|
|
138
|
-
```sql
|
|
139
|
-
ALTER TABLE "user_identities"
|
|
140
|
-
ADD CONSTRAINT "user_identities_user_id_fkey"
|
|
141
|
-
FOREIGN KEY ("user_id") REFERENCES "users"("id")
|
|
142
|
-
ON DELETE CASCADE ON UPDATE CASCADE;
|
|
143
|
-
```
|
|
144
|
-
|
|
145
|
-
Without the relation, `findByEmail` throws `PrismaClientValidationError: Unknown field `user` for include statement on model `UserIdentity``. This follows the same schema-of-record precedent as the UserSession contract.
|
|
146
|
-
|
|
147
|
-
## Primary Identity Migration and Acceptance Tests
|
|
148
|
-
|
|
149
|
-
- Primary uniqueness is consumer-owned migration SQL in `prisma/sql/primary-identity.postgresql.sql` and `prisma/sql/primary-identity.mysql.sql`; these are reference statements, not migrations run by this adapter. Run the duplicate-primary preflight first and have an operator choose any cleanup. Deploy the IAM clear-before-set code before enabling the index.
|
|
150
|
-
- Atomic switches require `PrismaModule.forRoot({ transaction: true })` to provide a real interactive transaction manager. The IAM service's no-manager fallback only performs sequential writes and is not atomic. The adapter maps primary-index `P2002` conflicts from `isPrimary: true` creates and updates to IAM code 22035 / HTTP 409, while preserving unrelated duplicate-identity errors.
|
|
151
|
-
- Run real disposable PostgreSQL 16 and MySQL 8.0 acceptance tests with `npm run test:db --workspace=@nathapp/nestjs-iam-prisma`; Docker is required, and an explicitly invoked run must fail if its container runtime is unavailable.
|
|
152
|
-
|
|
153
|
-
## API-key Scope Schema and Migration
|
|
154
|
-
|
|
155
|
-
- Keep the domain contract `ApiKey.scopes: string[]`. The shipped `ApiKey` model stores scopes as `Json @default("[]")`; its database row type is `unknown` and the adapter's local strict decoder accepts only arrays containing strings. Do not parse JSON text, filter mixed arrays, or change shared `readStringArray` behavior.
|
|
156
|
-
- The PostgreSQL reference migration is `prisma/sql/api-key-scopes.postgresql.sql`. It is consumer-owned SQL, not a migration the adapter applies. It locks `api_keys`, rejects NULL arrays and NULL elements for operator repair, converts with `to_jsonb(scopes)`, sets the JSONB `[]` default, and enforces `NOT NULL` in one transaction. Conversion preserves all valid existing arrays.
|
|
157
|
-
- Coordinate the PostgreSQL conversion, Prisma client regeneration, and adapter deployment in a maintenance window because the migration takes an `ACCESS EXCLUSIVE` lock and old scalar-list and new JSON clients are not interchangeable. If zero downtime is required, consumers need their own shadow-column/dual-write expand-contract path and must retire old clients before cutover.
|
|
158
|
-
- MySQL consumers that omitted `ApiKey` or use a custom model must add/update the model to JSON and regenerate their client. With Prisma 6, generated MySQL DDL does not emit a SQL-level default for JSON; Prisma Client still applies `[]` when a create call omits scopes. Raw SQL inserts must supply scopes or use a consumer-owned database default.
|
|
159
|
-
- The DB acceptance suite assembles the published IAM fragment directly for PostgreSQL and MySQL, changing only MySQL's `@db.Timestamptz(6)` annotation to `@db.DateTime(6)`. A separate portability test validates the tenant, IAM, account, notify, and OAuth fragments together for both providers.
|
|
160
|
-
- Timezone round-trip acceptance writes and reads `2026-10-04T08:00:00.123Z` on the same interactive-transaction connection with MySQL session time zone `+00:00` and PostgreSQL session time zone `+08:00`. Restore MySQL session state after the proof; PostgreSQL uses transaction-local timezone state.
|
package/CLAUDE.md
DELETED
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
# Project Context
|
|
2
|
-
|
|
3
|
-
This file is auto-generated from `.nax/context.md`.
|
|
4
|
-
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
-
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## Project Metadata
|
|
9
|
-
|
|
10
|
-
> Auto-injected by `nax generate`
|
|
11
|
-
|
|
12
|
-
**Project:** `@nathapp/nestjs-iam-prisma`
|
|
13
|
-
|
|
14
|
-
**Language:** TypeScript
|
|
15
|
-
|
|
16
|
-
**Key dependencies:** @nathapp/nestjs-oauth-prisma, @nathapp/nestjs-prisma, @prisma/client, prisma, typescript
|
|
17
|
-
|
|
18
|
-
**Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check`
|
|
19
|
-
|
|
20
|
-
---
|
|
21
|
-
# CLAUDE.md — @nathapp/nestjs-iam-prisma
|
|
22
|
-
|
|
23
|
-
Prisma adapter for `@nathapp/nestjs-iam`. Implements all 8 repository interfaces using `AbstractPrismaRepository` from `@nathapp/nestjs-prisma`.
|
|
24
|
-
|
|
25
|
-
## Status: ✅ Complete
|
|
26
|
-
|
|
27
|
-
## Implemented Repositories
|
|
28
|
-
|
|
29
|
-
All 8 repositories extend `AbstractPrismaRepository` and resolve their Prisma client per-operation from `TRANSACTION_MANAGER`.
|
|
30
|
-
|
|
31
|
-
- `PrismaUserRepository` → `USER_REPOSITORY`
|
|
32
|
-
- `PrismaIdentityRepository` → `USER_IDENTITY_REPOSITORY`
|
|
33
|
-
- `PrismaSessionRepository` → `SESSION_REPOSITORY`
|
|
34
|
-
- `PrismaLoginHistoryRepository` → `LOGIN_HISTORY_REPOSITORY`
|
|
35
|
-
- `PrismaSsoAccountRepository` → `SSO_ACCOUNT_REPOSITORY`
|
|
36
|
-
- `PrismaSsoProviderRepository` → `SSO_PROVIDER_REPOSITORY`
|
|
37
|
-
- `PrismaMfaRepository` → `MFA_REPOSITORY`
|
|
38
|
-
- `PrismaVerificationTokenRepository` → `VERIFICATION_TOKEN_REPOSITORY`
|
|
39
|
-
|
|
40
|
-
`IamPrismaModule` registers all repositories with their DI tokens.
|
|
41
|
-
|
|
42
|
-
## Module Registration
|
|
43
|
-
|
|
44
|
-
`IamPrismaModule.register()` takes no arguments. Consumer wiring:
|
|
45
|
-
|
|
46
|
-
```ts
|
|
47
|
-
PrismaModule.forRoot({ client: PrismaClient, transaction: true, isGlobal: true })
|
|
48
|
-
IamModule.register({...})
|
|
49
|
-
IamPrismaModule.register() // no args
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
> **`transaction: true` is mandatory.** `DefaultUserService.register()` creates a User and an Identity in two separate repository calls. Both are wrapped in `txManager.run()` so they roll back together on failure — but only if `TRANSACTION_MANAGER` is backed by a real Prisma interactive transaction. Without `transaction: true`, `txManager.run()` is a passthrough and a failure between the two writes leaves an orphaned User with no Identity.
|
|
53
|
-
|
|
54
|
-
`PrismaModule.forRoot` (from `@nathapp/nestjs-prisma`) provides both the Prisma client and `TRANSACTION_MANAGER`. All repositories resolve the client from `TRANSACTION_MANAGER` at operation time, enabling automatic transaction propagation.
|
|
55
|
-
|
|
56
|
-
## Dependencies
|
|
57
|
-
|
|
58
|
-
- `@nathapp/nestjs-iam` (workspace)
|
|
59
|
-
- `@nathapp/nestjs-prisma` ^3.2.0 (peer) — provides `AbstractPrismaRepository` and `PrismaModule`
|
|
60
|
-
- `@prisma/client` ^6.0.0 (peer)
|
|
61
|
-
|
|
62
|
-
## Schema conventions
|
|
63
|
-
|
|
64
|
-
For PostgreSQL, `DateTime` fields in the consumer's IAM models (User, Identity, Session, LoginHistory, SsoAccount, Mfa, VerificationToken) MUST use `@db.Timestamptz(6)`:
|
|
65
|
-
|
|
66
|
-
```prisma
|
|
67
|
-
createdAt DateTime @db.Timestamptz(6) @default(now()) @map("created_at")
|
|
68
|
-
updatedAt DateTime @db.Timestamptz(6) @updatedAt @map("updated_at")
|
|
69
|
-
expiresAt DateTime @db.Timestamptz(6) @map("expires_at")
|
|
70
|
-
revokedAt DateTime? @db.Timestamptz(6) @map("revoked_at")
|
|
71
|
-
consumedAt DateTime? @db.Timestamptz(6) @map("consumed_at")
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
This maps to PostgreSQL `timestamptz`, which stores UTC and converts correctly regardless of DB server timezone. Bare `DateTime` (maps to `timestamp without time zone`) is not correct for these PostgreSQL fields.
|
|
75
|
-
|
|
76
|
-
### PostgreSQL and MySQL fragment assembly
|
|
77
|
-
|
|
78
|
-
- The tenant, IAM, account, notify, and OAuth Prisma files are model-only fragments. Assemble them into one schema with one generator and datasource; keep each model body and cross-package relation intact.
|
|
79
|
-
- Published fragments retain `@db.Timestamptz(6)` for PostgreSQL. For a MySQL schema, replace only that native annotation with `@db.DateTime(6)` in the assembled output. Do not edit or publish provider-specific copies of the fragments.
|
|
80
|
-
- MySQL `DateTime(6)` stores a wall-clock value without timezone metadata. Keep application values and MySQL sessions on UTC (`time_zone = '+00:00'`). Existing local wall-clock values need a consumer-specific timezone conversion during migration; do not relabel them all as UTC.
|
|
81
|
-
- The adapter README has a copyable Node / Prisma 6 recipe. Its portability test assembles and validates all five fragments with the local Prisma CLI, and confirms that unreplaced `Timestamptz(6)` is rejected for MySQL.
|
|
82
|
-
|
|
83
|
-
When migrating an existing database:
|
|
84
|
-
```sql
|
|
85
|
-
ALTER TABLE <table> ALTER COLUMN <col> TYPE TIMESTAMPTZ(6) USING <col> AT TIME ZONE 'UTC';
|
|
86
|
-
```
|
|
87
|
-
Run one statement per column. Verify `SHOW timezone;` returns `UTC` before migrating production data.
|
|
88
|
-
|
|
89
|
-
## UserSsoAccount schema contract
|
|
90
|
-
|
|
91
|
-
- `accessTokenEnc` and `refreshTokenEnc` store encrypted OAuth/OIDC token values; `PrismaSsoAccountRepository` reads and writes these fields exclusively.
|
|
92
|
-
- If an existing database still uses `access_token` or `refresh_token`, rename them before regenerating the Prisma client:
|
|
93
|
-
|
|
94
|
-
```sql
|
|
95
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "access_token" TO "access_token_enc";
|
|
96
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "refresh_token" TO "refresh_token_enc";
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
## UserSession schema contract
|
|
100
|
-
|
|
101
|
-
The consumer's `UserSession` Prisma model MUST include a nullable `previousRefreshTokenHash` column, snake-cased via `@map`. `PrismaSessionRepository.rotateRefreshToken` writes it as part of the CAS, and `PrismaSessionRepository.findByPreviousRefreshToken` reads it to detect OAuth refresh-token replay (RFC 6819 §5.2.2.3).
|
|
102
|
-
|
|
103
|
-
```prisma
|
|
104
|
-
model UserSession {
|
|
105
|
-
id String @id @default(uuid())
|
|
106
|
-
// ... other columns ...
|
|
107
|
-
refreshTokenHash String @map("refresh_token_hash")
|
|
108
|
-
previousRefreshTokenHash String? @map("previous_refresh_token_hash")
|
|
109
|
-
// ... other columns ...
|
|
110
|
-
}
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
A composite index on `(previousRefreshTokenHash)` is recommended for replay-detection lookups: replay attempts are rare but latency-sensitive.
|
|
114
|
-
|
|
115
|
-
This follows the SSO-registry-model precedent: the iam-prisma adapter ships no `.prisma` schema or migration, and the consumer's Prisma model is the schema-of-record for fields the adapter reads or writes.
|
|
116
|
-
|
|
117
|
-
## UserIdentity → User relation contract
|
|
118
|
-
|
|
119
|
-
`PrismaUserRepository.findByEmail` resolves the user by joining it from the EMAIL identity via `include: { user: true }`. The consumer's `UserIdentity` Prisma model MUST therefore declare the relation to `User`, and `User` the reverse `identities` field. The shipped `prisma/iam.prisma` fragment declares both, so consumers who assemble their schema from the fragment get a working client out of the box:
|
|
120
|
-
|
|
121
|
-
```prisma
|
|
122
|
-
model User {
|
|
123
|
-
// ...
|
|
124
|
-
identities UserIdentity[]
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
model UserIdentity {
|
|
128
|
-
userId String @map("user_id")
|
|
129
|
-
// ...
|
|
130
|
-
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
|
131
|
-
}
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
The FK column (`user_id`) already exists with valid data, so adopting the relation on an existing database is a single additive migration with no data-loss risk:
|
|
135
|
-
|
|
136
|
-
```sql
|
|
137
|
-
ALTER TABLE "user_identities"
|
|
138
|
-
ADD CONSTRAINT "user_identities_user_id_fkey"
|
|
139
|
-
FOREIGN KEY ("user_id") REFERENCES "users"("id")
|
|
140
|
-
ON DELETE CASCADE ON UPDATE CASCADE;
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
Without the relation, `findByEmail` throws `PrismaClientValidationError: Unknown field `user` for include statement on model `UserIdentity``. This follows the same schema-of-record precedent as the UserSession contract.
|
|
144
|
-
|
|
145
|
-
## Primary Identity Migration and Acceptance Tests
|
|
146
|
-
|
|
147
|
-
- Primary uniqueness is consumer-owned migration SQL in `prisma/sql/primary-identity.postgresql.sql` and `prisma/sql/primary-identity.mysql.sql`; these are reference statements, not migrations run by this adapter. Run the duplicate-primary preflight first and have an operator choose any cleanup. Deploy the IAM clear-before-set code before enabling the index.
|
|
148
|
-
- Atomic switches require `PrismaModule.forRoot({ transaction: true })` to provide a real interactive transaction manager. The IAM service's no-manager fallback only performs sequential writes and is not atomic. The adapter maps primary-index `P2002` conflicts from `isPrimary: true` creates and updates to IAM code 22035 / HTTP 409, while preserving unrelated duplicate-identity errors.
|
|
149
|
-
- Run real disposable PostgreSQL 16 and MySQL 8.0 acceptance tests with `npm run test:db --workspace=@nathapp/nestjs-iam-prisma`; Docker is required, and an explicitly invoked run must fail if its container runtime is unavailable.
|
|
150
|
-
|
|
151
|
-
## API-key Scope Schema and Migration
|
|
152
|
-
|
|
153
|
-
- Keep the domain contract `ApiKey.scopes: string[]`. The shipped `ApiKey` model stores scopes as `Json @default("[]")`; its database row type is `unknown` and the adapter's local strict decoder accepts only arrays containing strings. Do not parse JSON text, filter mixed arrays, or change shared `readStringArray` behavior.
|
|
154
|
-
- The PostgreSQL reference migration is `prisma/sql/api-key-scopes.postgresql.sql`. It is consumer-owned SQL, not a migration the adapter applies. It locks `api_keys`, rejects NULL arrays and NULL elements for operator repair, converts with `to_jsonb(scopes)`, sets the JSONB `[]` default, and enforces `NOT NULL` in one transaction. Conversion preserves all valid existing arrays.
|
|
155
|
-
- Coordinate the PostgreSQL conversion, Prisma client regeneration, and adapter deployment in a maintenance window because the migration takes an `ACCESS EXCLUSIVE` lock and old scalar-list and new JSON clients are not interchangeable. If zero downtime is required, consumers need their own shadow-column/dual-write expand-contract path and must retire old clients before cutover.
|
|
156
|
-
- MySQL consumers that omitted `ApiKey` or use a custom model must add/update the model to JSON and regenerate their client. With Prisma 6, generated MySQL DDL does not emit a SQL-level default for JSON; Prisma Client still applies `[]` when a create call omits scopes. Raw SQL inserts must supply scopes or use a consumer-owned database default.
|
|
157
|
-
- The DB acceptance suite assembles the published IAM fragment directly for PostgreSQL and MySQL, changing only MySQL's `@db.Timestamptz(6)` annotation to `@db.DateTime(6)`. A separate portability test validates the tenant, IAM, account, notify, and OAuth fragments together for both providers.
|
|
158
|
-
- Timezone round-trip acceptance writes and reads `2026-10-04T08:00:00.123Z` on the same interactive-transaction connection with MySQL session time zone `+00:00` and PostgreSQL session time zone `+08:00`. Restore MySQL session state after the proof; PostgreSQL uses transaction-local timezone state.
|
package/GEMINI.md
DELETED
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
# Gemini CLI Context
|
|
2
|
-
|
|
3
|
-
This file is auto-generated from `.nax/context.md`.
|
|
4
|
-
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
-
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## Project Metadata
|
|
9
|
-
|
|
10
|
-
> Auto-injected by `nax generate`
|
|
11
|
-
|
|
12
|
-
**Project:** `@nathapp/nestjs-iam-prisma`
|
|
13
|
-
|
|
14
|
-
**Language:** TypeScript
|
|
15
|
-
|
|
16
|
-
**Key dependencies:** @nathapp/nestjs-oauth-prisma, @nathapp/nestjs-prisma, @prisma/client, prisma, typescript
|
|
17
|
-
|
|
18
|
-
**Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check`
|
|
19
|
-
|
|
20
|
-
---
|
|
21
|
-
# CLAUDE.md — @nathapp/nestjs-iam-prisma
|
|
22
|
-
|
|
23
|
-
Prisma adapter for `@nathapp/nestjs-iam`. Implements all 8 repository interfaces using `AbstractPrismaRepository` from `@nathapp/nestjs-prisma`.
|
|
24
|
-
|
|
25
|
-
## Status: ✅ Complete
|
|
26
|
-
|
|
27
|
-
## Implemented Repositories
|
|
28
|
-
|
|
29
|
-
All 8 repositories extend `AbstractPrismaRepository` and resolve their Prisma client per-operation from `TRANSACTION_MANAGER`.
|
|
30
|
-
|
|
31
|
-
- `PrismaUserRepository` → `USER_REPOSITORY`
|
|
32
|
-
- `PrismaIdentityRepository` → `USER_IDENTITY_REPOSITORY`
|
|
33
|
-
- `PrismaSessionRepository` → `SESSION_REPOSITORY`
|
|
34
|
-
- `PrismaLoginHistoryRepository` → `LOGIN_HISTORY_REPOSITORY`
|
|
35
|
-
- `PrismaSsoAccountRepository` → `SSO_ACCOUNT_REPOSITORY`
|
|
36
|
-
- `PrismaSsoProviderRepository` → `SSO_PROVIDER_REPOSITORY`
|
|
37
|
-
- `PrismaMfaRepository` → `MFA_REPOSITORY`
|
|
38
|
-
- `PrismaVerificationTokenRepository` → `VERIFICATION_TOKEN_REPOSITORY`
|
|
39
|
-
|
|
40
|
-
`IamPrismaModule` registers all repositories with their DI tokens.
|
|
41
|
-
|
|
42
|
-
## Module Registration
|
|
43
|
-
|
|
44
|
-
`IamPrismaModule.register()` takes no arguments. Consumer wiring:
|
|
45
|
-
|
|
46
|
-
```ts
|
|
47
|
-
PrismaModule.forRoot({ client: PrismaClient, transaction: true, isGlobal: true })
|
|
48
|
-
IamModule.register({...})
|
|
49
|
-
IamPrismaModule.register() // no args
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
> **`transaction: true` is mandatory.** `DefaultUserService.register()` creates a User and an Identity in two separate repository calls. Both are wrapped in `txManager.run()` so they roll back together on failure — but only if `TRANSACTION_MANAGER` is backed by a real Prisma interactive transaction. Without `transaction: true`, `txManager.run()` is a passthrough and a failure between the two writes leaves an orphaned User with no Identity.
|
|
53
|
-
|
|
54
|
-
`PrismaModule.forRoot` (from `@nathapp/nestjs-prisma`) provides both the Prisma client and `TRANSACTION_MANAGER`. All repositories resolve the client from `TRANSACTION_MANAGER` at operation time, enabling automatic transaction propagation.
|
|
55
|
-
|
|
56
|
-
## Dependencies
|
|
57
|
-
|
|
58
|
-
- `@nathapp/nestjs-iam` (workspace)
|
|
59
|
-
- `@nathapp/nestjs-prisma` ^3.2.0 (peer) — provides `AbstractPrismaRepository` and `PrismaModule`
|
|
60
|
-
- `@prisma/client` ^6.0.0 (peer)
|
|
61
|
-
|
|
62
|
-
## Schema conventions
|
|
63
|
-
|
|
64
|
-
For PostgreSQL, `DateTime` fields in the consumer's IAM models (User, Identity, Session, LoginHistory, SsoAccount, Mfa, VerificationToken) MUST use `@db.Timestamptz(6)`:
|
|
65
|
-
|
|
66
|
-
```prisma
|
|
67
|
-
createdAt DateTime @db.Timestamptz(6) @default(now()) @map("created_at")
|
|
68
|
-
updatedAt DateTime @db.Timestamptz(6) @updatedAt @map("updated_at")
|
|
69
|
-
expiresAt DateTime @db.Timestamptz(6) @map("expires_at")
|
|
70
|
-
revokedAt DateTime? @db.Timestamptz(6) @map("revoked_at")
|
|
71
|
-
consumedAt DateTime? @db.Timestamptz(6) @map("consumed_at")
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
This maps to PostgreSQL `timestamptz`, which stores UTC and converts correctly regardless of DB server timezone. Bare `DateTime` (maps to `timestamp without time zone`) is not correct for these PostgreSQL fields.
|
|
75
|
-
|
|
76
|
-
### PostgreSQL and MySQL fragment assembly
|
|
77
|
-
|
|
78
|
-
- The tenant, IAM, account, notify, and OAuth Prisma files are model-only fragments. Assemble them into one schema with one generator and datasource; keep each model body and cross-package relation intact.
|
|
79
|
-
- Published fragments retain `@db.Timestamptz(6)` for PostgreSQL. For a MySQL schema, replace only that native annotation with `@db.DateTime(6)` in the assembled output. Do not edit or publish provider-specific copies of the fragments.
|
|
80
|
-
- MySQL `DateTime(6)` stores a wall-clock value without timezone metadata. Keep application values and MySQL sessions on UTC (`time_zone = '+00:00'`). Existing local wall-clock values need a consumer-specific timezone conversion during migration; do not relabel them all as UTC.
|
|
81
|
-
- The adapter README has a copyable Node / Prisma 6 recipe. Its portability test assembles and validates all five fragments with the local Prisma CLI, and confirms that unreplaced `Timestamptz(6)` is rejected for MySQL.
|
|
82
|
-
|
|
83
|
-
When migrating an existing database:
|
|
84
|
-
```sql
|
|
85
|
-
ALTER TABLE <table> ALTER COLUMN <col> TYPE TIMESTAMPTZ(6) USING <col> AT TIME ZONE 'UTC';
|
|
86
|
-
```
|
|
87
|
-
Run one statement per column. Verify `SHOW timezone;` returns `UTC` before migrating production data.
|
|
88
|
-
|
|
89
|
-
## UserSsoAccount schema contract
|
|
90
|
-
|
|
91
|
-
- `accessTokenEnc` and `refreshTokenEnc` store encrypted OAuth/OIDC token values; `PrismaSsoAccountRepository` reads and writes these fields exclusively.
|
|
92
|
-
- If an existing database still uses `access_token` or `refresh_token`, rename them before regenerating the Prisma client:
|
|
93
|
-
|
|
94
|
-
```sql
|
|
95
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "access_token" TO "access_token_enc";
|
|
96
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "refresh_token" TO "refresh_token_enc";
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
## UserSession schema contract
|
|
100
|
-
|
|
101
|
-
The consumer's `UserSession` Prisma model MUST include a nullable `previousRefreshTokenHash` column, snake-cased via `@map`. `PrismaSessionRepository.rotateRefreshToken` writes it as part of the CAS, and `PrismaSessionRepository.findByPreviousRefreshToken` reads it to detect OAuth refresh-token replay (RFC 6819 §5.2.2.3).
|
|
102
|
-
|
|
103
|
-
```prisma
|
|
104
|
-
model UserSession {
|
|
105
|
-
id String @id @default(uuid())
|
|
106
|
-
// ... other columns ...
|
|
107
|
-
refreshTokenHash String @map("refresh_token_hash")
|
|
108
|
-
previousRefreshTokenHash String? @map("previous_refresh_token_hash")
|
|
109
|
-
// ... other columns ...
|
|
110
|
-
}
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
A composite index on `(previousRefreshTokenHash)` is recommended for replay-detection lookups: replay attempts are rare but latency-sensitive.
|
|
114
|
-
|
|
115
|
-
This follows the SSO-registry-model precedent: the iam-prisma adapter ships no `.prisma` schema or migration, and the consumer's Prisma model is the schema-of-record for fields the adapter reads or writes.
|
|
116
|
-
|
|
117
|
-
## UserIdentity → User relation contract
|
|
118
|
-
|
|
119
|
-
`PrismaUserRepository.findByEmail` resolves the user by joining it from the EMAIL identity via `include: { user: true }`. The consumer's `UserIdentity` Prisma model MUST therefore declare the relation to `User`, and `User` the reverse `identities` field. The shipped `prisma/iam.prisma` fragment declares both, so consumers who assemble their schema from the fragment get a working client out of the box:
|
|
120
|
-
|
|
121
|
-
```prisma
|
|
122
|
-
model User {
|
|
123
|
-
// ...
|
|
124
|
-
identities UserIdentity[]
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
model UserIdentity {
|
|
128
|
-
userId String @map("user_id")
|
|
129
|
-
// ...
|
|
130
|
-
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
|
131
|
-
}
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
The FK column (`user_id`) already exists with valid data, so adopting the relation on an existing database is a single additive migration with no data-loss risk:
|
|
135
|
-
|
|
136
|
-
```sql
|
|
137
|
-
ALTER TABLE "user_identities"
|
|
138
|
-
ADD CONSTRAINT "user_identities_user_id_fkey"
|
|
139
|
-
FOREIGN KEY ("user_id") REFERENCES "users"("id")
|
|
140
|
-
ON DELETE CASCADE ON UPDATE CASCADE;
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
Without the relation, `findByEmail` throws `PrismaClientValidationError: Unknown field `user` for include statement on model `UserIdentity``. This follows the same schema-of-record precedent as the UserSession contract.
|
|
144
|
-
|
|
145
|
-
## Primary Identity Migration and Acceptance Tests
|
|
146
|
-
|
|
147
|
-
- Primary uniqueness is consumer-owned migration SQL in `prisma/sql/primary-identity.postgresql.sql` and `prisma/sql/primary-identity.mysql.sql`; these are reference statements, not migrations run by this adapter. Run the duplicate-primary preflight first and have an operator choose any cleanup. Deploy the IAM clear-before-set code before enabling the index.
|
|
148
|
-
- Atomic switches require `PrismaModule.forRoot({ transaction: true })` to provide a real interactive transaction manager. The IAM service's no-manager fallback only performs sequential writes and is not atomic. The adapter maps primary-index `P2002` conflicts from `isPrimary: true` creates and updates to IAM code 22035 / HTTP 409, while preserving unrelated duplicate-identity errors.
|
|
149
|
-
- Run real disposable PostgreSQL 16 and MySQL 8.0 acceptance tests with `npm run test:db --workspace=@nathapp/nestjs-iam-prisma`; Docker is required, and an explicitly invoked run must fail if its container runtime is unavailable.
|
|
150
|
-
|
|
151
|
-
## API-key Scope Schema and Migration
|
|
152
|
-
|
|
153
|
-
- Keep the domain contract `ApiKey.scopes: string[]`. The shipped `ApiKey` model stores scopes as `Json @default("[]")`; its database row type is `unknown` and the adapter's local strict decoder accepts only arrays containing strings. Do not parse JSON text, filter mixed arrays, or change shared `readStringArray` behavior.
|
|
154
|
-
- The PostgreSQL reference migration is `prisma/sql/api-key-scopes.postgresql.sql`. It is consumer-owned SQL, not a migration the adapter applies. It locks `api_keys`, rejects NULL arrays and NULL elements for operator repair, converts with `to_jsonb(scopes)`, sets the JSONB `[]` default, and enforces `NOT NULL` in one transaction. Conversion preserves all valid existing arrays.
|
|
155
|
-
- Coordinate the PostgreSQL conversion, Prisma client regeneration, and adapter deployment in a maintenance window because the migration takes an `ACCESS EXCLUSIVE` lock and old scalar-list and new JSON clients are not interchangeable. If zero downtime is required, consumers need their own shadow-column/dual-write expand-contract path and must retire old clients before cutover.
|
|
156
|
-
- MySQL consumers that omitted `ApiKey` or use a custom model must add/update the model to JSON and regenerate their client. With Prisma 6, generated MySQL DDL does not emit a SQL-level default for JSON; Prisma Client still applies `[]` when a create call omits scopes. Raw SQL inserts must supply scopes or use a consumer-owned database default.
|
|
157
|
-
- The DB acceptance suite assembles the published IAM fragment directly for PostgreSQL and MySQL, changing only MySQL's `@db.Timestamptz(6)` annotation to `@db.DateTime(6)`. A separate portability test validates the tenant, IAM, account, notify, and OAuth fragments together for both providers.
|
|
158
|
-
- Timezone round-trip acceptance writes and reads `2026-10-04T08:00:00.123Z` on the same interactive-transaction connection with MySQL session time zone `+00:00` and PostgreSQL session time zone `+08:00`. Restore MySQL session state after the proof; PostgreSQL uses transaction-local timezone state.
|
package/codex.md
DELETED
|
@@ -1,158 +0,0 @@
|
|
|
1
|
-
# Codex Instructions
|
|
2
|
-
|
|
3
|
-
This file is auto-generated from `.nax/context.md`.
|
|
4
|
-
DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
|
|
5
|
-
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## Project Metadata
|
|
9
|
-
|
|
10
|
-
> Auto-injected by `nax generate`
|
|
11
|
-
|
|
12
|
-
**Project:** `@nathapp/nestjs-iam-prisma`
|
|
13
|
-
|
|
14
|
-
**Language:** TypeScript
|
|
15
|
-
|
|
16
|
-
**Key dependencies:** @nathapp/nestjs-oauth-prisma, @nathapp/nestjs-prisma, @prisma/client, prisma, typescript
|
|
17
|
-
|
|
18
|
-
**Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check`
|
|
19
|
-
|
|
20
|
-
---
|
|
21
|
-
# CLAUDE.md — @nathapp/nestjs-iam-prisma
|
|
22
|
-
|
|
23
|
-
Prisma adapter for `@nathapp/nestjs-iam`. Implements all 8 repository interfaces using `AbstractPrismaRepository` from `@nathapp/nestjs-prisma`.
|
|
24
|
-
|
|
25
|
-
## Status: ✅ Complete
|
|
26
|
-
|
|
27
|
-
## Implemented Repositories
|
|
28
|
-
|
|
29
|
-
All 8 repositories extend `AbstractPrismaRepository` and resolve their Prisma client per-operation from `TRANSACTION_MANAGER`.
|
|
30
|
-
|
|
31
|
-
- `PrismaUserRepository` → `USER_REPOSITORY`
|
|
32
|
-
- `PrismaIdentityRepository` → `USER_IDENTITY_REPOSITORY`
|
|
33
|
-
- `PrismaSessionRepository` → `SESSION_REPOSITORY`
|
|
34
|
-
- `PrismaLoginHistoryRepository` → `LOGIN_HISTORY_REPOSITORY`
|
|
35
|
-
- `PrismaSsoAccountRepository` → `SSO_ACCOUNT_REPOSITORY`
|
|
36
|
-
- `PrismaSsoProviderRepository` → `SSO_PROVIDER_REPOSITORY`
|
|
37
|
-
- `PrismaMfaRepository` → `MFA_REPOSITORY`
|
|
38
|
-
- `PrismaVerificationTokenRepository` → `VERIFICATION_TOKEN_REPOSITORY`
|
|
39
|
-
|
|
40
|
-
`IamPrismaModule` registers all repositories with their DI tokens.
|
|
41
|
-
|
|
42
|
-
## Module Registration
|
|
43
|
-
|
|
44
|
-
`IamPrismaModule.register()` takes no arguments. Consumer wiring:
|
|
45
|
-
|
|
46
|
-
```ts
|
|
47
|
-
PrismaModule.forRoot({ client: PrismaClient, transaction: true, isGlobal: true })
|
|
48
|
-
IamModule.register({...})
|
|
49
|
-
IamPrismaModule.register() // no args
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
> **`transaction: true` is mandatory.** `DefaultUserService.register()` creates a User and an Identity in two separate repository calls. Both are wrapped in `txManager.run()` so they roll back together on failure — but only if `TRANSACTION_MANAGER` is backed by a real Prisma interactive transaction. Without `transaction: true`, `txManager.run()` is a passthrough and a failure between the two writes leaves an orphaned User with no Identity.
|
|
53
|
-
|
|
54
|
-
`PrismaModule.forRoot` (from `@nathapp/nestjs-prisma`) provides both the Prisma client and `TRANSACTION_MANAGER`. All repositories resolve the client from `TRANSACTION_MANAGER` at operation time, enabling automatic transaction propagation.
|
|
55
|
-
|
|
56
|
-
## Dependencies
|
|
57
|
-
|
|
58
|
-
- `@nathapp/nestjs-iam` (workspace)
|
|
59
|
-
- `@nathapp/nestjs-prisma` ^3.2.0 (peer) — provides `AbstractPrismaRepository` and `PrismaModule`
|
|
60
|
-
- `@prisma/client` ^6.0.0 (peer)
|
|
61
|
-
|
|
62
|
-
## Schema conventions
|
|
63
|
-
|
|
64
|
-
For PostgreSQL, `DateTime` fields in the consumer's IAM models (User, Identity, Session, LoginHistory, SsoAccount, Mfa, VerificationToken) MUST use `@db.Timestamptz(6)`:
|
|
65
|
-
|
|
66
|
-
```prisma
|
|
67
|
-
createdAt DateTime @db.Timestamptz(6) @default(now()) @map("created_at")
|
|
68
|
-
updatedAt DateTime @db.Timestamptz(6) @updatedAt @map("updated_at")
|
|
69
|
-
expiresAt DateTime @db.Timestamptz(6) @map("expires_at")
|
|
70
|
-
revokedAt DateTime? @db.Timestamptz(6) @map("revoked_at")
|
|
71
|
-
consumedAt DateTime? @db.Timestamptz(6) @map("consumed_at")
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
This maps to PostgreSQL `timestamptz`, which stores UTC and converts correctly regardless of DB server timezone. Bare `DateTime` (maps to `timestamp without time zone`) is not correct for these PostgreSQL fields.
|
|
75
|
-
|
|
76
|
-
### PostgreSQL and MySQL fragment assembly
|
|
77
|
-
|
|
78
|
-
- The tenant, IAM, account, notify, and OAuth Prisma files are model-only fragments. Assemble them into one schema with one generator and datasource; keep each model body and cross-package relation intact.
|
|
79
|
-
- Published fragments retain `@db.Timestamptz(6)` for PostgreSQL. For a MySQL schema, replace only that native annotation with `@db.DateTime(6)` in the assembled output. Do not edit or publish provider-specific copies of the fragments.
|
|
80
|
-
- MySQL `DateTime(6)` stores a wall-clock value without timezone metadata. Keep application values and MySQL sessions on UTC (`time_zone = '+00:00'`). Existing local wall-clock values need a consumer-specific timezone conversion during migration; do not relabel them all as UTC.
|
|
81
|
-
- The adapter README has a copyable Node / Prisma 6 recipe. Its portability test assembles and validates all five fragments with the local Prisma CLI, and confirms that unreplaced `Timestamptz(6)` is rejected for MySQL.
|
|
82
|
-
|
|
83
|
-
When migrating an existing database:
|
|
84
|
-
```sql
|
|
85
|
-
ALTER TABLE <table> ALTER COLUMN <col> TYPE TIMESTAMPTZ(6) USING <col> AT TIME ZONE 'UTC';
|
|
86
|
-
```
|
|
87
|
-
Run one statement per column. Verify `SHOW timezone;` returns `UTC` before migrating production data.
|
|
88
|
-
|
|
89
|
-
## UserSsoAccount schema contract
|
|
90
|
-
|
|
91
|
-
- `accessTokenEnc` and `refreshTokenEnc` store encrypted OAuth/OIDC token values; `PrismaSsoAccountRepository` reads and writes these fields exclusively.
|
|
92
|
-
- If an existing database still uses `access_token` or `refresh_token`, rename them before regenerating the Prisma client:
|
|
93
|
-
|
|
94
|
-
```sql
|
|
95
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "access_token" TO "access_token_enc";
|
|
96
|
-
ALTER TABLE "user_sso_accounts" RENAME COLUMN "refresh_token" TO "refresh_token_enc";
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
## UserSession schema contract
|
|
100
|
-
|
|
101
|
-
The consumer's `UserSession` Prisma model MUST include a nullable `previousRefreshTokenHash` column, snake-cased via `@map`. `PrismaSessionRepository.rotateRefreshToken` writes it as part of the CAS, and `PrismaSessionRepository.findByPreviousRefreshToken` reads it to detect OAuth refresh-token replay (RFC 6819 §5.2.2.3).
|
|
102
|
-
|
|
103
|
-
```prisma
|
|
104
|
-
model UserSession {
|
|
105
|
-
id String @id @default(uuid())
|
|
106
|
-
// ... other columns ...
|
|
107
|
-
refreshTokenHash String @map("refresh_token_hash")
|
|
108
|
-
previousRefreshTokenHash String? @map("previous_refresh_token_hash")
|
|
109
|
-
// ... other columns ...
|
|
110
|
-
}
|
|
111
|
-
```
|
|
112
|
-
|
|
113
|
-
A composite index on `(previousRefreshTokenHash)` is recommended for replay-detection lookups: replay attempts are rare but latency-sensitive.
|
|
114
|
-
|
|
115
|
-
This follows the SSO-registry-model precedent: the iam-prisma adapter ships no `.prisma` schema or migration, and the consumer's Prisma model is the schema-of-record for fields the adapter reads or writes.
|
|
116
|
-
|
|
117
|
-
## UserIdentity → User relation contract
|
|
118
|
-
|
|
119
|
-
`PrismaUserRepository.findByEmail` resolves the user by joining it from the EMAIL identity via `include: { user: true }`. The consumer's `UserIdentity` Prisma model MUST therefore declare the relation to `User`, and `User` the reverse `identities` field. The shipped `prisma/iam.prisma` fragment declares both, so consumers who assemble their schema from the fragment get a working client out of the box:
|
|
120
|
-
|
|
121
|
-
```prisma
|
|
122
|
-
model User {
|
|
123
|
-
// ...
|
|
124
|
-
identities UserIdentity[]
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
model UserIdentity {
|
|
128
|
-
userId String @map("user_id")
|
|
129
|
-
// ...
|
|
130
|
-
user User @relation(fields: [userId], references: [id], onDelete: Cascade, onUpdate: Cascade)
|
|
131
|
-
}
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
The FK column (`user_id`) already exists with valid data, so adopting the relation on an existing database is a single additive migration with no data-loss risk:
|
|
135
|
-
|
|
136
|
-
```sql
|
|
137
|
-
ALTER TABLE "user_identities"
|
|
138
|
-
ADD CONSTRAINT "user_identities_user_id_fkey"
|
|
139
|
-
FOREIGN KEY ("user_id") REFERENCES "users"("id")
|
|
140
|
-
ON DELETE CASCADE ON UPDATE CASCADE;
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
Without the relation, `findByEmail` throws `PrismaClientValidationError: Unknown field `user` for include statement on model `UserIdentity``. This follows the same schema-of-record precedent as the UserSession contract.
|
|
144
|
-
|
|
145
|
-
## Primary Identity Migration and Acceptance Tests
|
|
146
|
-
|
|
147
|
-
- Primary uniqueness is consumer-owned migration SQL in `prisma/sql/primary-identity.postgresql.sql` and `prisma/sql/primary-identity.mysql.sql`; these are reference statements, not migrations run by this adapter. Run the duplicate-primary preflight first and have an operator choose any cleanup. Deploy the IAM clear-before-set code before enabling the index.
|
|
148
|
-
- Atomic switches require `PrismaModule.forRoot({ transaction: true })` to provide a real interactive transaction manager. The IAM service's no-manager fallback only performs sequential writes and is not atomic. The adapter maps primary-index `P2002` conflicts from `isPrimary: true` creates and updates to IAM code 22035 / HTTP 409, while preserving unrelated duplicate-identity errors.
|
|
149
|
-
- Run real disposable PostgreSQL 16 and MySQL 8.0 acceptance tests with `npm run test:db --workspace=@nathapp/nestjs-iam-prisma`; Docker is required, and an explicitly invoked run must fail if its container runtime is unavailable.
|
|
150
|
-
|
|
151
|
-
## API-key Scope Schema and Migration
|
|
152
|
-
|
|
153
|
-
- Keep the domain contract `ApiKey.scopes: string[]`. The shipped `ApiKey` model stores scopes as `Json @default("[]")`; its database row type is `unknown` and the adapter's local strict decoder accepts only arrays containing strings. Do not parse JSON text, filter mixed arrays, or change shared `readStringArray` behavior.
|
|
154
|
-
- The PostgreSQL reference migration is `prisma/sql/api-key-scopes.postgresql.sql`. It is consumer-owned SQL, not a migration the adapter applies. It locks `api_keys`, rejects NULL arrays and NULL elements for operator repair, converts with `to_jsonb(scopes)`, sets the JSONB `[]` default, and enforces `NOT NULL` in one transaction. Conversion preserves all valid existing arrays.
|
|
155
|
-
- Coordinate the PostgreSQL conversion, Prisma client regeneration, and adapter deployment in a maintenance window because the migration takes an `ACCESS EXCLUSIVE` lock and old scalar-list and new JSON clients are not interchangeable. If zero downtime is required, consumers need their own shadow-column/dual-write expand-contract path and must retire old clients before cutover.
|
|
156
|
-
- MySQL consumers that omitted `ApiKey` or use a custom model must add/update the model to JSON and regenerate their client. With Prisma 6, generated MySQL DDL does not emit a SQL-level default for JSON; Prisma Client still applies `[]` when a create call omits scopes. Raw SQL inserts must supply scopes or use a consumer-owned database default.
|
|
157
|
-
- The DB acceptance suite assembles the published IAM fragment directly for PostgreSQL and MySQL, changing only MySQL's `@db.Timestamptz(6)` annotation to `@db.DateTime(6)`. A separate portability test validates the tenant, IAM, account, notify, and OAuth fragments together for both providers.
|
|
158
|
-
- Timezone round-trip acceptance writes and reads `2026-10-04T08:00:00.123Z` on the same interactive-transaction connection with MySQL session time zone `+00:00` and PostgreSQL session time zone `+08:00`. Restore MySQL session state after the proof; PostgreSQL uses transaction-local timezone state.
|