@lowdefy/api 7.0.0 → 7.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/dist/context/createAuthorizeOutcome.js +1 -1
  2. package/dist/context/createEvaluateOperators.js +2 -1
  3. package/dist/context/isWebSocketOriginAllowed.js +3 -1
  4. package/dist/context/readMemberships.js +10 -4
  5. package/dist/context/resolveAuthentication.js +95 -21
  6. package/dist/email/renderAuthEmail.js +3 -2
  7. package/dist/index.js +7 -1
  8. package/dist/response/redactErrorResponse.js +8 -4
  9. package/dist/routes/agent/callAgent.js +20 -2
  10. package/dist/routes/agent/redactMessages.js +136 -0
  11. package/dist/routes/auth/createAuthLogger.js +23 -6
  12. package/dist/routes/auth/createMcpAccessTokenClaims.js +8 -6
  13. package/dist/routes/auth/createOnAPIError.js +15 -5
  14. package/dist/routes/auth/createSendEmail.js +15 -5
  15. package/dist/routes/auth/getBetterAuth.js +3 -3
  16. package/dist/routes/auth/getBetterAuthConfig.js +163 -92
  17. package/dist/routes/auth/hooks/buildEngineHooks.js +15 -1
  18. package/dist/routes/auth/hooks/createUserAfterHook.js +17 -2
  19. package/dist/routes/auth/hooks/createUserBeforeHook.js +20 -4
  20. package/dist/routes/auth/mobile/buildBearerPlugin.js +45 -0
  21. package/dist/routes/auth/mobile/buildOneTimeTokenPlugin.js +50 -0
  22. package/dist/routes/auth/mobile/createCodeVerifierCheck.js +57 -0
  23. package/dist/routes/auth/mobile/createKnownDeviceHook.js +76 -0
  24. package/dist/routes/auth/mobile/createMobileAuthPageResponse.js +79 -0
  25. package/dist/routes/auth/mobile/createMobileSessionCreateHook.js +41 -0
  26. package/dist/routes/auth/mobile/createMobileSessionRefreshHook.js +40 -0
  27. package/dist/routes/auth/mobile/createMobileSignInCsrfToken.js +32 -0
  28. package/dist/routes/auth/mobile/createPhoneSession.js +59 -0
  29. package/dist/routes/auth/mobile/escapeHtml.js +26 -0
  30. package/dist/routes/auth/mobile/getCodeHolderIdentifier.js +20 -0
  31. package/dist/routes/auth/mobile/getKnownDeviceIdentifier.js +20 -0
  32. package/dist/routes/auth/mobile/getMobileSessionExpiry.js +18 -0
  33. package/dist/routes/auth/mobile/getMobileSignInReturnUrl.js +31 -0
  34. package/dist/routes/auth/mobile/getOneTimeTokenIdentifiers.js +26 -0
  35. package/dist/routes/auth/mobile/handleMobileSignIn.js +303 -0
  36. package/dist/routes/auth/mobile/handleMobileSignInCallback.js +30 -0
  37. package/dist/routes/auth/mobile/isNativeAuthRequest.js +33 -0
  38. package/dist/routes/auth/mobile/matchesCodeChallenge.js +29 -0
  39. package/dist/routes/auth/mobile/mintOneTimeToken.js +41 -0
  40. package/dist/routes/auth/mobile/readDeviceKeyHash.js +34 -0
  41. package/dist/routes/auth/mobile/readMobileSignInParams.js +90 -0
  42. package/dist/routes/auth/mobile/sha256Base64Url.js +22 -0
  43. package/dist/routes/auth/mobile/storeCodeChallenge.js +29 -0
  44. package/dist/routes/auth/organizations/buildOrganizationPlugin.js +43 -6
  45. package/dist/routes/auth/organizations/createAcceptExistingMemberHook.js +7 -2
  46. package/dist/routes/auth/organizations/createActiveOrgPolicyHook.js +41 -189
  47. package/dist/routes/auth/organizations/createAdmissionGateHook.js +5 -5
  48. package/dist/routes/auth/organizations/createBeforeCreateInvitationHook.js +62 -0
  49. package/dist/routes/auth/organizations/createBeforeUpdateMemberRoleHook.js +45 -0
  50. package/dist/routes/auth/organizations/createSuspendedMemberGate.js +146 -0
  51. package/dist/routes/auth/organizations/createSuspendedOrganizationsFilter.js +44 -0
  52. package/dist/routes/auth/organizations/ensureAuthIndexes.js +11 -10
  53. package/dist/routes/auth/organizations/getOrganizationBinding.js +4 -2
  54. package/dist/routes/auth/organizations/isActiveMember.js +26 -0
  55. package/dist/routes/auth/organizations/isEmailAdmitted.js +12 -5
  56. package/dist/routes/auth/organizations/memberRowsLimit.js +19 -0
  57. package/dist/routes/auth/organizations/mintOrganization.js +258 -0
  58. package/dist/routes/auth/organizations/organizationAccessControl.js +5 -1
  59. package/dist/routes/auth/organizations/provisionOrganization.js +117 -0
  60. package/dist/routes/auth/organizations/readSuspendedOrganizationIds.js +36 -0
  61. package/dist/routes/auth/requestHooks/buildRequestHooks.js +72 -0
  62. package/dist/routes/auth/requestHooks/createEmailCodeHolderGate.js +58 -0
  63. package/dist/routes/auth/requestHooks/createEmailSendLimit.js +116 -0
  64. package/dist/routes/auth/requestHooks/createSignInRefusedRedirectHook.js +75 -0
  65. package/dist/routes/auth/requestHooks/holdEmailCode.js +80 -0
  66. package/dist/routes/auth/requestHooks/reserveSendSlot.js +70 -0
  67. package/dist/routes/auth/runReportingFaults.js +32 -0
  68. package/dist/routes/connections/resolveUnwalledReach.js +14 -16
  69. package/dist/routes/endpoints/callEndpoint.js +6 -3
  70. package/dist/routes/endpoints/control/controlFor.js +9 -6
  71. package/dist/routes/endpoints/control/controlIf.js +8 -3
  72. package/dist/routes/endpoints/control/controlLog.js +3 -1
  73. package/dist/routes/endpoints/control/controlParallelFor.js +9 -6
  74. package/dist/routes/endpoints/control/controlReturn.js +3 -2
  75. package/dist/routes/endpoints/control/controlSetState.js +1 -1
  76. package/dist/routes/endpoints/control/controlSwitch.js +6 -3
  77. package/dist/routes/endpoints/control/controlWhile.js +6 -3
  78. package/dist/routes/endpoints/createLinkAnswer.js +76 -0
  79. package/dist/routes/endpoints/dispatchDetached.js +38 -0
  80. package/dist/routes/endpoints/forwardScheduledEndpoint.js +32 -11
  81. package/dist/routes/endpoints/handleAgentCall.js +1 -1
  82. package/dist/routes/endpoints/handleAuthStep.js +19 -4
  83. package/dist/routes/endpoints/handleEndpointCall.js +6 -4
  84. package/dist/routes/endpoints/handleRequest.js +3 -2
  85. package/dist/routes/endpoints/handleValidateDynamic.js +1 -1
  86. package/dist/routes/endpoints/matchLinkEndpoint.js +30 -0
  87. package/dist/routes/endpoints/runLinkEndpoint.js +148 -0
  88. package/dist/routes/endpoints/runRoutine.js +5 -5
  89. package/dist/routes/endpoints/scheduleBackground.js +13 -11
  90. package/dist/routes/endpoints/test/runTest.js +30 -11
  91. package/dist/routes/mcp/createMcpServer.js +2 -7
  92. package/dist/routes/mcp/runAfterToolCall.js +9 -3
  93. package/dist/routes/mobile/createAppleAppSiteAssociation.js +51 -0
  94. package/dist/routes/mobile/createAssetLinks.js +38 -0
  95. package/dist/routes/mobile/filterMobileMenus.js +31 -0
  96. package/dist/routes/mobile/getMobileAppEvents.js +23 -0
  97. package/dist/routes/mobile/getMobileRootConfig.js +109 -0
  98. package/dist/routes/mobile/getOpenablePageIds.js +21 -0
  99. package/dist/routes/page/dynamic/policy/checkAction.js +67 -2
  100. package/dist/routes/page/dynamic/policy/checkEvents.js +8 -2
  101. package/dist/routes/page/dynamic/policy/checkPolicy.js +86 -6
  102. package/dist/routes/page/dynamic/policy/checkValue.js +97 -6
  103. package/dist/routes/page/dynamic/policy/collectSchemaKinds.js +173 -0
  104. package/dist/routes/page/dynamic/policy/findDataRows.js +94 -0
  105. package/dist/routes/page/dynamic/policy/findEmbeddedUrls.js +24 -12
  106. package/dist/routes/page/dynamic/policy/findHtmlUrls.js +64 -0
  107. package/dist/routes/page/dynamic/policy/overlapsStatePath.js +28 -0
  108. package/dist/routes/page/dynamic/resolveDynamicContent.js +23 -17
  109. package/dist/routes/page/getPageConfig.js +25 -1
  110. package/dist/routes/request/callRequestResolver.js +29 -36
  111. package/dist/routes/request/stampTypedError.js +37 -0
  112. package/dist/routes/request/summarisedError.js +62 -0
  113. package/dist/routes/request/wrapResolverError.js +61 -0
  114. package/dist/routes/websocket/createChannelRegistry.js +13 -15
  115. package/dist/routes/websocket/createWebSocketConnection.js +5 -8
  116. package/dist/test/createMemoryAuth.js +125 -0
  117. package/package.json +20 -22
  118. package/dist/routes/page/dynamic/policy/collectUrlKinds.js +0 -117
  119. package/dist/routes/request/maskCredentialProperties.js +0 -34
