@nexpress/core 0.2.2 → 0.3.1

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 (74) hide show
  1. package/dist/auth.d.ts +26 -3
  2. package/dist/auth.js +5 -3
  3. package/dist/{can-FKIEV54H.js → can-UJ2NAOIR.js} +3 -3
  4. package/dist/{chunk-CHQJG4BB.js → chunk-2N53KKIL.js} +2 -2
  5. package/dist/{chunk-DWG3RZH2.js → chunk-2VZZ7M26.js} +2 -2
  6. package/dist/{chunk-5LCLS6VE.js → chunk-56ZK5PWM.js} +19 -19
  7. package/dist/{chunk-S37WWNBB.js → chunk-6IEYOY2L.js} +28 -121
  8. package/dist/chunk-6IEYOY2L.js.map +1 -0
  9. package/dist/{chunk-QYP6E5FP.js → chunk-6UV2P5MW.js} +63 -50
  10. package/dist/chunk-6UV2P5MW.js.map +1 -0
  11. package/dist/{chunk-26RYBFTF.js → chunk-AEKO4MXK.js} +21 -4
  12. package/dist/chunk-AEKO4MXK.js.map +1 -0
  13. package/dist/{chunk-L4F5RAQ5.js → chunk-DKOCKZVG.js} +9 -9
  14. package/dist/{chunk-KSUS4UNN.js → chunk-HUESWYZJ.js} +2 -2
  15. package/dist/{chunk-CTUHJHLH.js → chunk-HVHV3IHF.js} +2 -2
  16. package/dist/chunk-P5WGQRSG.js +180 -0
  17. package/dist/chunk-P5WGQRSG.js.map +1 -0
  18. package/dist/{chunk-HM46WM45.js → chunk-RDTTK27V.js} +6 -6
  19. package/dist/{chunk-PQBJWZ7D.js → chunk-RJ76SKWQ.js} +4 -4
  20. package/dist/{chunk-74CGJJDY.js → chunk-RKM4GDWM.js} +1 -1
  21. package/dist/{chunk-7GNVXRLG.js → chunk-UIQYA3Y7.js} +5 -5
  22. package/dist/{chunk-CKT4QZDC.js → chunk-WJJ5MBH5.js} +5 -5
  23. package/dist/community.d.ts +1 -1
  24. package/dist/community.js +20 -19
  25. package/dist/{config-65OBL4YH.js → config-44MFLLIX.js} +8 -7
  26. package/dist/db-schema.d.ts +2 -2
  27. package/dist/db.d.ts +3 -3
  28. package/dist/db.js +1 -1
  29. package/dist/fields.d.ts +54 -0
  30. package/dist/fields.js +14 -0
  31. package/dist/{host-55D6RX3U.js → host-DKOWZWKA.js} +6 -5
  32. package/dist/i18n.d.ts +1 -1
  33. package/dist/i18n.js +1 -1
  34. package/dist/{index-Ccw0AkXh.d.ts → index-BmR3Z8Y5.d.ts} +1 -1
  35. package/dist/{index-BWsQUGRZ.d.ts → index-C-jKU1St.d.ts} +2 -2
  36. package/dist/{index-D6Q7DOl7.d.ts → index-Ca-WUDH5.d.ts} +1 -1
  37. package/dist/{index-BpW3PGhP.d.ts → index-lACZ9sON.d.ts} +1 -1
  38. package/dist/index.d.ts +10 -12
  39. package/dist/index.js +189 -78
  40. package/dist/index.js.map +1 -1
  41. package/dist/jobs.d.ts +2 -2
  42. package/dist/jobs.js +2 -2
  43. package/dist/media.d.ts +2 -2
  44. package/dist/media.js +2 -2
  45. package/dist/{mentions-NCQR4B72.js → mentions-U4JACYI6.js} +3 -3
  46. package/dist/{mutes-FJSSU2JP.js → mutes-MNQP6ACF.js} +3 -3
  47. package/dist/{scheduled-UC7O2HBQ.js → scheduled-VEOGI5EW.js} +7 -6
  48. package/dist/seo.js +6 -5
  49. package/dist/{settings-JODDWMDB.js → settings-OZWM6L2K.js} +2 -2
  50. package/dist/settings-OZWM6L2K.js.map +1 -0
  51. package/dist/strings-4EWJYDOG.js +1 -1
  52. package/dist/{types-C-r01wmU.d.ts → types-BY1UmEiY.d.ts} +267 -2
  53. package/package.json +6 -1
  54. package/dist/chunk-26RYBFTF.js.map +0 -1
  55. package/dist/chunk-QYP6E5FP.js.map +0 -1
  56. package/dist/chunk-S37WWNBB.js.map +0 -1
  57. /package/dist/{can-FKIEV54H.js.map → can-UJ2NAOIR.js.map} +0 -0
  58. /package/dist/{chunk-CHQJG4BB.js.map → chunk-2N53KKIL.js.map} +0 -0
  59. /package/dist/{chunk-DWG3RZH2.js.map → chunk-2VZZ7M26.js.map} +0 -0
  60. /package/dist/{chunk-5LCLS6VE.js.map → chunk-56ZK5PWM.js.map} +0 -0
  61. /package/dist/{chunk-L4F5RAQ5.js.map → chunk-DKOCKZVG.js.map} +0 -0
  62. /package/dist/{chunk-KSUS4UNN.js.map → chunk-HUESWYZJ.js.map} +0 -0
  63. /package/dist/{chunk-CTUHJHLH.js.map → chunk-HVHV3IHF.js.map} +0 -0
  64. /package/dist/{chunk-HM46WM45.js.map → chunk-RDTTK27V.js.map} +0 -0
  65. /package/dist/{chunk-PQBJWZ7D.js.map → chunk-RJ76SKWQ.js.map} +0 -0
  66. /package/dist/{chunk-74CGJJDY.js.map → chunk-RKM4GDWM.js.map} +0 -0
  67. /package/dist/{chunk-7GNVXRLG.js.map → chunk-UIQYA3Y7.js.map} +0 -0
  68. /package/dist/{chunk-CKT4QZDC.js.map → chunk-WJJ5MBH5.js.map} +0 -0
  69. /package/dist/{config-65OBL4YH.js.map → config-44MFLLIX.js.map} +0 -0
  70. /package/dist/{host-55D6RX3U.js.map → fields.js.map} +0 -0
  71. /package/dist/{mentions-NCQR4B72.js.map → host-DKOWZWKA.js.map} +0 -0
  72. /package/dist/{mutes-FJSSU2JP.js.map → mentions-U4JACYI6.js.map} +0 -0
  73. /package/dist/{scheduled-UC7O2HBQ.js.map → mutes-MNQP6ACF.js.map} +0 -0
  74. /package/dist/{settings-JODDWMDB.js.map → scheduled-VEOGI5EW.js.map} +0 -0
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-ML2E3P3X.js";
4
4
  import {
5
5
  getCommunitySettings
6
- } from "./chunk-74CGJJDY.js";
6
+ } from "./chunk-RKM4GDWM.js";
7
7
  import {
8
8
  NpAuthError,
9
9
  NpForbiddenError,
@@ -65,6 +65,18 @@ function isTokenVerificationError(err) {
65
65
  return false;
66
66
  }
67
67
 
68
+ // src/auth/users.ts
69
+ import { eq } from "drizzle-orm";
70
+ async function getUserById(id) {
71
+ const db = getDb();
72
+ const [user] = await db.select({
73
+ id: npUsers.id,
74
+ name: npUsers.name,
75
+ email: npUsers.email
76
+ }).from(npUsers).where(eq(npUsers.id, id)).limit(1);
77
+ return user ?? null;
78
+ }
79
+
68
80
  // src/auth/password.ts
69
81
  import { hash, verify } from "@node-rs/argon2";
70
82
  var ARGON2_OPTIONS = {
@@ -122,7 +134,7 @@ function resetOAuthProviders() {
122
134
  }
123
135
 
124
136
  // src/auth/oauth-resolve.ts
125
- import { eq, and, sql } from "drizzle-orm";
137
+ import { eq as eq2, and, sql } from "drizzle-orm";
126
138
  var SYNTHETIC_EMAIL_SUFFIX = ".oauth.local";
127
139
  function syntheticEmail(provider, providerUserId) {
128
140
  return `${providerUserId}@${provider}${SYNTHETIC_EMAIL_SUFFIX}`;
@@ -142,13 +154,13 @@ async function resolveOAuthLogin(input) {
142
154
  identityId: npUserOAuthIdentities.id
143
155
  }).from(npUserOAuthIdentities).where(
144
156
  and(
145
- eq(npUserOAuthIdentities.provider, provider),
146
- eq(npUserOAuthIdentities.providerUserId, profile.providerUserId)
157
+ eq2(npUserOAuthIdentities.provider, provider),
158
+ eq2(npUserOAuthIdentities.providerUserId, profile.providerUserId)
147
159
  )
148
160
  ).limit(1);
149
161
  if (existingLink) {
150
162
  const metadata = mergeMetadata(profile);
151
- await db.update(npUserOAuthIdentities).set({ metadata, updatedAt: /* @__PURE__ */ new Date() }).where(eq(npUserOAuthIdentities.id, existingLink.identityId));
163
+ await db.update(npUserOAuthIdentities).set({ metadata, updatedAt: /* @__PURE__ */ new Date() }).where(eq2(npUserOAuthIdentities.id, existingLink.identityId));
152
164
  const user = await loadUser(db, existingLink.userId);
153
165
  return { user, created: false, linked: false };
154
166
  }
@@ -160,7 +172,7 @@ async function resolveOAuthLogin(input) {
160
172
  name: npUsers.name,
161
173
  role: npUsers.role,
162
174
  tokenVersion: npUsers.tokenVersion
163
- }).from(npUsers).where(eq(sql`lower(${npUsers.email})`, normalizedEmail)).limit(1);
175
+ }).from(npUsers).where(eq2(sql`lower(${npUsers.email})`, normalizedEmail)).limit(1);
164
176
  if (existingUser) {
165
177
  await db.insert(npUserOAuthIdentities).values({
166
178
  userId: existingUser.id,
@@ -211,7 +223,7 @@ async function loadUser(db, userId) {
211
223
  name: npUsers.name,
212
224
  role: npUsers.role,
213
225
  tokenVersion: npUsers.tokenVersion
214
- }).from(npUsers).where(eq(npUsers.id, userId)).limit(1);
226
+ }).from(npUsers).where(eq2(npUsers.id, userId)).limit(1);
215
227
  if (!row) {
216
228
  throw new Error(`User ${userId} referenced by oauth identity is missing`);
217
229
  }
@@ -219,7 +231,7 @@ async function loadUser(db, userId) {
219
231
  }
220
232
 
221
233
  // src/auth/oauth-resolve-member.ts
222
- import { and as and2, eq as eq2, sql as sql2 } from "drizzle-orm";
234
+ import { and as and2, eq as eq3, sql as sql2 } from "drizzle-orm";
223
235
  var SYNTHETIC_EMAIL_SUFFIX2 = ".oauth.local";
224
236
  var HANDLE_FALLBACK = "user";
225
237
  var HANDLE_RANDOM_SUFFIX_BYTES = 4;
@@ -254,7 +266,7 @@ async function loadMember(db, memberId) {
254
266
  displayName: npMembers.displayName,
255
267
  status: npMembers.status,
256
268
  tokenVersion: npMembers.tokenVersion
257
- }).from(npMembers).where(eq2(npMembers.id, memberId)).limit(1);
269
+ }).from(npMembers).where(eq3(npMembers.id, memberId)).limit(1);
258
270
  if (!row) {
259
271
  throw new Error(`Member ${memberId} referenced by oauth identity is missing`);
260
272
  }
