@nathapp/nestjs-iam-prisma 0.0.0-stage → 1.0.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.
Files changed (62) hide show
  1. package/AGENTS.md +160 -0
  2. package/CLAUDE.md +158 -0
  3. package/GEMINI.md +158 -0
  4. package/README.md +360 -2
  5. package/codex.md +158 -0
  6. package/dist/credential-id-hash.d.ts +1 -0
  7. package/dist/credential-id-hash.js +8 -0
  8. package/dist/credential-id-hash.js.map +1 -0
  9. package/dist/iam-prisma.module.d.ts +7 -0
  10. package/dist/iam-prisma.module.js +73 -0
  11. package/dist/iam-prisma.module.js.map +1 -0
  12. package/dist/index.d.ts +15 -0
  13. package/dist/index.js +47 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/prisma-api-key.repository.d.ts +28 -0
  16. package/dist/prisma-api-key.repository.js +90 -0
  17. package/dist/prisma-api-key.repository.js.map +1 -0
  18. package/dist/prisma-auth-attempt.store.d.ts +42 -0
  19. package/dist/prisma-auth-attempt.store.js +112 -0
  20. package/dist/prisma-auth-attempt.store.js.map +1 -0
  21. package/dist/prisma-identity.repository.d.ts +26 -0
  22. package/dist/prisma-identity.repository.js +107 -0
  23. package/dist/prisma-identity.repository.js.map +1 -0
  24. package/dist/prisma-login-history.repository.d.ts +24 -0
  25. package/dist/prisma-login-history.repository.js +58 -0
  26. package/dist/prisma-login-history.repository.js.map +1 -0
  27. package/dist/prisma-mfa.repository.d.ts +20 -0
  28. package/dist/prisma-mfa.repository.js +57 -0
  29. package/dist/prisma-mfa.repository.js.map +1 -0
  30. package/dist/prisma-model.types.d.ts +188 -0
  31. package/dist/prisma-model.types.js +36 -0
  32. package/dist/prisma-model.types.js.map +1 -0
  33. package/dist/prisma-session.repository.d.ts +31 -0
  34. package/dist/prisma-session.repository.js +97 -0
  35. package/dist/prisma-session.repository.js.map +1 -0
  36. package/dist/prisma-sso-account.repository.d.ts +24 -0
  37. package/dist/prisma-sso-account.repository.js +71 -0
  38. package/dist/prisma-sso-account.repository.js.map +1 -0
  39. package/dist/prisma-sso-provider.repository.d.ts +28 -0
  40. package/dist/prisma-sso-provider.repository.js +91 -0
  41. package/dist/prisma-sso-provider.repository.js.map +1 -0
  42. package/dist/prisma-totp-replay.store.d.ts +34 -0
  43. package/dist/prisma-totp-replay.store.js +78 -0
  44. package/dist/prisma-totp-replay.store.js.map +1 -0
  45. package/dist/prisma-user.repository.d.ts +27 -0
  46. package/dist/prisma-user.repository.js +101 -0
  47. package/dist/prisma-user.repository.js.map +1 -0
  48. package/dist/prisma-verification-token.repository.d.ts +23 -0
  49. package/dist/prisma-verification-token.repository.js +66 -0
  50. package/dist/prisma-verification-token.repository.js.map +1 -0
  51. package/dist/prisma-webauthn-credential.repository.d.ts +32 -0
  52. package/dist/prisma-webauthn-credential.repository.js +113 -0
  53. package/dist/prisma-webauthn-credential.repository.js.map +1 -0
  54. package/dist/prisma-webauthn-mfa-binding.store.d.ts +26 -0
  55. package/dist/prisma-webauthn-mfa-binding.store.js +66 -0
  56. package/dist/prisma-webauthn-mfa-binding.store.js.map +1 -0
  57. package/package.json +45 -4
  58. package/prisma/iam.prisma +246 -0
  59. package/prisma/sql/api-key-scopes.postgresql.sql +18 -0
  60. package/prisma/sql/long-text-columns.mysql.sql +15 -0
  61. package/prisma/sql/primary-identity.mysql.sql +10 -0
  62. package/prisma/sql/primary-identity.postgresql.sql +11 -0
package/AGENTS.md ADDED
@@ -0,0 +1,160 @@
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 ADDED
@@ -0,0 +1,158 @@
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 ADDED
@@ -0,0 +1,158 @@
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.