@@ -13,13 +13,18 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import send from '@lowdefy/connection-smtp/send';
16
- import { ServiceError } from '@lowdefy/errors';
16
+ import { ConfigError, ServiceError } from '@lowdefy/errors';
17
+ import { type } from '@lowdefy/helpers';
17
18
  import getConnectionConfig from '../connections/getConnectionConfig.js';
18
19
  // auth.email sends every auth email (verification, password reset, magic link)
19
20
  // through an SMTP connection. Resolving the connection per fire lets operators
20
21
  // and the connection's delivery filter apply, so failures - and filtering -
21
- // surface here at send time rather than at construction.
22
- function createSendEmail({ connectionId }) {
22
+ // surface here at send time rather than at construction. A failure names the
23
+ // connection and points at auth.email, never the recipient: the server's reply
24
+ // quotes the address it refused.
25
+ function createSendEmail({ authEmailConfig }) {
26
+ const { connectionId } = authEmailConfig;
27
+ const configKey = authEmailConfig['~k'];
23
28
  return async function sendEmail({ to, subject, html, text, context }) {
24
29
  const connectionConfig = await getConnectionConfig(context, {
25
30
  connectionId
@@ -44,10 +49,15 @@ function createSendEmail({ connectionId }) {
44
49
  if (ServiceError.isServiceError(error)) {
45
50
  throw new ServiceError(undefined, {
46
51
  cause: error,
47
- service: 'SMTP'
52
+ service: 'SMTP',
53
+ configKey
48
54
  });
49
55
  }
50
- throw error;
56
+ const code = type.isNone(error?.code) ? '' : ` (${error.code})`;
57
+ throw new ConfigError(`Auth email could not be sent through connection "${connectionId}"${code}. Check the SMTP connection auth.email.connectionId names.`, {
58
+ cause: error,
59
+ configKey
60
+ });
51
61
  }
52
62
  };
53
63
  }
@@ -69,9 +69,9 @@ function getBetterAuth({ appMeta, authJson, config, createSystemContext, dev, lo
69
69
  });
70
70
  }
71
71
  // Ensure the unique indexes the organization writes rely on at startup. The
72
- // tenant signup mint awaits the same ensure and refuses to mint without
73
- // them. A failure is logged by ensureAuthIndexes and retried after its
74
- // cool-down, so nothing is left to handle here.
72
+ // tenant signup mint and the CreateOrganization step await the same ensure
73
+ // and write nothing without them. A failure is logged by ensureAuthIndexes
74
+ // and retried after its cool-down, so nothing is left to handle here.
75
75
  if (authJson.database) {
76
76
  ensureAuthIndexes({
77
77
  auth: instance,
@@ -24,8 +24,10 @@ import { type } from '@lowdefy/helpers';
24
24
  import { ConfigError, LowdefyInternalError } from '@lowdefy/errors';
25
25
  import getCanonicalUrl from '../../context/getCanonicalUrl.js';
26
26
  import buildAdminPlugin from './buildAdminPlugin.js';
27
+ import buildBearerPlugin from './mobile/buildBearerPlugin.js';
27
28
  import buildCaptchaPlugin from './buildCaptchaPlugin.js';
28
29
  import buildMcpTokenPlugin from './buildMcpTokenPlugin.js';
30
+ import buildOneTimeTokenPlugin from './mobile/buildOneTimeTokenPlugin.js';
29
31
  import buildHooks from './hooks/buildHooks.js';
30
32
  import buildOrganizationPlugin from './organizations/buildOrganizationPlugin.js';
31
33
  import buildOauthPostLogin from './buildOauthPostLogin.js';
@@ -40,6 +42,7 @@ import { CLIENT_ADDRESS_HEADER } from './handleAuthRequest.js';
40
42
  import modelNames from './modelNames.js';
41
43
  import renderAuthEmail from '../../email/renderAuthEmail.js';
42
44
  import resolveCookiePrefix from './resolveCookiePrefix.js';
45
+ import runReportingFaults from './runReportingFaults.js';
43
46
  import sanitizeSessionResponse from './sanitizeSessionResponse.js';
44
47
  // Decision 4: under the "pinned" org policy, disable every mounted
45
48
  // /organization/* HTTP path EXCEPT /organization/accept-invitation (the
@@ -196,7 +199,8 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
196
199
  }
197
200
  if (!type.isString(authConfig.secret)) {
198
201
  throw new ConfigError('Auth "secret" did not resolve to a string. Check the _secret operator reference and that the secret is set.', {
199
- received: type.typeOf(authConfig.secret)
202
+ received: type.typeOf(authConfig.secret),
203
+ configKey: authConfig['~k']
200
204
  });
201
205
  }
202
206
  // Secrets are opaque at build time; strength checks are startup warnings.
@@ -232,7 +236,7 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
232
236
  plugins
233
237
  });
234
238
  const sendEmail = type.isNone(authConfig.email) ? undefined : createSendEmail({
235
- connectionId: authConfig.email.connectionId
239
+ authEmailConfig: authConfig.email
236
240
  });
237
241
  // BetterAuth builds password-reset, magic-link and email-verification links,
238
242
  // and its trusted origins (the CSRF Origin check and the allowed
@@ -363,6 +367,18 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
363
367
  if (!type.isNone(database)) {
364
368
  options.database = database;
365
369
  }
370
+ // Phone sessions are marked so they can be given their own lifetime
371
+ // (mobile.auth.sessionExpiresIn) - see createMobileSessionCreateHook. input:
372
+ // false keeps the mark out of every client-writable body.
373
+ if (type.isNumber(authConfig.mobile?.sessionExpiresIn)) {
374
+ options.session.additionalFields = {
375
+ mobile: {
376
+ type: 'boolean',
377
+ required: false,
378
+ input: false
379
+ }
380
+ };
381
+ }
366
382
  if (authConfig.session.crossSubDomainCookies.enabled === true) {
367
383
  options.advanced.crossSubDomainCookies = {
368
384
  enabled: true,
@@ -381,21 +397,26 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
381
397
  const context = createSystemContext({
382
398
  auth: getAuth()
383
399
  });
384
- const { subject, html, text } = await renderAuthEmail({
385
- flow: 'resetPassword',
386
- vars: {
387
- url
388
- },
389
- authEmailConfig: authConfig.email,
390
- baseURL: baseUrlOrigin,
391
- context
392
- });
393
- await sendEmail({
394
- to: user.email,
395
- subject,
396
- html,
397
- text,
398
- context
400
+ await runReportingFaults({
401
+ context,
402
+ run: async ()=>{
403
+ const { subject, html, text } = await renderAuthEmail({
404
+ flow: 'resetPassword',
405
+ vars: {
406
+ url
407
+ },
408
+ authEmailConfig: authConfig.email,
409
+ baseURL: baseUrlOrigin,
410
+ context
411
+ });
412
+ await sendEmail({
413
+ to: user.email,
414
+ subject,
415
+ html,
416
+ text,
417
+ context
418
+ });
419
+ }
399
420
  });
400
421
  };
401
422
  } else {
@@ -410,21 +431,26 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
410
431
  const context = createSystemContext({
411
432
  auth: getAuth()
412
433
  });
413
- const { subject, html, text } = await renderAuthEmail({
414
- flow: 'verifyEmail',
415
- vars: {
416
- url
417
- },
418
- authEmailConfig: authConfig.email,
419
- baseURL: baseUrlOrigin,
420
- context
421
- });
422
- await sendEmail({
423
- to: user.email,
424
- subject,
425
- html,
426
- text,
427
- context
434
+ await runReportingFaults({
435
+ context,
436
+ run: async ()=>{
437
+ const { subject, html, text } = await renderAuthEmail({
438
+ flow: 'verifyEmail',
439
+ vars: {
440
+ url
441
+ },
442
+ authEmailConfig: authConfig.email,
443
+ baseURL: baseUrlOrigin,
444
+ context
445
+ });
446
+ await sendEmail({
447
+ to: user.email,
448
+ subject,
449
+ html,
450
+ text,
451
+ context
452
+ });
453
+ }
428
454
  });
429
455
  }
430
456
  };
@@ -441,42 +467,47 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
441
467
  const context = createSystemContext({
442
468
  auth: getAuth()
443
469
  });
444
- // One email serves both paths when the code is also configured: mail
445
- // security that pre-fetches links burns the single-use magic-link
446
- // token before the person clicks, and the code they type into the tab
447
- // they started from survives that. createVerificationOTP is the
448
- // plugin's server-only mint - it stores the sign-in code and returns
449
- // it, sending nothing - so the code rides on the link email instead of
450
- // arriving as a second one.
451
- const otpVars = emailOTPEnabled ? {
452
- otp: await getAuth().api.createVerificationOTP({
453
- body: {
454
- email,
455
- type: 'sign-in'
456
- }
457
- }),
458
- expiresIn: authConfig.emailOTP.expiresIn
459
- } : {};
460
- const { subject, html, text } = await renderAuthEmail({
461
- flow: 'magicLink',
462
- vars: {
463
- url: buildMagicLinkUrl({
464
- authConfig,
465
- config,
466
- url
467
- }),
468
- ...otpVars
469
- },
470
- authEmailConfig: authConfig.email,
471
- baseURL: baseUrlOrigin,
472
- context
473
- });
474
- await sendEmail({
475
- to: email,
476
- subject,
477
- html,
478
- text,
479
- context
470
+ await runReportingFaults({
471
+ context,
472
+ run: async ()=>{
473
+ // One email serves both paths when the code is also configured: mail
474
+ // security that pre-fetches links burns the single-use magic-link
475
+ // token before the person clicks, and the code they type into the tab
476
+ // they started from survives that. createVerificationOTP is the
477
+ // plugin's server-only mint - it stores the sign-in code and returns
478
+ // it, sending nothing - so the code rides on the link email instead of
479
+ // arriving as a second one.
480
+ const otpVars = emailOTPEnabled ? {
481
+ otp: await getAuth().api.createVerificationOTP({
482
+ body: {
483
+ email,
484
+ type: 'sign-in'
485
+ }
486
+ }),
487
+ expiresIn: authConfig.emailOTP.expiresIn
488
+ } : {};
489
+ const { subject, html, text } = await renderAuthEmail({
490
+ flow: 'magicLink',
491
+ vars: {
492
+ url: buildMagicLinkUrl({
493
+ authConfig,
494
+ config,
495
+ url
496
+ }),
497
+ ...otpVars
498
+ },
499
+ authEmailConfig: authConfig.email,
500
+ baseURL: baseUrlOrigin,
501
+ context
502
+ });
503
+ await sendEmail({
504
+ to: email,
505
+ subject,
506
+ html,
507
+ text,
508
+ context
509
+ });
510
+ }
480
511
  });
481
512
  }
482
513
  }));
@@ -491,29 +522,48 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
491
522
  expiresIn: authConfig.emailOTP.expiresIn,
492
523
  allowedAttempts: authConfig.emailOTP.allowedAttempts,
493
524
  disableSignUp: authConfig.emailOTP.disableSignUp,
525
+ // With phones, a resend keeps the live code rather than replacing it, so
526
+ // a stranger's send cannot take a known phone's code away
527
+ // (holdEmailCode). Web-only apps keep BetterAuth's default.
528
+ ...type.isNone(authConfig.mobile) ? {} : {
529
+ resendStrategy: 'reuse'
530
+ },
494
531
  sendVerificationOTP: async ({ email, otp, type: otpType })=>{
495
- if (otpType !== 'sign-in') {
496
- throw new ConfigError(`Auth "emailOTP" only wires the sign-in code. A "${otpType}" one-time code was requested, and the Lowdefy engine has no email flow for it.`);
497
- }
498
532
  const context = createSystemContext({
499
533
  auth: getAuth()
500
534
  });
501
- const { subject, html, text } = await renderAuthEmail({
502
- flow: 'emailOTP',
503
- vars: {
504
- otp,
505
- expiresIn: authConfig.emailOTP.expiresIn
506
- },
507
- authEmailConfig: authConfig.email,
508
- baseURL: baseUrlOrigin,
509
- context
510
- });
511
- await sendEmail({
512
- to: email,
513
- subject,
514
- html,
515
- text,
516
- context
535
+ // The type is the caller's: BetterAuth's send-verification-otp endpoint takes it from
536
+ // the request body, so another type is a refused request, not an engine fault. BetterAuth
537
+ // may run this send in the background, where a throw is only its own error line, so the
538
+ // refusal is one warning and no email.
539
+ if (otpType !== 'sign-in') {
540
+ context.logger.warn({
541
+ event: 'auth_email_otp_type_refused',
542
+ otpType
543
+ }, `Auth "emailOTP" only sends the sign-in code. A "${otpType}" one-time code was requested and not sent.`);
544
+ return;
545
+ }
546
+ await runReportingFaults({
547
+ context,
548
+ run: async ()=>{
549
+ const { subject, html, text } = await renderAuthEmail({
550
+ flow: 'emailOTP',
551
+ vars: {
552
+ otp,
553
+ expiresIn: authConfig.emailOTP.expiresIn
554
+ },
555
+ authEmailConfig: authConfig.email,
556
+ baseURL: baseUrlOrigin,
557
+ context
558
+ });
559
+ await sendEmail({
560
+ to: email,
561
+ subject,
562
+ html,
563
+ text,
564
+ context
565
+ });
566
+ }
517
567
  });
518
568
  }
519
569
  }));
@@ -638,6 +688,14 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
638
688
  // it the route authenticates nobody.
639
689
  buildMcpTokenPlugin());
640
690
  }