@@ -265,12 +277,12 @@ async function resolveMemberOAuthLogin(input) {
265
277
  const { provider, profile } = input;
266
278
  const [existingLink] = await db.select({ memberId: npMemberIdentities.memberId, identityId: npMemberIdentities.id }).from(npMemberIdentities).where(
267
279
  and2(
268
- eq2(npMemberIdentities.provider, provider),
269
- eq2(npMemberIdentities.subject, profile.providerUserId)
280
+ eq3(npMemberIdentities.provider, provider),
281
+ eq3(npMemberIdentities.subject, profile.providerUserId)
270
282
  )
271
283
  ).limit(1);
272
284
  if (existingLink) {
273
- await db.update(npMemberIdentities).set({ metadata: mergeMetadata2(profile), updatedAt: /* @__PURE__ */ new Date() }).where(eq2(npMemberIdentities.id, existingLink.identityId));
285
+ await db.update(npMemberIdentities).set({ metadata: mergeMetadata2(profile), updatedAt: /* @__PURE__ */ new Date() }).where(eq3(npMemberIdentities.id, existingLink.identityId));
274
286
  const member = await loadMember(db, existingLink.memberId);
275
287
  return { member, created: false, linked: false };
276
288
  }
@@ -283,7 +295,7 @@ async function resolveMemberOAuthLogin(input) {
283
295
  displayName: npMembers.displayName,
284
296
  status: npMembers.status,
285
297
  tokenVersion: npMembers.tokenVersion
286
- }).from(npMembers).where(eq2(sql2`lower(${npMembers.email})`, normalizedEmail)).limit(1);
298
+ }).from(npMembers).where(eq3(sql2`lower(${npMembers.email})`, normalizedEmail)).limit(1);
287
299
  if (existingMember) {
288
300
  if (existingMember.status !== "active") {
289
301
  return { member: existingMember, created: false, linked: false };
@@ -409,7 +421,7 @@ function fromArctic(factory, opts) {
409
421
 
410
422
  // src/auth/session.ts
411
423
  import { webcrypto } from "crypto";
412
- import { eq as eq3, sql as sql3 } from "drizzle-orm";
424
+ import { eq as eq4, sql as sql3 } from "drizzle-orm";
413
425
  async function sha256(input) {
414
426
  const digest = await webcrypto.subtle.digest(
415
427
  "SHA-256",
@@ -428,7 +440,7 @@ async function verifyTokenFull(token, secret, db, expectedUse = "access") {
428
440
  name: npUsers.name,
429
441
  role: npUsers.role,
430
442
  tokenVersion: npUsers.tokenVersion
431
- }).from(npUsers).where(eq3(npUsers.id, payload.sub)).limit(1);
443
+ }).from(npUsers).where(eq4(npUsers.id, payload.sub)).limit(1);
432
444
  if (!user || user.tokenVersion !== payload.ver) {
433
445
  return null;
434
446
  }
@@ -438,47 +450,47 @@ async function invalidateAllSessions(userId, db) {
438
450
  await db.transaction(async (tx) => {
439
451
  await tx.update(npUsers).set({
440
452
  tokenVersion: sql3`${npUsers.tokenVersion} + 1`
441
- }).where(eq3(npUsers.id, userId));
442
- await tx.delete(npSessions).where(eq3(npSessions.userId, userId));
453
+ }).where(eq4(npUsers.id, userId));
454
+ await tx.delete(npSessions).where(eq4(npSessions.userId, userId));
443
455
  });
444
456
  }
445
457
 
446
458
  // src/auth/identities-admin.ts
447
- import { and as and3, desc, eq as eq4 } from "drizzle-orm";
459
+ import { and as and3, desc, eq as eq5 } from "drizzle-orm";
448
460
  async function assertUserExists(userId) {
449
461
  const db = getDb();
450
- const [row] = await db.select({ id: npUsers.id }).from(npUsers).where(eq4(npUsers.id, userId)).limit(1);
462
+ const [row] = await db.select({ id: npUsers.id }).from(npUsers).where(eq5(npUsers.id, userId)).limit(1);
451
463
  if (!row) throw new NpNotFoundError("user", userId);
452
464
  }
453
465
  async function assertMemberExists(memberId) {
454
466
  const db = getDb();
455
- const [row] = await db.select({ id: npMembers.id }).from(npMembers).where(eq4(npMembers.id, memberId)).limit(1);
467
+ const [row] = await db.select({ id: npMembers.id }).from(npMembers).where(eq5(npMembers.id, memberId)).limit(1);
456
468
  if (!row) throw new NpNotFoundError("member", memberId);
457
469
  }
458
470
  async function listUserIdentities(userId) {
459
471
  await assertUserExists(userId);
460
472
  const db = getDb();
461
- const rows = await db.select().from(npUserOAuthIdentities).where(eq4(npUserOAuthIdentities.userId, userId)).orderBy(desc(npUserOAuthIdentities.createdAt));
473
+ const rows = await db.select().from(npUserOAuthIdentities).where(eq5(npUserOAuthIdentities.userId, userId)).orderBy(desc(npUserOAuthIdentities.createdAt));
462
474
  return rows;
463
475
  }
464
476
  async function listMemberIdentities(memberId) {
465
477
  await assertMemberExists(memberId);
466
478
  const db = getDb();
467
- const rows = await db.select().from(npMemberIdentities).where(eq4(npMemberIdentities.memberId, memberId)).orderBy(desc(npMemberIdentities.createdAt));
479
+ const rows = await db.select().from(npMemberIdentities).where(eq5(npMemberIdentities.memberId, memberId)).orderBy(desc(npMemberIdentities.createdAt));
468
480
  return rows;
469
481
  }
470
482
  async function revokeUserIdentity(userId, identityId, actor) {
471
483
  const db = getDb();
472
484
  const [existing] = await db.select().from(npUserOAuthIdentities).where(
473
485
  and3(
474
- eq4(npUserOAuthIdentities.id, identityId),
475
- eq4(npUserOAuthIdentities.userId, userId)
486
+ eq5(npUserOAuthIdentities.id, identityId),
487
+ eq5(npUserOAuthIdentities.userId, userId)
476
488
  )
477
489
  ).limit(1);
478
490
  if (!existing) {
479
491
  throw new NpNotFoundError("identity", identityId);
480
492
  }
481
- const deleted = await db.delete(npUserOAuthIdentities).where(eq4(npUserOAuthIdentities.id, identityId)).returning({ id: npUserOAuthIdentities.id });
493
+ const deleted = await db.delete(npUserOAuthIdentities).where(eq5(npUserOAuthIdentities.id, identityId)).returning({ id: npUserOAuthIdentities.id });
482
494
  if (deleted.length === 0) return;
483
495
  await recordAuditEvent({
484
496
  actor: { kind: "staff", userId: actor.staffUserId },
@@ -496,12 +508,12 @@ async function revokeMemberIdentity(memberId, identityId, actor) {
496
508
  const db = getDb();
497
509
  const [existing] = await db.select().from(npMemberIdentities).where(
498
510
  and3(
499
- eq4(npMemberIdentities.id, identityId),
500
- eq4(npMemberIdentities.memberId, memberId)
511
+ eq5(npMemberIdentities.id, identityId),
512
+ eq5(npMemberIdentities.memberId, memberId)
501
513
  )
502
514
  ).limit(1);
503
515
  if (!existing) throw new NpNotFoundError("identity", identityId);
504
- const deleted = await db.delete(npMemberIdentities).where(eq4(npMemberIdentities.id, identityId)).returning({ id: npMemberIdentities.id });
516
+ const deleted = await db.delete(npMemberIdentities).where(eq5(npMemberIdentities.id, identityId)).returning({ id: npMemberIdentities.id });
505
517
  if (deleted.length === 0) return;
506
518
  await recordAuditEvent({
507
519
  actor: { kind: "staff", userId: actor.staffUserId },
@@ -518,7 +530,7 @@ async function revokeMemberIdentity(memberId, identityId, actor) {
518
530
 
519
531
  // src/auth/reset-token.ts
520
532
  import { randomBytes as randomBytes3 } from "crypto";
521
- import { and as and4, eq as eq5, gt, isNotNull, sql as sql4 } from "drizzle-orm";
533
+ import { and as and4, eq as eq6, gt, isNotNull, sql as sql4 } from "drizzle-orm";
522
534
  var MIN_PASSWORD_LENGTH = 8;
523
535
  function generateRawToken() {
524
536
  return randomBytes3(32).toString("hex");
@@ -532,7 +544,7 @@ async function createPasswordResetToken(db, options) {
532
544
  passwordResetExpiresAt: expiresAt,
533
545
  passwordResetPurpose: options.purpose,
534
546
  updatedAt: /* @__PURE__ */ new Date()
535
- }).where(eq5(npUsers.id, options.userId));
547
+ }).where(eq6(npUsers.id, options.userId));
536
548
  return { token, expiresAt, purpose: options.purpose };
537
549
  }
538
550
  async function requestPasswordReset(db, email, ttlMs) {
@@ -541,7 +553,7 @@ async function requestPasswordReset(db, email, ttlMs) {
541
553
  id: npUsers.id,
542
554
  email: npUsers.email,
543
555
  name: npUsers.name
544
- }).from(npUsers).where(eq5(npUsers.email, normalizedEmail)).limit(1);
556
+ }).from(npUsers).where(eq6(npUsers.email, normalizedEmail)).limit(1);
545
557
  if (!user) {
546
558
  return { userId: null, name: null, email: null, issued: null };
547
559
  }
@@ -574,7 +586,7 @@ async function consumePasswordResetToken(db, options) {
574
586
  purpose: npUsers.passwordResetPurpose
575
587
  }).from(npUsers).where(
576
588
  and4(
577
- eq5(npUsers.passwordResetTokenHash, tokenHash),
589
+ eq6(npUsers.passwordResetTokenHash, tokenHash),
578
590
  isNotNull(npUsers.passwordResetExpiresAt),
579
591
  gt(npUsers.passwordResetExpiresAt, now)
580
592
  )
@@ -595,8 +607,8 @@ async function consumePasswordResetToken(db, options) {
595
607
  lockUntil: null,
596
608
  tokenVersion: sql4`${npUsers.tokenVersion} + 1`,
597
609
  updatedAt: /* @__PURE__ */ new Date()
598
- }).where(eq5(npUsers.id, user.id));
599
- await tx.delete(npSessions).where(eq5(npSessions.userId, user.id));
610
+ }).where(eq6(npUsers.id, user.id));
611
+ await tx.delete(npSessions).where(eq6(npSessions.userId, user.id));
600
612
  });
601
613
  return {
602
614
  userId: user.id,
@@ -631,7 +643,7 @@ async function verifyMemberToken(token, secret, expectedUse) {
631
643
  }
632
644
 
633
645
  // src/auth/member-session.ts
634
- import { and as and5, eq as eq6, gt as gt2, sql as sql5 } from "drizzle-orm";
646
+ import { and as and5, eq as eq7, gt as gt2, sql as sql5 } from "drizzle-orm";
635
647
  async function getMemberFromTokenPayload(db, payload, accessToken) {
636
648
  const [row] = await db.select({
637
649
  id: npMembers.id,
@@ -640,7 +652,7 @@ async function getMemberFromTokenPayload(db, payload, accessToken) {
640
652
  displayName: npMembers.displayName,
641
653
  status: npMembers.status,
642
654
  tokenVersion: npMembers.tokenVersion
643
- }).from(npMembers).where(eq6(npMembers.id, payload.sub)).limit(1);
655
+ }).from(npMembers).where(eq7(npMembers.id, payload.sub)).limit(1);
644
656
  if (!row) return null;
645
657
  if (row.tokenVersion !== payload.ver) return null;
646
658
  if (accessToken) {
@@ -648,8 +660,8 @@ async function getMemberFromTokenPayload(db, payload, accessToken) {
648
660
  const now = /* @__PURE__ */ new Date();
649
661
  const [session] = await db.select({ id: npMemberSessions.id }).from(npMemberSessions).where(
650
662
  and5(
651
- eq6(npMemberSessions.memberId, row.id),
652
- eq6(npMemberSessions.tokenHash, tokenHash),
663
+ eq7(npMemberSessions.memberId, row.id),
664
+ eq7(npMemberSessions.tokenHash, tokenHash),
653
665
  gt2(npMemberSessions.expiresAt, now)
654
666
  )
655
667
  ).limit(1);
@@ -662,14 +674,14 @@ async function invalidateAllMemberSessions(db, memberId) {
662
674
  await tx.update(npMembers).set({
663
675
  tokenVersion: sql5`${npMembers.tokenVersion} + 1`,
664
676
  updatedAt: /* @__PURE__ */ new Date()
665
- }).where(eq6(npMembers.id, memberId));
666
- await tx.delete(npMemberSessions).where(eq6(npMemberSessions.memberId, memberId));
677
+ }).where(eq7(npMembers.id, memberId));
678
+ await tx.delete(npMemberSessions).where(eq7(npMemberSessions.memberId, memberId));
667
679
  });
668
680
  }
669
681
 
670
682
  // src/auth/member-credentials.ts
671
683
  import { randomBytes as randomBytes5 } from "crypto";
672
- import { and as and6, eq as eq7, gt as gt3, isNotNull as isNotNull2, sql as sql6 } from "drizzle-orm";
684
+ import { and as and6, eq as eq8, gt as gt3, isNotNull as isNotNull2, sql as sql6 } from "drizzle-orm";
673
685
  var MIN_PASSWORD_LENGTH2 = 8;
674
686
  function generateRawToken2() {
675
687
  return randomBytes5(32).toString("hex");
@@ -682,7 +694,7 @@ async function createMemberEmailVerifyToken(db, memberId, ttlMs) {
682
694
  emailVerifyTokenHash: tokenHash,
683
695
  emailVerifyExpiresAt: expiresAt,
684
696
  updatedAt: /* @__PURE__ */ new Date()
685
- }).where(eq7(npMembers.id, memberId));
697
+ }).where(eq8(npMembers.id, memberId));
686
698
  return { token, expiresAt };
