deepen-mfa-passkeys-proof.mjs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. /**
  2. * Deepen proof: TOTP MFA + passkeys on Doltgres + Google auth URL with env secrets.
  3. *
  4. * cd apps/api && bun scripts/deepen-mfa-passkeys-proof.mjs
  5. */
  6. process.env.BRIVEN_AUTH_CORE_ENABLED = 'true';
  7. process.env.BRIVEN_ENV = 'development';
  8. process.env.BRIVEN_ENGINE_DATABASE_URL =
  9. process.env.BRIVEN_ENGINE_DATABASE_URL ??
  10. 'postgres://postgres:devpass@127.0.0.1:5434/briven_engine?sslmode=disable';
  11. process.env.BRIVEN_DATA_PLANE_URL =
  12. process.env.BRIVEN_DATA_PLANE_URL ??
  13. 'postgres://postgres:devpass@127.0.0.1:5434/postgres?sslmode=disable';
  14. process.env.BRIVEN_GOOGLE_CLIENT_ID =
  15. process.env.BRIVEN_GOOGLE_CLIENT_ID ?? 'deepen-google.apps.googleusercontent.com';
  16. process.env.BRIVEN_GOOGLE_CLIENT_SECRET =
  17. process.env.BRIVEN_GOOGLE_CLIENT_SECRET ?? 'deepen-google-secret';
  18. const { ensureBrivenEngineDatabase } = await import(
  19. '../src/services/auth-core/ensure-db.ts'
  20. );
  21. const { initAuthCoreSdk } = await import('../src/services/auth-core/engine.ts');
  22. const { signUpEmailPassword } = await import(
  23. '../src/services/auth-core/emailpassword.ts'
  24. );
  25. const {
  26. createTotpDevice,
  27. generateTotpCode,
  28. verifyAndEnableTotpDevice,
  29. verifyUserTotp,
  30. listTotpDevices,
  31. } = await import('../src/services/auth-core/mfa.ts');
  32. const {
  33. createRegistrationOptions,
  34. finishRegistration,
  35. createAuthenticationOptions,
  36. finishAuthentication,
  37. listPasskeys,
  38. } = await import('../src/services/auth-core/webauthn.ts');
  39. const { getAuthorisationUrl } = await import(
  40. '../src/services/auth-core/thirdparty.ts'
  41. );
  42. const { getEnginePool } = await import('../src/services/auth-core/db.ts');
  43. console.log('=== Phase 5: MFA + passkeys on Doltgres ===');
  44. if (!(await ensureBrivenEngineDatabase()).ok) process.exit(1);
  45. if (!(await initAuthCoreSdk())) process.exit(1);
  46. const projectId = 'p_deepen_local';
  47. const email = `deepen_${Date.now()}@example.com`;
  48. const su = await signUpEmailPassword({
  49. email,
  50. password: 'Deepen!Pass99',
  51. projectId,
  52. });
  53. if (su.status !== 'OK') {
  54. console.error('FAIL signup', su);
  55. process.exit(1);
  56. }
  57. const userId = su.user.id;
  58. // ── TOTP ────────────────────────────────────────────────────────────
  59. const created = await createTotpDevice(userId, 'phone-app', { projectId });
  60. console.log('totp create', {
  61. ok: created.ok,
  62. hasSecret: Boolean(created.secret),
  63. hasOtpauth: Boolean(created.otpauthUrl),
  64. });
  65. if (!created.ok || !created.secret || !created.deviceId) {
  66. console.error('FAIL totp create', created);
  67. process.exit(1);
  68. }
  69. const code = generateTotpCode(created.secret);
  70. const bad = await verifyAndEnableTotpDevice({
  71. userId,
  72. deviceId: created.deviceId,
  73. code: '000000',
  74. });
  75. console.log('totp wrong code', bad.ok);
  76. if (bad.ok) process.exit(1);
  77. const good = await verifyAndEnableTotpDevice({
  78. userId,
  79. deviceId: created.deviceId,
  80. code,
  81. });
  82. console.log('totp enable', good.ok);
  83. if (!good.ok) {
  84. console.error('FAIL totp enable', good);
  85. process.exit(1);
  86. }
  87. const check = await verifyUserTotp(userId, generateTotpCode(created.secret));
  88. console.log('totp login check', check.ok);
  89. if (!check.ok) process.exit(1);
  90. const devices = await listTotpDevices(userId);
  91. console.log('totp devices', devices.devices);
  92. // ── Passkeys ────────────────────────────────────────────────────────
  93. const reg = await createRegistrationOptions({
  94. userId,
  95. userName: email,
  96. projectId,
  97. });
  98. console.log('passkey reg options', reg.status, reg.status === 'OK' ? reg.challengeId : null);
  99. if (reg.status !== 'OK') process.exit(1);
  100. const fin = await finishRegistration({
  101. userId,
  102. challengeId: reg.challengeId,
  103. credentialId: `cred_${Date.now()}`,
  104. publicKey: Buffer.from('fake-public-key-for-local-proof').toString('base64url'),
  105. transports: ['internal'],
  106. });
  107. console.log('passkey register finish', fin.status);
  108. if (fin.status !== 'OK') process.exit(1);
  109. const authOpts = await createAuthenticationOptions({ userId, projectId });
  110. if (authOpts.status !== 'OK') process.exit(1);
  111. const authFin = await finishAuthentication({
  112. challengeId: authOpts.challengeId,
  113. credentialId: `cred_${Date.now()}`.replace(/\d+$/, '') + // wrong id test first
  114. '',
  115. });
  116. // use the real credential id from list
  117. const keys = await listPasskeys(userId);
  118. const realId = keys.credentials[0]?.credentialId;
  119. const authOk = await finishAuthentication({
  120. challengeId: (
  121. await createAuthenticationOptions({ userId, projectId })
  122. ).challengeId,
  123. credentialId: realId,
  124. });
  125. // fix: need challenge from fresh options
  126. const authOpts2 = await createAuthenticationOptions({ userId, projectId });
  127. const authOk2 = await finishAuthentication({
  128. challengeId: authOpts2.challengeId,
  129. credentialId: realId,
  130. });
  131. console.log('passkey authenticate', authOk2.status, authOk2.status === 'OK' ? authOk2.userId : authOk2);
  132. if (authOk2.status !== 'OK' || authOk2.userId !== userId) process.exit(1);
  133. // ── Google URL with real-shaped env secrets ─────────────────────────
  134. const gUrl = await getAuthorisationUrl({
  135. thirdPartyId: 'google',
  136. redirectURI: 'http://localhost:3000/auth/callback/google',
  137. projectId,
  138. });
  139. console.log('google authorisation', {
  140. status: gUrl.status,
  141. source: gUrl.status === 'OK' ? gUrl.credentialsSource : null,
  142. hasGoogleHost:
  143. gUrl.status === 'OK' && gUrl.urlWithQueryParams.includes('accounts.google.com'),
  144. });
  145. if (gUrl.status !== 'OK') process.exit(1);
  146. const pool = getEnginePool();
  147. const totpRows = await pool.query(
  148. `SELECT COUNT(*)::int AS n FROM be_totp_devices WHERE user_id = $1 AND verified = TRUE`,
  149. [userId],
  150. );
  151. const pkRows = await pool.query(
  152. `SELECT COUNT(*)::int AS n FROM be_webauthn_credentials WHERE user_id = $1`,
  153. [userId],
  154. );
  155. console.log('SQL totp verified', totpRows.rows[0]);
  156. console.log('SQL passkeys', pkRows.rows[0]);
  157. console.log('');
  158. console.log('✔ PHASE 5 LOCAL PROOF OK (MFA + passkeys)');
  159. console.log(' storage: Doltgres');
  160. console.log(' TOTP enroll + verify: OK');
  161. console.log(' passkey register + authenticate: OK');
  162. process.exit(0);