691
+ // Phones hold ordinary sessions and send them as bearers. Both plugins are on
692
+ // only when the app has a mobile section, and neither changes what a browser
693
+ // sends or receives: the session token header goes to native requests only
694
+ // (buildBearerPlugin), and only the server mints one-time tokens
695
+ // (buildOneTimeTokenPlugin, minted by the mobile sign-in page).
696
+ if (!type.isNone(authConfig.mobile)) {
697
+ options.plugins.push(buildBearerPlugin(), buildOneTimeTokenPlugin());
698
+ }
641
699
  // The admin plugin is framework-controlled - it owns the user row's ban fields
642
700
  // and the endpoints the ban, delete and revoke-sessions steps call. Its whole
643
701
  // HTTP surface is disabled (see ADMIN_PATHS_DISABLED).
@@ -683,17 +741,28 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
683
741
  // build), the same stance as password reset. The accept URL is only
684
742
  // buildable when the origin is pinned AND authPages.acceptInvitation is set;
685
743
  // otherwise the stock InvitationEmail renders branded with no CTA button.
686
- async function sendInvitationEmail({ email, organization, invitation }) {
744
+ async function sendInvitationEmail(args) {
745
+ const context = createSystemContext({
746
+ auth: getAuth()
747
+ });
748
+ await runReportingFaults({
749
+ context,
750
+ run: ()=>renderAndSendInvitation({
751
+ ...args,
752
+ context
753
+ })
754
+ });
755
+ }
756
+ async function renderAndSendInvitation({ email, organization, invitation, context }) {
687
757
  if (type.isNone(authConfig.email)) {
688
- throw new ConfigError('Cannot send the invitation email. Configure "auth.email".');
758
+ throw new ConfigError('Cannot send the invitation email. Configure "auth.email".', {
759
+ configKey: authConfig['~k']
760
+ });
689
761
  }
690
762
  const acceptPath = authConfig.authPages?.acceptInvitation;
691
763
  const canBuildAcceptUrl = type.isString(baseUrlOrigin) && type.isString(acceptPath);
692
764
  const basePath = config.basePath ?? '';
693
765
  const acceptUrl = canBuildAcceptUrl ? `${baseUrlOrigin}${basePath}${acceptPath}?invitationId=${invitation.id}` : undefined;
694
- const context = createSystemContext({
695
- auth: getAuth()
696
- });
697
766
  const { subject, html, text } = await renderAuthEmail({
698
767
  flow: 'invitation',
699
768
  vars: {
@@ -746,6 +815,8 @@ function getBetterAuthConfig({ appMeta, authJson, config = {}, createSystemConte
746
815
  // line, not an error - see createOnAPIError.
747
816
  options.onAPIError = {
748
817
  onError: createOnAPIError({
818
+ createSystemContext,
819
+ getAuth,
749
820
  logger
750
821
  })
751
822
  };
@@ -12,10 +12,13 @@
12
12
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
- */ import createAcceptActiveOrgGuardHook from '../organizations/createAcceptActiveOrgGuardHook.js';
15
+ */ import { type } from '@lowdefy/helpers';
16
+ import createAcceptActiveOrgGuardHook from '../organizations/createAcceptActiveOrgGuardHook.js';
16
17
  import createActiveOrgPolicyHook from '../organizations/createActiveOrgPolicyHook.js';
17
18
  import createAdmissionGateHook from '../organizations/createAdmissionGateHook.js';
18
19
  import createAutoJoinHook from '../organizations/createAutoJoinHook.js';
20
+ import createMobileSessionCreateHook from '../mobile/createMobileSessionCreateHook.js';
21
+ import createMobileSessionRefreshHook from '../mobile/createMobileSessionRefreshHook.js';
19
22
  // Engine-tier hook bindings - hard-coded framework behavior, not entries in
20
23
  // auth.hooks. Keyed by point; each point lists BetterAuth-native callbacks
21
24
  // (before: (data, ctx) => false | { data } | undefined, after: (data, ctx)).
@@ -63,6 +66,17 @@ function buildEngineHooks({ authConfig, getAuth, logger }) {
63
66
  })
64
67
  ];
65
68
  }
69
+ // Phone sessions get their own lifetime. After the organization policy hook,
70
+ // which picks the session's organization and leaves its expiry alone.
71
+ const sessionExpiresIn = authConfig.mobile?.sessionExpiresIn;
72
+ if (type.isNumber(sessionExpiresIn)) {
73
+ engineHooks['session.create.before'].push(createMobileSessionCreateHook({
74
+ sessionExpiresIn
75
+ }));
76
+ engineHooks['session.update.before'].push(createMobileSessionRefreshHook({
77
+ sessionExpiresIn
78
+ }));
79
+ }
66
80
  return engineHooks;
67
81
  }
68
82
  export default buildEngineHooks;
@@ -13,6 +13,7 @@
13
13
  See the License for the specific language governing permissions and
14
14
  limitations under the License.
15
15
  */ import { APIError } from 'better-auth/api';
16
+ import { isExpectedError } from '@lowdefy/errors';
16
17
  // Translates the routine's terminal control for after and synthetic points.
17
18
  // These fire after the write committed, so `:return` data is ignored and a
18
19
  // `:reject`/throw surfaces as an operational error on the underlying
@@ -22,13 +23,27 @@ function createUserAfterHook({ dispatch }) {
22
23
  const result = await dispatch(data, ctx);
23
24
  if (result.status === 'reject') {
24
25
  // Keep the rejecting UserError as the cause so the server-side trace still
25
- // names the routine control that refused the write.
26
+ // names the routine control that refused the write. The code matches the
27
+ // before hook's, so a sign-in refused at either timing lands on the error
28
+ // page the same way.
26
29
  throw new APIError('BAD_REQUEST', {
27
30
  cause: result.error,
28
- message: result.error.message
31
+ message: result.error.message,
32
+ code: 'AUTH_HOOK_REJECTED'
29
33
  });
30
34
  }
31
35
  if (result.status === 'error') {
36
+ // An expected outcome (a :throw, a nested call's refusal) is a 400 like :reject, code
37
+ // included, not a 500. runRoutine has logged it as a warning.
38
+ if (isExpectedError(result.error)) {
39
+ throw new APIError('BAD_REQUEST', {
40
+ cause: result.error,
41
+ message: result.error.message,
42
+ code: 'AUTH_HOOK_REJECTED'
43
+ });
44
+ }
45
+ // A fault runRoutine has already reported (handled), so createOnAPIError does not
46
+ // log it again.
32
47
  throw result.error;
33
48
  }
34
49
  };
@@ -14,7 +14,7 @@
14
14
  limitations under the License.
15
15
  */ import { APIError } from 'better-auth/api';
16
16
  import { type } from '@lowdefy/helpers';
17
- import { ConfigError } from '@lowdefy/errors';
17
+ import { ConfigError, isExpectedError } from '@lowdefy/errors';
18
18
  // Translates the routine's terminal control into BetterAuth's before-hook
19
19
  // contract. The routine `:return`s plain data - the ceremony lives here:
20
20
  // returned data replaces the record ({ data } wrap), a fall-through leaves
@@ -24,8 +24,9 @@ function createUserBeforeHook({ dispatch, hook }) {
24
24
  const result = await dispatch(data, ctx);
25
25
  if (result.status === 'return') {
26
26
  if (!type.isObject(result.response)) {
27
+ // The type, not the value: the value is a user record being written.
27
28
  throw new ConfigError(`Auth hook "${hook.id}" at point "${hook.point}" returned a ${type.typeOf(result.response)}. A before hook ":return" value replaces the record being written, so it should be an object.`, {
28
- received: result.response
29
+ configKey: hook['~k']
29
30
  });
30
31
  }
31
32
  return {
@@ -34,13 +35,28 @@ function createUserBeforeHook({ dispatch, hook }) {
34
35
  }
35
36
  if (result.status === 'reject') {
36
37
  // Keep the rejecting UserError as the cause so the server-side trace still
37
- // names the routine control that refused the write.
38
+ // names the routine control that refused the write. BetterAuth redirects a
39
+ // refused sign-in to the error page only when the APIError carries a code,
40
+ // so without one the browser is shown the JSON.
38
41
  throw new APIError('BAD_REQUEST', {
39
42
  cause: result.error,
40
- message: result.error.message
43
+ message: result.error.message,
44
+ code: 'AUTH_HOOK_REJECTED'
41
45
  });
42
46
  }
43
47
  if (result.status === 'error') {
48
+ // An expected outcome (a :throw, a nested call's refusal) refuses the write as
49
+ // :reject does - a 400 with its code, not a 500. runRoutine has logged it as a
50
+ // warning.
51
+ if (isExpectedError(result.error)) {
52
+ throw new APIError('BAD_REQUEST', {
53
+ cause: result.error,
54
+ message: result.error.message,
55
+ code: 'AUTH_HOOK_REJECTED'
56
+ });
57
+ }
58
+ // A fault runRoutine has already reported (handled), so createOnAPIError does not
59
+ // log it again.
44
60
  throw result.error;
45
61
  }
46
62
  // The routine fell through without a terminal control - record unchanged.
@@ -0,0 +1,45 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { bearer } from 'better-auth/plugins';
16
+ import isNativeAuthRequest from './isNativeAuthRequest.js';
17
+ // BetterAuth's bearer plugin, for phone shells: a request carrying
18
+ // "Authorization: Bearer <signed session token>" is resolved as that session,
19
+ // as a cookie would be. requireSignature refuses an unsigned token, so only
20
+ // the signed value BetterAuth itself issued works; a JWT or another bearer
21
+ // fails the signature check and falls through to the API strategies untouched.
22
+ //
23
+ // The plugin also copies the session token into a set-auth-token response
24
+ // header whenever a response sets the session cookie. A browser's script can
25
+ // read response headers, and Lowdefy keeps the token out of reach of page
26
+ // script (sanitizeSessionResponse), so the header is sent only to native
27
+ // requests: a phone signing in, or exchanging a one-time token.
28
+ function buildBearerPlugin() {
29
+ const plugin = bearer({
30
+ requireSignature: true
31
+ });
32
+ return {
33
+ ...plugin,
34
+ hooks: {
35
+ ...plugin.hooks,
36
+ after: plugin.hooks.after.map((hook)=>({
37
+ ...hook,
38
+ matcher: (ctx)=>isNativeAuthRequest({
39
+ request: ctx.request
40
+ }) && hook.matcher(ctx)
41
+ }))
42
+ }
43
+ };
44
+ }
45
+ export default buildBearerPlugin;
@@ -0,0 +1,50 @@
1
+ /*
2
+ Copyright 2020-2026 Lowdefy, Inc
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */ import { createAuthMiddleware } from 'better-auth/api';
16
+ import { oneTimeToken } from 'better-auth/plugins';
17
+ import createCodeVerifierCheck from './createCodeVerifierCheck.js';
18
+ // The one-time token the mobile sign-in page hands a shell, which the shell
19
+ // exchanges at /one-time-token/verify, with its PKCE code_verifier, for the
20
+ // session created for the phone. It lasts one minute (expiresIn is in
21
+ // minutes) and is consumed by its first verify. Stored hashed, so the database
22
+ // never holds a usable token.
23
+ //
24
+ // Only the server mints one (mintOneTimeToken, once the person confirms on the
25
+ // mobile sign-in page): disableClientRequest closes GET
26
+ // /one-time-token/generate to HTTP callers, so page script running in a
27
+ // signed-in browser can not turn its session into a token it could carry off.
28
+ // The verify route takes the token only with the verifier of the challenge it
29
+ // was minted for (createCodeVerifierCheck).
30
+ function buildOneTimeTokenPlugin() {
31
+ const plugin = oneTimeToken({
32
+ expiresIn: 1,
33
+ disableClientRequest: true,
34
+ storeToken: 'hashed'
35
+ });
36
+ return {
37
+ ...plugin,
38
+ hooks: {
39
+ ...plugin.hooks,
40
+ before: [
41
+ ...plugin.hooks.before ?? [],
42
+ {
43
+ matcher: (ctx)=>ctx.path === '/one-time-token/verify',
44
+ handler: createAuthMiddleware(createCodeVerifierCheck())
45
+ }
46
+ ]
47
+ }
48
+ };
49
+ }
50
+ export default buildOneTimeTokenPlugin;