687
699
  }
688
700
  async function consumeMemberEmailVerifyToken(db, token) {
@@ -700,7 +712,7 @@ async function consumeMemberEmailVerifyToken(db, token) {
700
712
  displayName: npMembers.displayName
701
713
  }).from(npMembers).where(
702
714
  and6(
703
- eq7(npMembers.emailVerifyTokenHash, tokenHash),
715
+ eq8(npMembers.emailVerifyTokenHash, tokenHash),
704
716
  isNotNull2(npMembers.emailVerifyExpiresAt),
705
717
  gt3(npMembers.emailVerifyExpiresAt, now)
706
718
  )
@@ -719,7 +731,7 @@ async function consumeMemberEmailVerifyToken(db, token) {
719
731
  emailVerifyTokenHash: null,
720
732
  emailVerifyExpiresAt: null,
721
733
  updatedAt: now
722
- }).where(eq7(npMembers.id, member.id));
734
+ }).where(eq8(npMembers.id, member.id));
723
735
  return {
724
736
  memberId: member.id,
725
737
  email: member.email,
@@ -734,7 +746,7 @@ async function requestMemberPasswordReset(db, email, ttlMs) {
734
746
  email: npMembers.email,
735
747
  displayName: npMembers.displayName,
736
748
  status: npMembers.status
737
- }).from(npMembers).where(eq7(npMembers.email, normalizedEmail)).limit(1);
749
+ }).from(npMembers).where(eq8(npMembers.email, normalizedEmail)).limit(1);
738
750
  if (!member || member.status === "deleted") {
739
751
  return { memberId: null, displayName: null, email: null, issued: null };
740
752
  }
@@ -745,7 +757,7 @@ async function requestMemberPasswordReset(db, email, ttlMs) {
745
757
  passwordResetTokenHash: tokenHash,
746
758
  passwordResetExpiresAt: expiresAt,
747
759
  updatedAt: /* @__PURE__ */ new Date()
748
- }).where(eq7(npMembers.id, member.id));
760
+ }).where(eq8(npMembers.id, member.id));
749
761
  return {
750
762
  memberId: member.id,
751
763
  displayName: member.displayName,
@@ -771,7 +783,7 @@ async function consumeMemberPasswordReset(db, token, newPassword) {
771
783
  const now = /* @__PURE__ */ new Date();
772
784
  const [member] = await db.select({ id: npMembers.id, email: npMembers.email }).from(npMembers).where(
773
785
  and6(
774
- eq7(npMembers.passwordResetTokenHash, tokenHash),
786
+ eq8(npMembers.passwordResetTokenHash, tokenHash),
775
787
  isNotNull2(npMembers.passwordResetExpiresAt),
776
788
  gt3(npMembers.passwordResetExpiresAt, now)
777
789
  )
@@ -796,8 +808,8 @@ async function consumeMemberPasswordReset(db, token, newPassword) {
796
808
  emailVerified: true,
797
809
  status: sql6`case when ${npMembers.status} = 'pending' then 'active' else ${npMembers.status} end`,
798
810
  updatedAt: /* @__PURE__ */ new Date()
799
- }).where(eq7(npMembers.id, member.id));
800
- await tx.delete(npMemberSessions).where(eq7(npMemberSessions.memberId, member.id));
811
+ }).where(eq8(npMembers.id, member.id));
812
+ await tx.delete(npMemberSessions).where(eq8(npMemberSessions.memberId, member.id));
801
813
  });
802
814
  return { memberId: member.id, email: member.email };
803
815
  }
@@ -810,6 +822,7 @@ export {
810
822
  signToken,
811
823
  verifyToken,
812
824
  isTokenVerificationError,
825
+ getUserById,
813
826
  ARGON2_OPTIONS,
814
827
  hashPassword,
815
828
  verifyPassword,
@@ -842,4 +855,4 @@ export {
842
855
  requestMemberPasswordReset,
843
856
  consumeMemberPasswordReset
844
857
  };
845
- //# sourceMappingURL=chunk-QYP6E5FP.js.map
858
+ //# sourceMappingURL=chunk-6UV2P5MW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/access.ts","../src/auth/token.ts","../src/auth/users.ts","../src/auth/password.ts","../src/auth/csrf.ts","../src/auth/oauth-providers.ts","../src/auth/oauth-resolve.ts","../src/auth/oauth-resolve-member.ts","../src/auth/oauth-state.ts","../src/auth/oauth-arctic.ts","../src/auth/session.ts","../src/auth/identities-admin.ts","../src/auth/reset-token.ts","../src/auth/member-token.ts","../src/auth/member-session.ts","../src/auth/member-credentials.ts"],"sourcesContent":["import { type NpAccessFunction } from \"./types.js\";\n\nexport const authenticated: NpAccessFunction = ({ user }) => !!user;\n\nexport const isAdmin: NpAccessFunction = ({ user }) => user?.role === \"admin\";\n\nexport const isEditorOrAbove: NpAccessFunction = ({ user }) =>\n !!user && (user.role === \"admin\" || user.role === \"editor\");\n\nexport const isOwnerOrAdmin: NpAccessFunction = ({ user, doc }) =>\n user?.role === \"admin\" || doc?.createdBy === user?.id;\n","import { randomBytes } from \"node:crypto\";\nimport { jwtVerify, SignJWT, errors as joseErrors, type JWTPayload } from \"jose\";\n\nimport type { NpUserRole } from \"../config/types.js\";\nimport { NpAuthError } from \"../errors.js\";\n\n/**\n * Staff-side JWT helpers. Both access (`np-session`) and refresh\n * (`np-refresh`) cookies are signed with this module; the\n * `use: \"access\" | \"refresh\"` claim separates them so a stolen\n * refresh JWT cannot be replayed as a session cookie. Without this\n * separation a leaked 7-day refresh became a 7-day admin bearer\n * because both cookies decoded to the same `{ sub, role, ver }`\n * payload through `verifyToken` (#94).\n *\n * The fix mirrors the member-side fix from #92/#93: the `use` claim\n * is required, no legacy fallback for tokens missing the claim. The\n * cost is one forced re-login for staff sessions issued before the\n * deploy; bounded by the 7-day refresh TTL.\n */\nexport type NpTokenUse = \"access\" | \"refresh\";\n\nexport interface NpTokenPayload {\n sub: string;\n role: NpUserRole;\n ver: number;\n /** Required. `verifyToken` refuses tokens missing this claim so\n * legacy refresh JWTs cannot be smuggled into the session\n * cookie path. */\n use: NpTokenUse;\n /** Random per-token id — needed if rotation lands on the staff\n * side (mirrors the member-side `jti` for #45). Optional today\n * but populated on every newly-minted token. */\n jti?: string;\n iat: number;\n exp: number;\n}\n\nconst textEncoder = new TextEncoder();\n\nexport async function signToken(\n user: { id: string; role: NpUserRole; tokenVersion: number },\n secret: string,\n expirationSeconds: number = 7200,\n tokenUse: NpTokenUse = \"access\",\n): Promise<string> {\n const secretKey = textEncoder.encode(secret);\n\n return new SignJWT({\n sub: user.id,\n role: user.role,\n ver: user.tokenVersion,\n use: tokenUse,\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .setJti(randomBytes(16).toString(\"base64url\"))\n .setIssuedAt()\n .setExpirationTime(Math.floor(Date.now() / 1000) + expirationSeconds)\n .sign(secretKey);\n}\n\n/**\n * Verify a staff JWT. When `expectedUse` is provided, refuses tokens\n * whose `use` claim doesn't match — that's how `getSessionUser`\n * rejects a refresh token used as a session cookie and how the\n * refresh route rejects an access token as a refresh trigger.\n *\n * Tokens minted before the `use` claim landed have NO `use` payload\n * field. We refuse those outright rather than treating them as\n * `access` — the prior fallback would let still-live legacy refresh\n * JWTs be smuggled into the session cookie and pass the access\n * check. Cost: staff logged in before this deploy must log in once.\n * Bounded by the refresh-token TTL (default 7 days).\n */\nexport async function verifyToken(\n token: string,\n secret: string,\n expectedUse?: NpTokenUse,\n): Promise<NpTokenPayload> {\n const secretKey = textEncoder.encode(secret);\n const { payload } = await jwtVerify(token, secretKey);\n const typed = payload as JWTPayload & {\n sub: string;\n role: NpUserRole;\n ver: number;\n iat: number;\n exp: number;\n use?: NpTokenUse;\n };\n if (typed.use !== \"access\" && typed.use !== \"refresh\") {\n throw new NpAuthError(\"Staff token missing `use` claim\");\n }\n const use: NpTokenUse = typed.use;\n if (expectedUse && use !== expectedUse) {\n throw new NpAuthError(\n `Staff token use mismatch: expected ${expectedUse}, got ${use}`,\n );\n }\n return { ...typed, use };\n}\n\n/**\n * True when `err` represents a token-verification failure rather than\n * an unrelated runtime fault (DB outage, misconfiguration, …). Auth\n * helpers use this to keep the existing \"bad token → 401\" behavior\n * silent while letting infrastructure failures surface as 5xx.\n *\n * Covers:\n * - `NpAuthError` — `verifyToken` / `verifyMemberToken` rejecting a\n * missing or wrong `use` claim, or `verifyCsrf` failing.\n * - `jose.errors.JOSEError` — every JWT signature / format /\n * expiration failure, including subclasses like `JWTExpired`,\n * `JWSSignatureVerificationFailed`, `JWTInvalid`.\n */\nexport function isTokenVerificationError(err: unknown): boolean {\n if (err instanceof NpAuthError) return true;\n if (err instanceof joseErrors.JOSEError) return true;\n return false;\n}\n","import { eq } from \"drizzle-orm\";\n\nimport { getDb } from \"../db/runtime.js\";\nimport { npUsers } from \"../db/schema/system.js\";\n\n/**\n * Minimal public projection of a user row — `id` + `name` + `email`.\n * Themes / plugins reach for this when they need to display a byline\n * (post.author → user) without pulling in session machinery. Password\n * hash + tokenVersion + reset state stay private to the auth module.\n */\nexport interface NpUserBasic {\n id: string;\n name: string;\n email: string;\n}\n\n/**\n * Look up a user by id. Returns `null` when the id doesn't exist\n * (caller handles missing-author UI). UUID validation lives at the\n * caller — Postgres rejects malformed ids inside `eq()` and the\n * surfacing error is already informative.\n *\n * This is the supported entry point for theme code that needs to\n * render a byline from `posts.author: relationTo(\"users\")`. Direct\n * drizzle reads against `np_users` are private to the framework.\n */\nexport async function getUserById(id: string): Promise<NpUserBasic | null> {\n const db = getDb();\n const [user] = await db\n .select({\n id: npUsers.id,\n name: npUsers.name,\n email: npUsers.email,\n })\n .from(npUsers)\n .where(eq(npUsers.id, id))\n .limit(1);\n return user ?? null;\n}\n","import { hash, verify, type Options } from \"@node-rs/argon2\";\n\nexport const ARGON2_OPTIONS: Options = {\n memoryCost: 19456,\n timeCost: 2,\n outputLen: 32,\n parallelism: 1,\n};\n\n// Test-only weak params — drops a hash from ~75ms to <1ms. Only kicks in\n// when NP_TEST_FAST_HASH=1 is explicitly set (vitest's setup-env.ts does\n// this) so production / dev never see weakened security.\nconst TEST_ARGON2_OPTIONS: Options = {\n memoryCost: 8,\n timeCost: 1,\n outputLen: 32,\n parallelism: 1,\n};\n\nexport function hashPassword(password: string): Promise<string> {\n return hash(\n password,\n process.env.NP_TEST_FAST_HASH === \"1\" ? TEST_ARGON2_OPTIONS : ARGON2_OPTIONS,\n );\n}\n\nexport function verifyPassword(\n passwordHash: string,\n password: string,\n): Promise<boolean> {\n return verify(passwordHash, password);\n}\n","const SAFE_METHODS = new Set([\"GET\", \"HEAD\", \"OPTIONS\"]);\n\nexport function verifyCsrf(\n method: string,\n cookieToken: string | undefined,\n headerToken: string | undefined,\n): boolean {\n if (SAFE_METHODS.has(method.toUpperCase())) {\n return true;\n }\n\n return Boolean(cookieToken && headerToken && cookieToken === headerToken);\n}\n","/**\n * OAuth provider registry — extension point for SSO. A provider plugin\n * (e.g. `@nexpress/plugin-oauth-github`) registers itself at startup\n * via `registerOAuthProvider()`; the framework's `/api/auth/oauth/{id}`\n * routes look it up by id.\n *\n * The provider is responsible for:\n * - Building the authorize URL (`authorize`).\n * - Exchanging the callback code for a normalized profile (`exchange`).\n *\n * The framework owns state-cookie signing, identity ↔ user resolution,\n * session minting, and audit. Providers must NOT touch cookies, the DB,\n * or response objects directly.\n */\n\n/**\n * Profile returned from a successful `exchange()`. The framework uses\n * `providerUserId` as the durable identifier — `email` may change at the\n * provider but `providerUserId` should not. If the provider doesn't\n * surface `email`, the framework falls back to creating a synthetic\n * placeholder (`<providerUserId>@<provider>.oauth.local`) so the\n * `np_users.email NOT NULL UNIQUE` constraint is still satisfied.\n */\nexport interface OAuthProfile {\n /** Stable per-user id from the provider. Required. */\n providerUserId: string;\n /** Optional — falls back to synthetic if missing. */\n email?: string | null;\n /** Optional — defaults to email local-part on user creation. */\n name?: string | null;\n /** Optional — written into `np_user_oauth_identities.metadata`. */\n avatarUrl?: string | null;\n /** Optional — full payload the provider wants to remember (e.g. scopes). */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Inputs the provider receives at the two callback boundaries. The\n * framework picks `redirectUri` from `SITE_URL` (or the request origin\n * in dev) so the provider doesn't have to know its own deployment URL.\n */\nexport interface OAuthAuthorizeParams {\n state: string;\n redirectUri: string;\n /**\n * PKCE code verifier (32+ char URL-safe random). The framework\n * generates one for every login and threads it through the state\n * cookie. Providers that don't support PKCE (e.g. GitHub) ignore it;\n * providers that require it (e.g. Google) hash it into the\n * `code_challenge` query param.\n */\n codeVerifier: string;\n}\n\nexport interface OAuthExchangeParams {\n code: string;\n state: string;\n redirectUri: string;\n /** Same verifier minted at /start, recovered from the state cookie. */\n codeVerifier: string;\n}\n\nexport interface OAuthProvider {\n /** Stable id used in route paths and `np_user_oauth_identities.provider`. */\n id: string;\n /** Human-readable label for admin UI / login buttons. */\n label?: string;\n /**\n * Returns a fully-qualified URL the framework should redirect the\n * browser to. Async to allow providers that need to mint per-request\n * client credentials.\n */\n authorize(params: OAuthAuthorizeParams): Promise<string> | string;\n /**\n * Validates the callback and returns the normalized profile.\n * Throwing here aborts the login with `OAUTH_EXCHANGE_FAILED`.\n */\n exchange(params: OAuthExchangeParams): Promise<OAuthProfile>;\n}\n\nconst providers = new Map<string, OAuthProvider>();\n\n/**\n * Register a provider. Idempotent: re-registering with the same id\n * overwrites — useful in dev when a plugin's `setup()` runs again on\n * reload.\n */\nexport function registerOAuthProvider(provider: OAuthProvider): void {\n if (!provider.id || typeof provider.id !== \"string\") {\n throw new Error(\"OAuth provider must have a non-empty string id\");\n }\n if (typeof provider.authorize !== \"function\" || typeof provider.exchange !== \"function\") {\n throw new Error(\n `OAuth provider \"${provider.id}\" must implement authorize() and exchange()`,\n );\n }\n providers.set(provider.id, provider);\n}\n\nexport function getOAuthProvider(id: string): OAuthProvider | undefined {\n return providers.get(id);\n}\n\nexport function listOAuthProviders(): OAuthProvider[] {\n return Array.from(providers.values());\n}\n\n/** Reset the registry — tests use this between cases. Not for runtime use. */\nexport function resetOAuthProviders(): void {\n providers.clear();\n}\n","import { eq, and, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\n\nimport { getDb } from \"../db/runtime.js\";\nimport { npUserOAuthIdentities, npUsers } from \"../db/schema/system.js\";\nimport type { NpUserRole } from \"../config/types.js\";\n\nimport { hashPassword } from \"./password.js\";\nimport type { OAuthProfile } from \"./oauth-providers.js\";\n\n/**\n * Resolves an `OAuthProfile` to a real `np_users` row, in this order:\n *\n * 1. Lookup by `(provider, provider_user_id)` — the durable link. This\n * is the only path that survives an email change at the provider.\n * 2. Email-match — if the provider gave us an email and an existing\n * user has it, link the OAuth identity to that user. Lets a staff\n * member who originally signed up with a password later \"sign in\n * with Google\" and have it just work, without an explicit linking\n * UI.\n * 3. Create — auto-provision a new user with the provider's profile,\n * default role `viewer`. The password column is filled with an\n * unrecoverable Argon2 hash of a random secret so the column\n * constraints are satisfied; the user can later run the\n * forgot-password flow to set a real password if they want one.\n *\n * Side effects: writes a row into `np_user_oauth_identities` for paths\n * 2 and 3, updates `metadata` for path 1.\n */\nexport interface ResolveOAuthLoginResult {\n user: ResolvedOAuthUser;\n /** Tells the caller whether this login created the underlying user. */\n created: boolean;\n /** Tells the caller whether this login linked a new identity row. */\n linked: boolean;\n}\n\nexport interface ResolvedOAuthUser {\n id: string;\n email: string;\n name: string;\n role: NpUserRole;\n tokenVersion: number;\n}\n\nexport interface ResolveOAuthLoginInput {\n provider: string;\n profile: OAuthProfile;\n /** Default role for auto-created users. Defaults to `\"viewer\"`. */\n defaultRole?: NpUserRole;\n}\n\nconst SYNTHETIC_EMAIL_SUFFIX = \".oauth.local\";\n\nfunction syntheticEmail(provider: string, providerUserId: string): string {\n // Stable, namespaced, doesn't collide with real provider domains.\n return `${providerUserId}@${provider}${SYNTHETIC_EMAIL_SUFFIX}`;\n}\n\nfunction deriveName(profile: OAuthProfile, fallbackEmail: string): string {\n if (profile.name && profile.name.trim().length > 0) return profile.name.trim();\n const localPart = fallbackEmail.split(\"@\")[0];\n return localPart && localPart.length > 0 ? localPart : \"Member\";\n}\n\nexport async function resolveOAuthLogin(\n input: ResolveOAuthLoginInput,\n): Promise<ResolveOAuthLoginResult> {\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n const provider = input.provider;\n const profile = input.profile;\n const role: NpUserRole = input.defaultRole ?? \"viewer\";\n\n // Step 1: lookup by durable provider link.\n const [existingLink] = (await db\n .select({\n userId: npUserOAuthIdentities.userId,\n identityId: npUserOAuthIdentities.id,\n })\n .from(npUserOAuthIdentities)\n .where(\n and(\n eq(npUserOAuthIdentities.provider, provider),\n eq(npUserOAuthIdentities.providerUserId, profile.providerUserId),\n ),\n )\n .limit(1)) as Array<{ userId: string; identityId: string }>;\n\n if (existingLink) {\n // Refresh metadata so the most recent provider info is captured.\n const metadata = mergeMetadata(profile);\n await db\n .update(npUserOAuthIdentities)\n .set({ metadata, updatedAt: new Date() })\n .where(eq(npUserOAuthIdentities.id, existingLink.identityId));\n\n const user = await loadUser(db, existingLink.userId);\n return { user, created: false, linked: false };\n }\n\n // Step 2: email match. Skipped when the provider doesn't surface an\n // email — we can't risk linking by guesswork.\n if (profile.email) {\n const normalizedEmail = profile.email.trim().toLowerCase();\n const [existingUser] = (await db\n .select({\n id: npUsers.id,\n email: npUsers.email,\n name: npUsers.name,\n role: npUsers.role,\n tokenVersion: npUsers.tokenVersion,\n })\n .from(npUsers)\n .where(eq(sql`lower(${npUsers.email})`, normalizedEmail))\n .limit(1)) as ResolvedOAuthUser[];\n\n if (existingUser) {\n await db.insert(npUserOAuthIdentities).values({\n userId: existingUser.id,\n provider,\n providerUserId: profile.providerUserId,\n metadata: mergeMetadata(profile),\n });\n return { user: existingUser, created: false, linked: true };\n }\n }\n\n // Step 3: auto-provision.\n const email =\n profile.email && profile.email.trim().length > 0\n ? profile.email.trim().toLowerCase()\n : syntheticEmail(provider, profile.providerUserId);\n const name = deriveName(profile, email);\n const placeholderPassword = await hashPassword(\n crypto.randomUUID() + crypto.randomUUID(),\n );\n\n const [created] = (await db\n .insert(npUsers)\n .values({\n email,\n name,\n password: placeholderPassword,\n role,\n })\n .returning({\n id: npUsers.id,\n email: npUsers.email,\n name: npUsers.name,\n role: npUsers.role,\n tokenVersion: npUsers.tokenVersion,\n })) as ResolvedOAuthUser[];\n\n await db.insert(npUserOAuthIdentities).values({\n userId: created.id,\n provider,\n providerUserId: profile.providerUserId,\n metadata: mergeMetadata(profile),\n });\n\n return { user: created, created: true, linked: true };\n}\n\nfunction mergeMetadata(profile: OAuthProfile): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (profile.avatarUrl) base.avatarUrl = profile.avatarUrl;\n if (profile.email) base.email = profile.email;\n if (profile.name) base.name = profile.name;\n if (profile.metadata) Object.assign(base, profile.metadata);\n return base;\n}\n\nasync function loadUser(\n db: NodePgDatabase<Record<string, unknown>>,\n userId: string,\n): Promise<ResolvedOAuthUser> {\n const [row] = (await db\n .select({\n id: npUsers.id,\n email: npUsers.email,\n name: npUsers.name,\n role: npUsers.role,\n tokenVersion: npUsers.tokenVersion,\n })\n .from(npUsers)\n .where(eq(npUsers.id, userId))\n .limit(1)) as ResolvedOAuthUser[];\n if (!row) {\n throw new Error(`User ${userId} referenced by oauth identity is missing`);\n }\n return row;\n}\n","import { and, eq, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\n\nimport { getDb } from \"../db/runtime.js\";\nimport { getCommunitySettings } from \"../community/settings.js\";\nimport { npMemberIdentities, npMembers } from \"../db/schema/community.js\";\nimport { NpForbiddenError } from \"../errors.js\";\n\nimport { hashPassword } from \"./password.js\";\nimport type { OAuthProfile } from \"./oauth-providers.js\";\n\n/**\n * Member-side mirror of `resolveOAuthLogin` (the staff resolver in\n * `oauth-resolve.ts`). Walks the same three-step ladder:\n *\n * 1. Lookup by `(provider, subject)` in `np_member_identities` —\n * durable provider link.\n * 2. Email match — if the profile carries an email, link the\n * identity to the existing `np_members` row.\n * 3. Auto-provision a new member with status=`active`, default\n * password = unrecoverable Argon2 of a random secret. The user\n * can later run forgot-password to set a real password if they\n * want one (or stay SSO-only).\n *\n * Members are kept distinct from staff users at every layer\n * (different table, different cookies, different audience claim on\n * the JWT). This resolver intentionally never touches `np_users`.\n */\nexport interface ResolvedOAuthMember {\n id: string;\n email: string;\n handle: string;\n displayName: string;\n status: \"active\" | \"pending\" | \"suspended\" | \"deleted\";\n tokenVersion: number;\n}\n\nexport interface ResolveMemberOAuthLoginInput {\n provider: string;\n profile: OAuthProfile;\n}\n\nexport interface ResolveMemberOAuthLoginResult {\n member: ResolvedOAuthMember;\n /** True when this login auto-provisioned the underlying member. */\n created: boolean;\n /** True when this login linked a new identity row (covers steps 2 + 3). */\n linked: boolean;\n}\n\nconst SYNTHETIC_EMAIL_SUFFIX = \".oauth.local\";\nconst HANDLE_FALLBACK = \"user\";\nconst HANDLE_RANDOM_SUFFIX_BYTES = 4;\n\nfunction syntheticEmail(provider: string, providerUserId: string): string {\n return `${providerUserId}@${provider}${SYNTHETIC_EMAIL_SUFFIX}`;\n}\n\n/**\n * Members have a unique `handle` field. Build a candidate from the\n * provider's profile, sanitize to the project's handle regex, and add\n * a short random suffix to dodge collisions on common values like\n * \"alice\" / \"octocat\".\n *\n * Handle regex (per `register/route.ts`):\n * /^[a-z0-9][a-z0-9_-]{2,29}$/\n */\nfunction generateHandle(profile: OAuthProfile, fallbackEmail: string): string {\n const seed =\n (profile.metadata && typeof profile.metadata.login === \"string\" && profile.metadata.login) ||\n profile.name ||\n fallbackEmail.split(\"@\")[0] ||\n HANDLE_FALLBACK;\n const sanitized = String(seed)\n .toLowerCase()\n .replace(/[^a-z0-9_-]/g, \"-\")\n .replace(/^[-_]+/, \"\")\n .slice(0, 20);\n const base = sanitized.length >= 3 ? sanitized : HANDLE_FALLBACK;\n // Random suffix keeps handles unique across the OAuth user pool —\n // accept the cost of \"alice-9k2x\" rather than fighting a tight loop\n // of insert-and-retry on every collision.\n const suffix = Math.random()\n .toString(36)\n .slice(2, 2 + HANDLE_RANDOM_SUFFIX_BYTES);\n return `${base}-${suffix}`.slice(0, 30);\n}\n\nfunction deriveDisplayName(profile: OAuthProfile, fallbackEmail: string): string {\n if (profile.name && profile.name.trim().length > 0) return profile.name.trim();\n const localPart = fallbackEmail.split(\"@\")[0];\n return localPart && localPart.length > 0 ? localPart : \"Member\";\n}\n\nfunction mergeMetadata(profile: OAuthProfile): Record<string, unknown> {\n const base: Record<string, unknown> = {};\n if (profile.avatarUrl) base.avatarUrl = profile.avatarUrl;\n if (profile.email) base.email = profile.email;\n if (profile.name) base.name = profile.name;\n if (profile.metadata) Object.assign(base, profile.metadata);\n return base;\n}\n\nasync function loadMember(\n db: NodePgDatabase<Record<string, unknown>>,\n memberId: string,\n): Promise<ResolvedOAuthMember> {\n const [row] = (await db\n .select({\n id: npMembers.id,\n email: npMembers.email,\n handle: npMembers.handle,\n displayName: npMembers.displayName,\n status: npMembers.status,\n tokenVersion: npMembers.tokenVersion,\n })\n .from(npMembers)\n .where(eq(npMembers.id, memberId))\n .limit(1)) as ResolvedOAuthMember[];\n if (!row) {\n throw new Error(`Member ${memberId} referenced by oauth identity is missing`);\n }\n return row;\n}\n\nexport async function resolveMemberOAuthLogin(\n input: ResolveMemberOAuthLoginInput,\n): Promise<ResolveMemberOAuthLoginResult> {\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n const { provider, profile } = input;\n\n // Step 1: durable lookup.\n const [existingLink] = (await db\n .select({ memberId: npMemberIdentities.memberId, identityId: npMemberIdentities.id })\n .from(npMemberIdentities)\n .where(\n and(\n eq(npMemberIdentities.provider, provider),\n eq(npMemberIdentities.subject, profile.providerUserId),\n ),\n )\n .limit(1)) as Array<{ memberId: string; identityId: string }>;\n\n if (existingLink) {\n await db\n .update(npMemberIdentities)\n .set({ metadata: mergeMetadata(profile), updatedAt: new Date() })\n .where(eq(npMemberIdentities.id, existingLink.identityId));\n const member = await loadMember(db, existingLink.memberId);\n return { member, created: false, linked: false };\n }\n\n // Step 2: email match.\n if (profile.email) {\n const normalizedEmail = profile.email.trim().toLowerCase();\n const [existingMember] = (await db\n .select({\n id: npMembers.id,\n email: npMembers.email,\n handle: npMembers.handle,\n displayName: npMembers.displayName,\n status: npMembers.status,\n tokenVersion: npMembers.tokenVersion,\n })\n .from(npMembers)\n .where(eq(sql`lower(${npMembers.email})`, normalizedEmail))\n .limit(1)) as ResolvedOAuthMember[];\n\n if (existingMember) {\n // Refuse to auto-link an OAuth identity to a non-active member.\n // Without this guard an attacker who controls an OAuth account\n // with a victim's email could pre-link an identity to the\n // victim's pending (unverified) row; once the victim later\n // activates, the attacker's identity is already attached and\n // they can sign in as the victim. The callback would still\n // refuse the immediate login (status check below), but the\n // dangling link would persist.\n //\n // Active members are the only ones we'll cross-link\n // automatically — pending / suspended / deleted are returned\n // as-is and the route's status check refuses the login.\n if (existingMember.status !== \"active\") {\n return { member: existingMember, created: false, linked: false };\n }\n await db.insert(npMemberIdentities).values({\n memberId: existingMember.id,\n provider,\n subject: profile.providerUserId,\n email: profile.email,\n metadata: mergeMetadata(profile),\n });\n return { member: existingMember, created: false, linked: true };\n }\n }\n\n // Step 3: auto-provision a brand-new member account. This is the\n // step the `community.registrationEnabled` site setting gates —\n // an invite-only site that disables password sign-up via\n // `/api/members/register` would otherwise be joined through OAuth\n // (the password endpoint and OAuth callback both create new\n // member rows from an unauthenticated request, so they're the\n // same surface from a policy point of view).\n //\n // Steps 1 and 2 are NOT gated: durable links and email matches\n // log an EXISTING member back in, which isn't a new\n // registration. An admin who flips `registrationEnabled = false`\n // expects existing members to keep working — only new accounts\n // should be refused.\n const settings = await getCommunitySettings();\n if (!settings.registrationEnabled) {\n throw new NpForbiddenError(\"members\", \"register\");\n }\n\n const email =\n profile.email && profile.email.trim().length > 0\n ? profile.email.trim().toLowerCase()\n : syntheticEmail(provider, profile.providerUserId);\n const displayName = deriveDisplayName(profile, email);\n const handle = generateHandle(profile, email);\n const placeholderPassword = await hashPassword(\n crypto.randomUUID() + crypto.randomUUID(),\n );\n\n const [created] = (await db\n .insert(npMembers)\n .values({\n email,\n handle,\n displayName,\n password: placeholderPassword,\n // OAuth verifies the address out-of-band (the provider showed the\n // user a real login screen for it), so skip the email-verify\n // dance that password registration goes through.\n emailVerified: true,\n status: \"active\",\n })\n .returning({\n id: npMembers.id,\n email: npMembers.email,\n handle: npMembers.handle,\n displayName: npMembers.displayName,\n status: npMembers.status,\n tokenVersion: npMembers.tokenVersion,\n })) as ResolvedOAuthMember[];\n\n await db.insert(npMemberIdentities).values({\n memberId: created.id,\n provider,\n subject: profile.providerUserId,\n email: profile.email ?? null,\n metadata: mergeMetadata(profile),\n });\n\n return { member: created, created: true, linked: true };\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\n\nimport { readEnvPositiveInt } from \"../config/env.js\";\n\n/**\n * HMAC-signed state tokens for the OAuth start ↔ callback handshake.\n * The framework (not the provider) issues + verifies these — providers\n * only see them as opaque strings.\n *\n * Token shape: `<base64url(payload)>.<base64url(hmac)>` where payload is\n * JSON `{ providerId, nonce, expSeconds, codeVerifier }`. Using an HMAC\n * instead of a JWT keeps this self-contained — no jose import, no key\n * rotation surface — and the payload stays comfortably under the\n * cookie size cap.\n *\n * The `codeVerifier` is a 32-byte URL-safe random string that providers\n * supporting PKCE (Google, etc.) hash into the authorize URL. Providers\n * that don't use PKCE (GitHub) ignore it. We always generate one so the\n * flow is uniform.\n *\n * Default state TTL is 10 minutes — long enough for slow IdP redirects\n * (corporate SSO with MFA prompts), short enough that a stale state\n * cookie doesn't sit around forever. Override via\n * `NP_OAUTH_STATE_TTL_SECONDS`.\n */\n\nconst STATE_TTL_SECONDS = readEnvPositiveInt(\"NP_OAUTH_STATE_TTL_SECONDS\", 600);\nconst CODE_VERIFIER_BYTES = 32;\n\nexport interface OAuthStatePayload {\n providerId: string;\n nonce: string;\n expSeconds: number;\n codeVerifier: string;\n}\n\nexport interface IssuedOAuthState {\n /** The serialized state token (cookie + redirect query value). */\n token: string;\n /** The PKCE verifier — also embedded in the token, surfaced here so\n * the route can pass it to `provider.authorize()` without re-parsing. */\n codeVerifier: string;\n}\n\nfunction b64url(input: string | Buffer): string {\n return Buffer.from(input).toString(\"base64url\");\n}\n\nfunction sign(payload: string, secret: string): string {\n return createHmac(\"sha256\", secret).update(payload).digest(\"base64url\");\n}\n\nexport function issueOAuthState(providerId: string, secret: string): IssuedOAuthState {\n const nonce = randomBytes(16).toString(\"base64url\");\n const codeVerifier = randomBytes(CODE_VERIFIER_BYTES).toString(\"base64url\");\n const expSeconds = Math.floor(Date.now() / 1000) + STATE_TTL_SECONDS;\n const payload: OAuthStatePayload = { providerId, nonce, expSeconds, codeVerifier };\n const encoded = b64url(JSON.stringify(payload));\n const sig = sign(encoded, secret);\n return { token: `${encoded}.${sig}`, codeVerifier };\n}\n\nexport interface VerifyOAuthStateResult {\n ok: boolean;\n payload?: OAuthStatePayload;\n reason?: \"format\" | \"signature\" | \"expired\";\n}\n\n/**\n * Strict verification:\n * - Format must be `<payload>.<sig>` with two segments.\n * - HMAC must match (constant-time compare).\n * - `expSeconds` must be in the future.\n * - `providerId` in the payload must match the route's expected provider.\n * - `codeVerifier` must be a non-empty string.\n */\nexport function verifyOAuthState(\n token: string,\n expectedProviderId: string,\n secret: string,\n): VerifyOAuthStateResult {\n if (typeof token !== \"string\" || !token.includes(\".\")) {\n return { ok: false, reason: \"format\" };\n }\n const [encoded, sig] = token.split(\".\") as [string, string];\n if (!encoded || !sig) {\n return { ok: false, reason: \"format\" };\n }\n const expectedSig = sign(encoded, secret);\n const sigBuf = Buffer.from(sig);\n const expectedBuf = Buffer.from(expectedSig);\n if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {\n return { ok: false, reason: \"signature\" };\n }\n\n let payload: OAuthStatePayload;\n try {\n payload = JSON.parse(Buffer.from(encoded, \"base64url\").toString(\"utf8\"));\n } catch {\n return { ok: false, reason: \"format\" };\n }\n\n if (\n !payload ||\n typeof payload.providerId !== \"string\" ||\n typeof payload.nonce !== \"string\" ||\n typeof payload.expSeconds !== \"number\" ||\n typeof payload.codeVerifier !== \"string\" ||\n payload.codeVerifier.length === 0\n ) {\n return { ok: false, reason: \"format\" };\n }\n\n if (payload.providerId !== expectedProviderId) {\n return { ok: false, reason: \"signature\" };\n }\n\n if (payload.expSeconds <= Math.floor(Date.now() / 1000)) {\n return { ok: false, reason: \"expired\" };\n }\n\n return { ok: true, payload };\n}\n","import type { OAuthProfile, OAuthProvider } from \"./oauth-providers.js\";\n\n/**\n * Adapter that bridges any [arctic](https://arctic.js.org/) provider\n * (`new GitHub(...)`, `new Google(...)`, `new Apple(...)`, etc.) to\n * NexPress's `OAuthProvider` interface.\n *\n * Why this exists: arctic ships ~25 maintained providers and handles\n * the OAuth dance — token exchange, PKCE hashing, refresh-token\n * support — so plugin authors only have to write the **profile fetch**\n * (the part that varies most by provider). Our framework still owns\n * state cookies, identity ↔ user resolution, and session minting; this\n * adapter just lets users skip the boilerplate token POST.\n *\n * Usage from a plugin:\n *\n * import { Apple } from \"arctic\";\n * import { fromArctic, registerOAuthProvider } from \"@nexpress/core\";\n *\n * registerOAuthProvider(fromArctic(\n * // Factory: framework calls this each request with the freshly-\n * // resolved redirectUri (matters in dev when Next.js may bind a\n * // non-default port).\n * (redirectUri) => new Apple(clientId, teamId, keyId, privateKey, redirectUri),\n * {\n * id: \"apple\",\n * scopes: [\"name\", \"email\"],\n * fetchProfile: async (accessToken, tokens) => {\n * // Apple returns the user payload INSIDE the token response\n * // (not a separate userinfo endpoint) — pull it from\n * // `tokens.idToken()` here and parse the JWT body.\n * return { providerUserId: parseAppleSub(tokens.idToken()), email: null };\n * },\n * },\n * ));\n */\n\n/**\n * Minimal slice of arctic's provider classes that the adapter actually\n * needs. Both `GitHub` (no PKCE) and `Google` (PKCE-required) match\n * this — the third positional arg is \"second positional\" for\n * non-PKCE providers (just unused) and \"code verifier\" for PKCE ones.\n *\n * Declared structurally so we don't drag arctic into the public type\n * graph of `@nexpress/core`. Plugins that import a real arctic class\n * pass it directly; the structural match keeps the signature lined up.\n */\nexport interface ArcticLikeProvider {\n createAuthorizationURL(state: string, ...rest: never[]): URL;\n validateAuthorizationCode(code: string, ...rest: never[]): Promise<ArcticLikeTokens>;\n}\n\nexport interface ArcticLikeTokens {\n accessToken(): string;\n hasRefreshToken?(): boolean;\n refreshToken?(): string;\n idToken?(): string;\n}\n\nexport interface FromArcticOptions {\n /** Provider id used in route paths and `np_user_oauth_identities.provider`. */\n id: string;\n /** Human label for admin UI / login buttons. */\n label?: string;\n /** Scopes passed to `createAuthorizationURL`. Most providers default\n * to nothing useful — set this. */\n scopes?: string[];\n /**\n * Whether the underlying arctic provider expects a PKCE code verifier\n * as the second arg to `createAuthorizationURL` and\n * `validateAuthorizationCode`. Default `true` (Google, Apple, etc.).\n * Set `false` for non-PKCE providers like GitHub.\n */\n pkce?: boolean;\n /**\n * Turns an access token (and the full token response, useful for\n * providers like Apple that return the profile in the token) into the\n * normalized `OAuthProfile` consumed by `resolveOAuthLogin`.\n *\n * Throwing aborts the login with `oauth_error=exchange_failed`.\n */\n fetchProfile: (\n accessToken: string,\n tokens: ArcticLikeTokens,\n ) => Promise<OAuthProfile>;\n}\n\n/**\n * Wraps an arctic provider into the framework's `OAuthProvider`\n * shape. The framework calls `authorize` and `exchange`; this adapter\n * builds a fresh arctic instance per request via `factory(redirectUri)`\n * so the redirect URI always matches what the framework computed for\n * THIS request — critical in dev where Next.js may fall back to a\n * non-3000 port and a setup-time-frozen redirectUri would diverge.\n *\n * Arctic provider classes are cheap to construct (just hold the three\n * credential strings), so the per-request factory call has no\n * meaningful cost.\n */\nexport function fromArctic(\n factory: (redirectUri: string) => ArcticLikeProvider,\n opts: FromArcticOptions,\n): OAuthProvider {\n const usePkce = opts.pkce !== false;\n const scopes = opts.scopes ?? [];\n\n return {\n id: opts.id,\n label: opts.label,\n authorize({ state, redirectUri, codeVerifier }) {\n const arctic = factory(redirectUri);\n // Arctic's signatures vary: `(state, scopes)` for non-PKCE,\n // `(state, codeVerifier, scopes)` for PKCE. The structural type\n // hides this; do the dispatch here so plugin code stays clean.\n const url = usePkce\n ? (arctic.createAuthorizationURL as unknown as (\n state: string,\n verifier: string,\n scopes: string[],\n ) => URL)(state, codeVerifier, scopes)\n : (arctic.createAuthorizationURL as unknown as (\n state: string,\n scopes: string[],\n ) => URL)(state, scopes);\n return url.toString();\n },\n async exchange({ code, redirectUri, codeVerifier }) {\n const arctic = factory(redirectUri);\n const tokens = usePkce\n ? await (arctic.validateAuthorizationCode as unknown as (\n code: string,\n verifier: string,\n ) => Promise<ArcticLikeTokens>)(code, codeVerifier)\n : await (arctic.validateAuthorizationCode as unknown as (\n code: string,\n ) => Promise<ArcticLikeTokens>)(code);\n return opts.fetchProfile(tokens.accessToken(), tokens);\n },\n };\n}\n","import { webcrypto } from \"node:crypto\";\n\nimport { eq, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\n\nimport type { NpAuthUser } from \"../config/types.js\";\nimport { verifyToken, type NpTokenUse } from \"./token.js\";\nimport { npSessions, npUsers } from \"../db/schema/system.js\";\n\n/**\n * Loose Drizzle handle type — every staff-auth caller passes\n * the same NodePgDatabase, but TS over-narrows when the\n * generated schema record is folded in. Using\n * `Record<string, unknown>` keeps the helper portable across\n * schema generations without surfacing as `any`.\n */\ntype SessionDb = NodePgDatabase<Record<string, unknown>>;\n\nexport async function sha256(input: string): Promise<string> {\n const digest = await webcrypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(input),\n );\n\n return Array.from(new Uint8Array(digest), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Verify a staff JWT and resolve the active user.\n *\n * `expectedUse` defaults to `\"access\"` because every caller of this\n * helper outside the rotation endpoint reads `np-session` (server\n * components, route handlers, the bootstrap layout). Defaulting\n * means a fresh route or RSC page can't accidentally tolerate a\n * refresh JWT in the session cookie just by forgetting the\n * argument. The rotation route explicitly passes `\"refresh\"` for\n * its `np-refresh` read.\n *\n * Tokens missing the `use` claim throw via `verifyToken`; we let\n * that propagate so a `NpAuthError` surfaces as 401 at the API\n * layer.\n */\nexport async function verifyTokenFull(\n token: string,\n secret: string,\n db: SessionDb,\n expectedUse: NpTokenUse = \"access\",\n): Promise<NpAuthUser | null> {\n const payload = await verifyToken(token, secret, expectedUse);\n const [user] = await db\n .select({\n id: npUsers.id,\n email: npUsers.email,\n name: npUsers.name,\n role: npUsers.role,\n tokenVersion: npUsers.tokenVersion,\n })\n .from(npUsers)\n .where(eq(npUsers.id, payload.sub))\n .limit(1);\n\n if (!user || user.tokenVersion !== payload.ver) {\n return null;\n }\n\n return user;\n}\n\nexport async function invalidateAllSessions(\n userId: string,\n db: SessionDb,\n): Promise<void> {\n await db.transaction(async (tx) => {\n await tx\n .update(npUsers)\n .set({\n tokenVersion: sql`${npUsers.tokenVersion} + 1`,\n })\n .where(eq(npUsers.id, userId));\n\n await tx.delete(npSessions).where(eq(npSessions.userId, userId));\n });\n}\n","import { and, desc, eq } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\n\nimport { getDb } from \"../db/runtime.js\";\nimport { recordAuditEvent } from \"../community/audit.js\";\nimport {\n npMemberIdentities,\n npMembers,\n} from \"../db/schema/community.js\";\nimport { npUserOAuthIdentities, npUsers } from \"../db/schema/system.js\";\nimport { NpNotFoundError } from \"../errors.js\";\n\n/**\n * Admin-side helpers for listing and revoking OAuth identity links.\n * Both staff (`np_user_oauth_identities`) and member\n * (`np_member_identities`) tables use the same shape: one row per\n * (account, provider) pair, holding the durable provider subject\n * plus arbitrary metadata. These helpers are the source of truth for\n * `/api/admin/users/[id]/identities` and the member equivalent.\n *\n * Revoking does not invalidate sessions — the user / member can\n * re-link by signing in via OAuth again, which creates a fresh\n * identity row through the resolver. Revocation is intentionally\n * reversible because the durable link is the only thing dropped;\n * the underlying account remains.\n */\n\nexport interface NpUserIdentityRow {\n id: string;\n userId: string;\n provider: string;\n providerUserId: string;\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface NpMemberIdentityRow {\n id: string;\n memberId: string;\n provider: string;\n subject: string;\n email: string | null;\n metadata: Record<string, unknown>;\n createdAt: Date;\n updatedAt: Date;\n}\n\nasync function assertUserExists(userId: string): Promise<void> {\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n const [row] = (await db\n .select({ id: npUsers.id })\n .from(npUsers)\n .where(eq(npUsers.id, userId))\n .limit(1)) as Array<{ id: string }>;\n if (!row) throw new NpNotFoundError(\"user\", userId);\n}\n\nasync function assertMemberExists(memberId: string): Promise<void> {\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n const [row] = (await db\n .select({ id: npMembers.id })\n .from(npMembers)\n .where(eq(npMembers.id, memberId))\n .limit(1)) as Array<{ id: string }>;\n if (!row) throw new NpNotFoundError(\"member\", memberId);\n}\n\nexport async function listUserIdentities(userId: string): Promise<NpUserIdentityRow[]> {\n await assertUserExists(userId);\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n const rows = (await db\n .select()\n .from(npUserOAuthIdentities)\n .where(eq(npUserOAuthIdentities.userId, userId))\n .orderBy(desc(npUserOAuthIdentities.createdAt))) as NpUserIdentityRow[];\n return rows;\n}\n\nexport async function listMemberIdentities(memberId: string): Promise<NpMemberIdentityRow[]> {\n await assertMemberExists(memberId);\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n const rows = (await db\n .select()\n .from(npMemberIdentities)\n .where(eq(npMemberIdentities.memberId, memberId))\n .orderBy(desc(npMemberIdentities.createdAt))) as NpMemberIdentityRow[];\n return rows;\n}\n\nexport interface RevokeIdentityInput {\n /** Staff user id whose identity is being revoked (`actorKind: \"staff\"`). */\n staffUserId: string;\n}\n\nexport async function revokeUserIdentity(\n userId: string,\n identityId: string,\n actor: RevokeIdentityInput,\n): Promise<void> {\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n // Fetch the row first so the audit event captures the provider /\n // subject — once deleted we'd lose the forensic context.\n const [existing] = (await db\n .select()\n .from(npUserOAuthIdentities)\n .where(\n and(\n eq(npUserOAuthIdentities.id, identityId),\n eq(npUserOAuthIdentities.userId, userId),\n ),\n )\n .limit(1)) as NpUserIdentityRow[];\n if (!existing) {\n // Either the identity doesn't exist or it belongs to a different\n // user — both surface as 404 to avoid leaking cross-user\n // existence to staff who don't have the right grants.\n throw new NpNotFoundError(\"identity\", identityId);\n }\n // Use `.returning()` so we can tell whether OUR call did the\n // delete. Two concurrent revokes both pass the select check\n // above; if we record an audit event unconditionally we'd\n // double-log the revocation. The second caller's delete returns\n // zero rows — we skip the audit there.\n const deleted = (await db\n .delete(npUserOAuthIdentities)\n .where(eq(npUserOAuthIdentities.id, identityId))\n .returning({ id: npUserOAuthIdentities.id })) as Array<{ id: string }>;\n if (deleted.length === 0) return;\n await recordAuditEvent({\n actor: { kind: \"staff\", userId: actor.staffUserId },\n action: \"user.identity.revoke\",\n targetType: \"user\",\n targetId: userId,\n payload: {\n identityId,\n provider: existing.provider,\n providerUserId: existing.providerUserId,\n },\n });\n}\n\nexport async function revokeMemberIdentity(\n memberId: string,\n identityId: string,\n actor: RevokeIdentityInput,\n): Promise<void> {\n const db = getDb() as unknown as NodePgDatabase<Record<string, unknown>>;\n const [existing] = (await db\n .select()\n .from(npMemberIdentities)\n .where(\n and(\n eq(npMemberIdentities.id, identityId),\n eq(npMemberIdentities.memberId, memberId),\n ),\n )\n .limit(1)) as NpMemberIdentityRow[];\n if (!existing) throw new NpNotFoundError(\"identity\", identityId);\n const deleted = (await db\n .delete(npMemberIdentities)\n .where(eq(npMemberIdentities.id, identityId))\n .returning({ id: npMemberIdentities.id })) as Array<{ id: string }>;\n if (deleted.length === 0) return;\n await recordAuditEvent({\n actor: { kind: \"staff\", userId: actor.staffUserId },\n action: \"member.identity.revoke\",\n targetType: \"member\",\n targetId: memberId,\n payload: {\n identityId,\n provider: existing.provider,\n subject: existing.subject,\n },\n });\n}\n","import { randomBytes } from \"node:crypto\";\n\nimport { and, eq, gt, isNotNull, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\n\nimport { NpValidationError } from \"../errors.js\";\nimport { npSessions, npUsers } from \"../db/schema/system.js\";\nimport { hashPassword } from \"./password.js\";\nimport { sha256 } from \"./session.js\";\n\nexport type NpPasswordResetPurpose = \"invite\" | \"reset\";\n\nexport interface NpIssuedResetToken {\n /** The raw token — deliver to the user, never persist. */\n token: string;\n /** Matches `np_users.password_reset_expires_at`. */\n expiresAt: Date;\n purpose: NpPasswordResetPurpose;\n}\n\nexport interface NpCreateResetTokenOptions {\n userId: string;\n purpose: NpPasswordResetPurpose;\n ttlMs: number;\n}\n\nconst MIN_PASSWORD_LENGTH = 8;\n\nfunction generateRawToken(): string {\n // 32 bytes → 64 hex chars. Wide enough that brute force is hopeless.\n return randomBytes(32).toString(\"hex\");\n}\n\n/**\n * Issues a new password reset token for `userId`. Stores the **hash** of the\n * token in the `np_users` row alongside the expiry and purpose, then returns\n * the raw token for the caller to deliver (email/link).\n *\n * Any previously-outstanding reset token for the user is replaced.\n */\nexport async function createPasswordResetToken(\n db: NodePgDatabase<Record<string, unknown>>,\n options: NpCreateResetTokenOptions,\n): Promise<NpIssuedResetToken> {\n const token = generateRawToken();\n const tokenHash = await sha256(token);\n const expiresAt = new Date(Date.now() + options.ttlMs);\n\n await db\n .update(npUsers)\n .set({\n passwordResetTokenHash: tokenHash,\n passwordResetExpiresAt: expiresAt,\n passwordResetPurpose: options.purpose,\n updatedAt: new Date(),\n })\n .where(eq(npUsers.id, options.userId));\n\n return { token, expiresAt, purpose: options.purpose };\n}\n\nexport interface NpResetRequestResult {\n userId: string | null;\n name: string | null;\n email: string | null;\n issued: NpIssuedResetToken | null;\n}\n\n/**\n * Handles the \"forgot password\" flow. If the email matches a user, issues a\n * reset token and returns their name so the mailer can personalise the email.\n * If not, silently returns nulls so callers can respond with a constant\n * message and avoid email enumeration.\n */\nexport async function requestPasswordReset(\n db: NodePgDatabase<Record<string, unknown>>,\n email: string,\n ttlMs: number,\n): Promise<NpResetRequestResult> {\n const normalizedEmail = email.trim().toLowerCase();\n const [user] = await db\n .select({\n id: npUsers.id,\n email: npUsers.email,\n name: npUsers.name,\n })\n .from(npUsers)\n .where(eq(npUsers.email, normalizedEmail))\n .limit(1);\n\n if (!user) {\n return { userId: null, name: null, email: null, issued: null };\n }\n\n const issued = await createPasswordResetToken(db, {\n userId: user.id,\n purpose: \"reset\",\n ttlMs,\n });\n\n return { userId: user.id, name: user.name, email: user.email, issued };\n}\n\nexport interface NpConsumeResetTokenOptions {\n token: string;\n newPassword: string;\n}\n\nexport interface NpConsumeResetTokenResult {\n userId: string;\n email: string;\n purpose: NpPasswordResetPurpose;\n}\n\n/**\n * Verifies a password reset token and atomically:\n * - sets the new password hash\n * - bumps `tokenVersion` and deletes all sessions (force logout everywhere)\n * - clears the reset columns on the user row\n *\n * Throws `NpValidationError` when the token is unknown, expired, or the\n * password is too short. Uses a single DB transaction for atomicity.\n */\nexport async function consumePasswordResetToken(\n db: NodePgDatabase<Record<string, unknown>>,\n options: NpConsumeResetTokenOptions,\n): Promise<NpConsumeResetTokenResult> {\n if (!options.token || typeof options.token !== \"string\") {\n throw new NpValidationError(\"Invalid input\", [\n { field: \"token\", message: \"Reset token is required.\" },\n ]);\n }\n\n if (!options.newPassword || options.newPassword.length < MIN_PASSWORD_LENGTH) {\n throw new NpValidationError(\"Invalid input\", [\n {\n field: \"password\",\n message: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`,\n },\n ]);\n }\n\n const tokenHash = await sha256(options.token);\n const now = new Date();\n\n const [user] = await db\n .select({\n id: npUsers.id,\n email: npUsers.email,\n purpose: npUsers.passwordResetPurpose,\n })\n .from(npUsers)\n .where(\n and(\n eq(npUsers.passwordResetTokenHash, tokenHash),\n isNotNull(npUsers.passwordResetExpiresAt),\n gt(npUsers.passwordResetExpiresAt, now),\n ),\n )\n .limit(1);\n\n if (!user) {\n throw new NpValidationError(\"Invalid input\", [\n { field: \"token\", message: \"Reset link is invalid or has expired.\" },\n ]);\n }\n\n const newPasswordHash = await hashPassword(options.newPassword);\n\n // We inline the tokenVersion bump + session delete instead of calling\n // invalidateAllSessions because we need them to land in the same\n // transaction as the password write + reset-column clear. Splitting into\n // two transactions could leave the user with a new password but still-\n // valid old JWTs if the second call failed.\n await db.transaction(async (tx) => {\n await tx\n .update(npUsers)\n .set({\n password: newPasswordHash,\n passwordResetTokenHash: null,\n passwordResetExpiresAt: null,\n passwordResetPurpose: null,\n loginAttempts: 0,\n lockUntil: null,\n tokenVersion: sql`${npUsers.tokenVersion} + 1`,\n updatedAt: new Date(),\n })\n .where(eq(npUsers.id, user.id));\n\n await tx.delete(npSessions).where(eq(npSessions.userId, user.id));\n });\n\n return {\n userId: user.id,\n email: user.email,\n purpose: (user.purpose ?? \"reset\") as NpPasswordResetPurpose,\n };\n}\n","import { randomBytes } from \"node:crypto\";\nimport { jwtVerify, SignJWT, type JWTPayload } from \"jose\";\n\nimport { NpAuthError } from \"../errors.js\";\n\n/**\n * Member-side JWT helpers. Mirrors `signToken` / `verifyToken` for\n * staff but adds a fixed `aud: \"member\"` claim so a forged JWT signed\n * for a staff user can't be replayed against member-only routes (and\n * vice-versa).\n *\n * The signing secret is the same `NP_SECRET`; rotating it invalidates\n * both staff and member sessions, which is the desired behavior.\n *\n * Every token gets a random `jti` so two tokens minted within the\n * same second for the same member produce DIFFERENT JWT strings —\n * needed for refresh-token rotation: without it, the rotated token\n * hash would collide with the prior token hash and revocation by\n * tokenHash would still resolve the rotated row.\n *\n * `use: \"access\" | \"refresh\"` separates the two token purposes. A\n * refresh JWT cannot be presented as the `np-mb-session` cookie and\n * a session JWT cannot drive the rotation endpoint — without this\n * separation a leaked refresh token effectively became a long-lived\n * bearer access token because both kinds were stored as fungible\n * rows in `np_member_sessions` with no row-level kind column.\n */\nexport type NpMemberTokenUse = \"access\" | \"refresh\";\n\nexport interface NpMemberTokenPayload {\n sub: string;\n aud: \"member\";\n ver: number;\n /** Required. `verifyMemberToken` refuses tokens missing this claim\n * so legacy refresh JWTs from before #92 cannot be smuggled into\n * the session cookie path (#91 reopen). */\n use: NpMemberTokenUse;\n /** Optional only for the deploy window; new tokens always carry\n * one. */\n jti?: string;\n iat: number;\n exp: number;\n}\n\nconst textEncoder = new TextEncoder();\nconst MEMBER_AUDIENCE = \"member\";\n\nexport async function signMemberToken(\n member: { id: string; tokenVersion: number },\n secret: string,\n expirationSeconds: number = 7200,\n tokenUse: NpMemberTokenUse = \"access\",\n): Promise<string> {\n const secretKey = textEncoder.encode(secret);\n return new SignJWT({ sub: member.id, ver: member.tokenVersion, use: tokenUse })\n .setProtectedHeader({ alg: \"HS256\" })\n .setAudience(MEMBER_AUDIENCE)\n .setJti(randomBytes(16).toString(\"base64url\"))\n .setIssuedAt()\n .setExpirationTime(Math.floor(Date.now() / 1000) + expirationSeconds)\n .sign(secretKey);\n}\n\n/**\n * Verify a member JWT and return the parsed payload. When\n * `expectedUse` is provided, refuses tokens whose `use` claim doesn't\n * match — that's how `getSessionMember` rejects a refresh token used\n * as a session cookie and how the refresh route rejects an access\n * token as a refresh trigger.\n *\n * Tokens minted before the `use` claim landed have NO `use` payload\n * field. We refuse those outright rather than treating them as\n * `access` — the prior fallback let still-live legacy refresh JWTs\n * (already persisted in `np_member_sessions` per #45's fix) be\n * smuggled into the session cookie and pass the access check (#91\n * reopen). The cost: members logged in before this deploy must log\n * in once. That's bounded by the access-token TTL (default 2h);\n * legacy session rows that don't match a new login age out via\n * `expiresAt` within 7 days regardless.\n */\nexport async function verifyMemberToken(\n token: string,\n secret: string,\n expectedUse?: NpMemberTokenUse,\n): Promise<NpMemberTokenPayload> {\n const secretKey = textEncoder.encode(secret);\n const { payload } = await jwtVerify(token, secretKey, { audience: MEMBER_AUDIENCE });\n // jwtVerify already validated `aud === MEMBER_AUDIENCE`; cast through\n // JWTPayload to lock in the fields we know land on member tokens.\n const typed = payload as JWTPayload & {\n sub: string;\n ver: number;\n iat: number;\n exp: number;\n use?: NpMemberTokenUse;\n };\n if (typed.use !== \"access\" && typed.use !== \"refresh\") {\n throw new NpAuthError(\"Member token missing `use` claim\");\n }\n const use: NpMemberTokenUse = typed.use;\n if (expectedUse && use !== expectedUse) {\n // Throw `NpAuthError` so the response mapper emits 401 instead of\n // a plain 500 — this is an auth failure, not a server failure.\n throw new NpAuthError(\n `Member token use mismatch: expected ${expectedUse}, got ${use}`,\n );\n }\n return { ...typed, aud: MEMBER_AUDIENCE, use };\n}\n","import { and, eq, gt, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\n\nimport { npMemberSessions, npMembers } from \"../db/schema/community.js\";\nimport { sha256 } from \"./session.js\";\n\n/**\n * Member-side session lookups, mirroring the staff helpers in session.ts\n * but for `np_members` / `np_member_sessions`. The sha256 helper is\n * reused (sessions store hashed tokens regardless of the principal kind).\n */\n\nexport interface NpMemberAuthRow {\n id: string;\n email: string;\n handle: string;\n displayName: string;\n status: \"active\" | \"pending\" | \"suspended\" | \"deleted\";\n tokenVersion: number;\n}\n\n/**\n * Resolve a member from a verified JWT payload AND the raw access\n * token. We hash the token and require a live row in\n * `np_member_sessions` — without that row check, deleting a session in\n * `/api/members/logout` had no effect and a stolen token kept working\n * until JWT expiry. (#45)\n *\n * Backward-compat: when no `accessToken` is passed (legacy callers in\n * tests / older routes), we fall back to the previous tokenVersion\n * check only. New paths should always pass the token.\n */\nexport async function getMemberFromTokenPayload(\n db: NodePgDatabase<Record<string, unknown>>,\n payload: { sub: string; ver: number },\n accessToken?: string,\n): Promise<NpMemberAuthRow | null> {\n const [row] = await db\n .select({\n id: npMembers.id,\n email: npMembers.email,\n handle: npMembers.handle,\n displayName: npMembers.displayName,\n status: npMembers.status,\n tokenVersion: npMembers.tokenVersion,\n })\n .from(npMembers)\n .where(eq(npMembers.id, payload.sub))\n .limit(1);\n\n if (!row) return null;\n if (row.tokenVersion !== payload.ver) return null;\n\n if (accessToken) {\n const tokenHash = await sha256(accessToken);\n const now = new Date();\n const [session] = (await db\n .select({ id: npMemberSessions.id })\n .from(npMemberSessions)\n .where(\n and(\n eq(npMemberSessions.memberId, row.id),\n eq(npMemberSessions.tokenHash, tokenHash),\n gt(npMemberSessions.expiresAt, now),\n ),\n )\n .limit(1)) as Array<{ id: string }>;\n if (!session) return null;\n }\n\n return row as NpMemberAuthRow;\n}\n\n/**\n * Bumps a member's tokenVersion + drops every session row, force-logging\n * them out everywhere. Call inside the same transaction as a password\n * change / soft-delete so a leaked old JWT can't outlive the change.\n */\nexport async function invalidateAllMemberSessions(\n db: NodePgDatabase<Record<string, unknown>>,\n memberId: string,\n): Promise<void> {\n await db.transaction(async (tx) => {\n await tx\n .update(npMembers)\n .set({\n tokenVersion: sql`${npMembers.tokenVersion} + 1`,\n updatedAt: new Date(),\n })\n .where(eq(npMembers.id, memberId));\n await tx.delete(npMemberSessions).where(eq(npMemberSessions.memberId, memberId));\n });\n}\n","import { randomBytes } from \"node:crypto\";\n\nimport { and, eq, gt, isNotNull, sql } from \"drizzle-orm\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\n\nimport { NpValidationError } from \"../errors.js\";\nimport { npMemberSessions, npMembers } from \"../db/schema/community.js\";\nimport { hashPassword } from \"./password.js\";\nimport { sha256 } from \"./session.js\";\n\n/**\n * Member-side credential flows: email verification on registration,\n * password reset, password change. Mirrors the staff equivalents in\n * `reset-token.ts` but writes to `np_members` and uses dedicated\n * verify columns (`email_verify_token_hash` / `email_verify_expires_at`)\n * so a verify and a reset can coexist on the same member row.\n */\n\nconst MIN_PASSWORD_LENGTH = 8;\n\nexport interface NpIssuedMemberToken {\n /** The raw token to ship to the user. Never persist. */\n token: string;\n expiresAt: Date;\n}\n\nfunction generateRawToken(): string {\n return randomBytes(32).toString(\"hex\");\n}\n\n// ── Email verification ────────────────────────────────────────────────\n\nexport async function createMemberEmailVerifyToken(\n db: NodePgDatabase<Record<string, unknown>>,\n memberId: string,\n ttlMs: number,\n): Promise<NpIssuedMemberToken> {\n const token = generateRawToken();\n const tokenHash = await sha256(token);\n const expiresAt = new Date(Date.now() + ttlMs);\n\n await db\n .update(npMembers)\n .set({\n emailVerifyTokenHash: tokenHash,\n emailVerifyExpiresAt: expiresAt,\n updatedAt: new Date(),\n })\n .where(eq(npMembers.id, memberId));\n\n return { token, expiresAt };\n}\n\nexport interface NpConsumeMemberEmailVerifyResult {\n memberId: string;\n email: string;\n handle: string;\n displayName: string;\n}\n\nexport async function consumeMemberEmailVerifyToken(\n db: NodePgDatabase<Record<string, unknown>>,\n token: string,\n): Promise<NpConsumeMemberEmailVerifyResult> {\n if (!token || typeof token !== \"string\") {\n throw new NpValidationError(\"Invalid input\", [\n { field: \"token\", message: \"Verification token is required.\" },\n ]);\n }\n const tokenHash = await sha256(token);\n const now = new Date();\n\n const [member] = await db\n .select({\n id: npMembers.id,\n email: npMembers.email,\n handle: npMembers.handle,\n displayName: npMembers.displayName,\n })\n .from(npMembers)\n .where(\n and(\n eq(npMembers.emailVerifyTokenHash, tokenHash),\n isNotNull(npMembers.emailVerifyExpiresAt),\n gt(npMembers.emailVerifyExpiresAt, now),\n ),\n )\n .limit(1);\n\n if (!member) {\n throw new NpValidationError(\"Invalid input\", [\n { field: \"token\", message: \"Verification link is invalid or has expired.\" },\n ]);\n }\n\n await db\n .update(npMembers)\n .set({\n emailVerified: true,\n // Pending → active on first verify so login can succeed afterwards.\n // Suspended/deleted members stay where they are; the mod UI flips\n // those statuses, never the verify endpoint.\n status: sql`case when ${npMembers.status} = 'pending' then 'active' else ${npMembers.status} end`,\n emailVerifyTokenHash: null,\n emailVerifyExpiresAt: null,\n updatedAt: now,\n })\n .where(eq(npMembers.id, member.id));\n\n return {\n memberId: member.id,\n email: member.email,\n handle: member.handle,\n displayName: member.displayName,\n };\n}\n\n// ── Password reset ────────────────────────────────────────────────────\n\nexport interface NpMemberResetRequestResult {\n memberId: string | null;\n displayName: string | null;\n email: string | null;\n issued: NpIssuedMemberToken | null;\n}\n\nexport async function requestMemberPasswordReset(\n db: NodePgDatabase<Record<string, unknown>>,\n email: string,\n ttlMs: number,\n): Promise<NpMemberResetRequestResult> {\n const normalizedEmail = email.trim().toLowerCase();\n const [member] = await db\n .select({\n id: npMembers.id,\n email: npMembers.email,\n displayName: npMembers.displayName,\n status: npMembers.status,\n })\n .from(npMembers)\n .where(eq(npMembers.email, normalizedEmail))\n .limit(1);\n\n if (!member || member.status === \"deleted\") {\n return { memberId: null, displayName: null, email: null, issued: null };\n }\n\n const token = generateRawToken();\n const tokenHash = await sha256(token);\n const expiresAt = new Date(Date.now() + ttlMs);\n\n await db\n .update(npMembers)\n .set({\n passwordResetTokenHash: tokenHash,\n passwordResetExpiresAt: expiresAt,\n updatedAt: new Date(),\n })\n .where(eq(npMembers.id, member.id));\n\n return {\n memberId: member.id,\n displayName: member.displayName,\n email: member.email,\n issued: { token, expiresAt },\n };\n}\n\nexport interface NpConsumeMemberResetResult {\n memberId: string;\n email: string;\n}\n\nexport async function consumeMemberPasswordReset(\n db: NodePgDatabase<Record<string, unknown>>,\n token: string,\n newPassword: string,\n): Promise<NpConsumeMemberResetResult> {\n if (!token || typeof token !== \"string\") {\n throw new NpValidationError(\"Invalid input\", [\n { field: \"token\", message: \"Reset token is required.\" },\n ]);\n }\n if (!newPassword || newPassword.length < MIN_PASSWORD_LENGTH) {\n throw new NpValidationError(\"Invalid input\", [\n {\n field: \"password\",\n message: `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`,\n },\n ]);\n }\n\n const tokenHash = await sha256(token);\n const now = new Date();\n\n const [member] = await db\n .select({ id: npMembers.id, email: npMembers.email })\n .from(npMembers)\n .where(\n and(\n eq(npMembers.passwordResetTokenHash, tokenHash),\n isNotNull(npMembers.passwordResetExpiresAt),\n gt(npMembers.passwordResetExpiresAt, now),\n ),\n )\n .limit(1);\n\n if (!member) {\n throw new NpValidationError(\"Invalid input\", [\n { field: \"token\", message: \"Reset link is invalid or has expired.\" },\n ]);\n }\n\n const newPasswordHash = await hashPassword(newPassword);\n\n await db.transaction(async (tx) => {\n await tx\n .update(npMembers)\n .set({\n password: newPasswordHash,\n passwordResetTokenHash: null,\n passwordResetExpiresAt: null,\n loginAttempts: 0,\n lockUntil: null,\n // Bump tokenVersion in-place so existing JWTs are invalidated. Also\n // mark email as verified — completing a reset on an unverified\n // account is itself proof of email ownership.\n tokenVersion: sql`${npMembers.tokenVersion} + 1`,\n emailVerified: true,\n status: sql`case when ${npMembers.status} = 'pending' then 'active' else ${npMembers.status} end`,\n updatedAt: new Date(),\n })\n .where(eq(npMembers.id, member.id));\n\n await tx.delete(npMemberSessions).where(eq(npMemberSessions.memberId, member.id));\n });\n\n return { memberId: member.id, email: member.email };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,IAAM,gBAAkC,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC;AAExD,IAAM,UAA4B,CAAC,EAAE,KAAK,MAAM,MAAM,SAAS;AAE/D,IAAM,kBAAoC,CAAC,EAAE,KAAK,MACvD,CAAC,CAAC,SAAS,KAAK,SAAS,WAAW,KAAK,SAAS;AAE7C,IAAM,iBAAmC,CAAC,EAAE,MAAM,IAAI,MAC3D,MAAM,SAAS,WAAW,KAAK,cAAc,MAAM;;;ACVrD,SAAS,mBAAmB;AAC5B,SAAS,WAAW,SAAS,UAAU,kBAAmC;AAqC1E,IAAM,cAAc,IAAI,YAAY;AAEpC,eAAsB,UACpB,MACA,QACA,oBAA4B,MAC5B,WAAuB,UACN;AACjB,QAAM,YAAY,YAAY,OAAO,MAAM;AAE3C,SAAO,IAAI,QAAQ;AAAA,IACjB,KAAK,KAAK;AAAA,IACV,MAAM,KAAK;AAAA,IACX,KAAK,KAAK;AAAA,IACV,KAAK;AAAA,EACP,CAAC,EACE,mBAAmB,EAAE,KAAK,QAAQ,CAAC,EACnC,OAAO,YAAY,EAAE,EAAE,SAAS,WAAW,CAAC,EAC5C,YAAY,EACZ,kBAAkB,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI,iBAAiB,EACnE,KAAK,SAAS;AACnB;AAeA,eAAsB,YACpB,OACA,QACA,aACyB;AACzB,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C1CC,IAAG,UAAU,wBAAwB,GAAG;AAAA,IAC1C;AAAA,EACF,EACC,MAAM,CAAC;AAEV,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,kBAAkB,iBAAiB;AAAA,MAC3C,EAAE,OAAO,SAAS,SAAS,wCAAwC;AAAA,IACrE,CAAC;AAAA,EACH;AAEA,QAAM,kBAAkB,MAAM,aAAa,WAAW;AAEtD,QAAM,GAAG,YAAY,OAAO,OAAO;AACjC,UAAM,GACH,OAAO,SAAS,EAChB,IAAI;AAAA,MACH,UAAU;AAAA,MACV,wBAAwB;AAAA,MACxB,wBAAwB;AAAA,MACxB,eAAe;AAAA,MACf,WAAW;AAAA;AAAA;AAAA;AAAA,MAIX,cAAcC,OAAM,UAAU,YAAY;AAAA,MAC1C,eAAe;AAAA,MACf,QAAQA,iBAAgB,UAAU,MAAM,mCAAmC,UAAU,MAAM;AAAA,MAC3F,WAAW,oBAAI,KAAK;AAAA,IACtB,CAAC,EACA,MAAMJ,IAAG,UAAU,IAAI,OAAO,EAAE,CAAC;AAEpC,UAAM,GAAG,OAAO,gBAAgB,EAAE,MAAMA,IAAG,iBAAiB,UAAU,OAAO,EAAE,CAAC;AAAA,EAClF,CAAC;AAED,SAAO,EAAE,UAAU,OAAO,IAAI,OAAO,OAAO,MAAM;AACpD;","names":["eq","eq","and","eq","sql","SYNTHETIC_EMAIL_SUFFIX","syntheticEmail","mergeMetadata","eq","and","sql","randomBytes","randomBytes","eq","sql","eq","sql","and","eq","eq","and","randomBytes","and","eq","sql","randomBytes","eq","and","sql","randomBytes","jwtVerify","SignJWT","textEncoder","SignJWT","randomBytes","jwtVerify","and","eq","gt","sql","eq","and","gt","sql","randomBytes","and","eq","gt","isNotNull","sql","MIN_PASSWORD_LENGTH","generateRawToken","randomBytes","eq","and","isNotNull","gt","sql"]}
@@ -270,23 +270,40 @@ function collectScalarColumns(fields, prefix, collectionTables) {
270
270
  }
271
271
  function buildScalarColumn(field, propertyName, columnName, collectionTables) {
272
272
  const notNull = field.required ? ".notNull()" : "";
273
+ const defaultClause = (() => {
274
+ if (field.defaultValue === void 0 || field.defaultValue === null) return "";
275
+ if (field.type === "text" || field.type === "textarea" || field.type === "email" || field.type === "select" || field.type === "radio") {
276
+ if (typeof field.defaultValue !== "string") return "";
277
+ const literal = field.defaultValue.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
278
+ return `.default("${literal}")`;
279
+ }
280
+ if (field.type === "number") {
281
+ if (typeof field.defaultValue !== "number" || !Number.isFinite(field.defaultValue)) return "";
282
+ return `.default(${field.defaultValue.toString()})`;
283
+ }
284
+ if (field.type === "checkbox") {
285
+ if (typeof field.defaultValue !== "boolean") return "";
286
+ return `.default(${field.defaultValue.toString()})`;
287
+ }
288
+ return "";
289
+ })();
273
290
  switch (field.type) {
274
291
  case "text":
275
292
  case "textarea":
276
293
  case "email":
277
294
  case "select":
278
295
  case "radio":
279
- return { columns: [`${propertyName}: text("${columnName}")${notNull}`], relations: [] };
296
+ return { columns: [`${propertyName}: text("${columnName}")${defaultClause}${notNull}`], relations: [] };
280
297
  case "number": {
281
298
  const builder = field.integerOnly ? "integer" : "doublePrecision";
282
- return { columns: [`${propertyName}: ${builder}("${columnName}")${notNull}`], relations: [] };
299
+ return { columns: [`${propertyName}: ${builder}("${columnName}")${defaultClause}${notNull}`], relations: [] };
283
300
  }
284
301
  case "richText":
285
302
  case "blocks":
286
303
  case "json":
287
304
  return { columns: [`${propertyName}: jsonb("${columnName}")${notNull}`], relations: [] };
288
305
  case "checkbox":
289
- return { columns: [`${propertyName}: boolean("${columnName}")${notNull}`], relations: [] };
306
+ return { columns: [`${propertyName}: boolean("${columnName}")${defaultClause}${notNull}`], relations: [] };
290
307
  case "date":
291
308
  return {
292
309
  columns: [`${propertyName}: timestamp("${columnName}", { withTimezone: true })${notNull}`],
@@ -691,4 +708,4 @@ export {
691
708
  generateTypeScript,
692
709
  generateDocumentsModule
693
710
  };
694
- //# sourceMappingURL=chunk-26RYBFTF.js.map
711
+ //# sourceMappingURL=chunk-AEKO4MXK.js.map