@teleporthq/teleport-plugin-next-workflows 0.43.46 → 0.43.47

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 (103) hide show
  1. package/__tests__/auth-env-secret-preservation.test.ts +35 -0
  2. package/__tests__/auth-nextauth-url.test.ts +28 -0
  3. package/__tests__/auth-session-cost.test.ts +614 -0
  4. package/__tests__/custom-js-params-env-invariance.test.ts +134 -0
  5. package/__tests__/data-node-not-awaited.test.ts +644 -0
  6. package/__tests__/element-trigger-static-attr-replace.test.ts +99 -0
  7. package/__tests__/element-visible-trigger-scoping.test.ts +296 -0
  8. package/__tests__/payment-charge-user-handler-serialization.test.ts +7 -5
  9. package/__tests__/payment-redirect-and-order-notification.test.ts +6 -4
  10. package/__tests__/raw-sql-param-binding.test.ts +82 -0
  11. package/__tests__/reserved-word-state-binding.test.ts +112 -0
  12. package/__tests__/strip-event-handler-attrs.test.ts +59 -0
  13. package/__tests__/workflow-auth-guard.test.ts +277 -0
  14. package/dist/cjs/api-route-generator.d.ts +3 -3
  15. package/dist/cjs/api-route-generator.d.ts.map +1 -1
  16. package/dist/cjs/api-route-generator.js +136 -11
  17. package/dist/cjs/api-route-generator.js.map +1 -1
  18. package/dist/cjs/auth-generator.d.ts +67 -1
  19. package/dist/cjs/auth-generator.d.ts.map +1 -1
  20. package/dist/cjs/auth-generator.js +458 -20
  21. package/dist/cjs/auth-generator.js.map +1 -1
  22. package/dist/cjs/await-result.d.ts +31 -0
  23. package/dist/cjs/await-result.d.ts.map +1 -0
  24. package/dist/cjs/await-result.js +50 -0
  25. package/dist/cjs/await-result.js.map +1 -0
  26. package/dist/cjs/executor-generator.d.ts.map +1 -1
  27. package/dist/cjs/executor-generator.js +150 -1
  28. package/dist/cjs/executor-generator.js.map +1 -1
  29. package/dist/cjs/nodes/account/account-get-current.d.ts.map +1 -1
  30. package/dist/cjs/nodes/account/account-get-current.js +44 -11
  31. package/dist/cjs/nodes/account/account-get-current.js.map +1 -1
  32. package/dist/cjs/nodes/account/account-login.d.ts.map +1 -1
  33. package/dist/cjs/nodes/account/account-login.js +10 -1
  34. package/dist/cjs/nodes/account/account-login.js.map +1 -1
  35. package/dist/cjs/raw-sql-param-binding.d.ts.map +1 -1
  36. package/dist/cjs/raw-sql-param-binding.js +32 -0
  37. package/dist/cjs/raw-sql-param-binding.js.map +1 -1
  38. package/dist/cjs/segment-splitter.d.ts.map +1 -1
  39. package/dist/cjs/segment-splitter.js +15 -7
  40. package/dist/cjs/segment-splitter.js.map +1 -1
  41. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  42. package/dist/cjs/workflow-auth-generator.d.ts +26 -0
  43. package/dist/cjs/workflow-auth-generator.d.ts.map +1 -0
  44. package/dist/cjs/workflow-auth-generator.js +166 -0
  45. package/dist/cjs/workflow-auth-generator.js.map +1 -0
  46. package/dist/cjs/workflow-component-plugin.d.ts.map +1 -1
  47. package/dist/cjs/workflow-component-plugin.js +107 -16
  48. package/dist/cjs/workflow-component-plugin.js.map +1 -1
  49. package/dist/cjs/workflow-project-plugin.d.ts +2 -1
  50. package/dist/cjs/workflow-project-plugin.d.ts.map +1 -1
  51. package/dist/cjs/workflow-project-plugin.js +170 -20
  52. package/dist/cjs/workflow-project-plugin.js.map +1 -1
  53. package/dist/esm/api-route-generator.d.ts +3 -3
  54. package/dist/esm/api-route-generator.d.ts.map +1 -1
  55. package/dist/esm/api-route-generator.js +136 -11
  56. package/dist/esm/api-route-generator.js.map +1 -1
  57. package/dist/esm/auth-generator.d.ts +67 -1
  58. package/dist/esm/auth-generator.d.ts.map +1 -1
  59. package/dist/esm/auth-generator.js +453 -19
  60. package/dist/esm/auth-generator.js.map +1 -1
  61. package/dist/esm/await-result.d.ts +31 -0
  62. package/dist/esm/await-result.d.ts.map +1 -0
  63. package/dist/esm/await-result.js +45 -0
  64. package/dist/esm/await-result.js.map +1 -0
  65. package/dist/esm/executor-generator.d.ts.map +1 -1
  66. package/dist/esm/executor-generator.js +150 -1
  67. package/dist/esm/executor-generator.js.map +1 -1
  68. package/dist/esm/nodes/account/account-get-current.d.ts.map +1 -1
  69. package/dist/esm/nodes/account/account-get-current.js +44 -11
  70. package/dist/esm/nodes/account/account-get-current.js.map +1 -1
  71. package/dist/esm/nodes/account/account-login.d.ts.map +1 -1
  72. package/dist/esm/nodes/account/account-login.js +10 -1
  73. package/dist/esm/nodes/account/account-login.js.map +1 -1
  74. package/dist/esm/raw-sql-param-binding.d.ts.map +1 -1
  75. package/dist/esm/raw-sql-param-binding.js +32 -0
  76. package/dist/esm/raw-sql-param-binding.js.map +1 -1
  77. package/dist/esm/segment-splitter.d.ts.map +1 -1
  78. package/dist/esm/segment-splitter.js +15 -7
  79. package/dist/esm/segment-splitter.js.map +1 -1
  80. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  81. package/dist/esm/workflow-auth-generator.d.ts +26 -0
  82. package/dist/esm/workflow-auth-generator.d.ts.map +1 -0
  83. package/dist/esm/workflow-auth-generator.js +161 -0
  84. package/dist/esm/workflow-auth-generator.js.map +1 -0
  85. package/dist/esm/workflow-component-plugin.d.ts.map +1 -1
  86. package/dist/esm/workflow-component-plugin.js +108 -17
  87. package/dist/esm/workflow-component-plugin.js.map +1 -1
  88. package/dist/esm/workflow-project-plugin.d.ts +2 -1
  89. package/dist/esm/workflow-project-plugin.d.ts.map +1 -1
  90. package/dist/esm/workflow-project-plugin.js +169 -20
  91. package/dist/esm/workflow-project-plugin.js.map +1 -1
  92. package/package.json +4 -4
  93. package/src/api-route-generator.ts +139 -11
  94. package/src/auth-generator.ts +471 -19
  95. package/src/await-result.ts +52 -0
  96. package/src/executor-generator.ts +150 -1
  97. package/src/nodes/account/account-get-current.ts +44 -9
  98. package/src/nodes/account/account-login.ts +12 -1
  99. package/src/raw-sql-param-binding.ts +33 -0
  100. package/src/segment-splitter.ts +15 -7
  101. package/src/workflow-auth-generator.ts +187 -0
  102. package/src/workflow-component-plugin.ts +129 -20
  103. package/src/workflow-project-plugin.ts +186 -19
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  UIDLAuthentication,
3
+ UIDLAuthTableColumn,
3
4
  UIDLCustomUserProperty,
4
5
  DataSourceType,
5
6
  } from '@teleporthq/teleport-types'
@@ -184,19 +185,123 @@ const airtableBase = new Airtable({
184
185
  }
185
186
  }
186
187
 
187
- const generateSanitizeUserFunction = (): string => {
188
+ /**
189
+ * How long (ms) a JWT may serve the profile fields it already carries before
190
+ * the next session request re-reads the `users` row. See the generated
191
+ * comment in `generateAuthOptionsFile` for the measurements behind it.
192
+ */
193
+ export const USER_REFRESH_INTERVAL_MS = 60000
194
+
195
+ /**
196
+ * Profile fields the session may always carry, even for a UIDL that ships no
197
+ * `users` schema at all.
198
+ *
199
+ * `id`/`name`/`email`/`image`/`role` are the fields the `account-get-current`
200
+ * output contract declares (workflow-schema's node-context-schemas), i.e. the
201
+ * ones every workflow and binding addresses. `roleName`/`roles` are the two
202
+ * alternate spellings `getUserRoleFromToken` in the generated middleware falls
203
+ * back to, so dropping them would silently disable role-based route protection
204
+ * for projects that use them.
205
+ */
206
+ export const SESSION_SAFE_USER_FIELDS: readonly string[] = [
207
+ 'id',
208
+ 'name',
209
+ 'email',
210
+ 'image',
211
+ 'role',
212
+ 'roleName',
213
+ 'roles',
214
+ ]
215
+
216
+ /**
217
+ * Credentials that must never leave the server, whatever the `users` table
218
+ * happens to declare: the OAuth single-table adapter's provider tokens plus the
219
+ * password hash. `findUserByEmail` does `SELECT *`, so without this list they
220
+ * ride the JWT into `session.user` and become readable by any script on the
221
+ * page through /api/auth/session.
222
+ *
223
+ * Denied unconditionally, so a custom user property whose key collides with one
224
+ * of these names cannot re-open the hole. `provider` itself is NOT here — it is
225
+ * just the provider's name ("google"), and `account-social-login` declares it
226
+ * as part of its output contract.
227
+ */
228
+ export const SENSITIVE_USER_FIELDS: readonly string[] = [
229
+ 'password',
230
+ 'password_hash',
231
+ 'passwordHash',
232
+ 'access_token',
233
+ 'refresh_token',
234
+ 'id_token',
235
+ 'expires_at',
236
+ 'session_state',
237
+ 'scope',
238
+ 'token_type',
239
+ 'provider_account_id',
240
+ 'provider_type',
241
+ ]
242
+
243
+ /**
244
+ * Mongo's primary key. NOT a secret — it is excluded because `sanitizeUser`
245
+ * already folds it into `id` (`rawId = user.id != null ? user.id : user._id`),
246
+ * so passing it through as well would put the same value on the session twice
247
+ * under two different names. A shape concern, not a security one, which is why
248
+ * it is kept out of `SENSITIVE_USER_FIELDS`.
249
+ */
250
+ const ID_ALIAS_FIELD = '_id'
251
+
252
+ /**
253
+ * The exact set of `users` columns this project allows into the session.
254
+ *
255
+ * Derived from the DECLARED schema (`auth.tables.users`), which the GUI
256
+ * composes as the canonical auth columns PLUS one column per custom account
257
+ * property — so every property the user configured is included by
258
+ * construction, while a column that exists in the database but not in the UIDL
259
+ * never is. `customUserProperties` is unioned in directly rather than relied on
260
+ * transitively, so the list stays complete for a UIDL that carries the
261
+ * properties without a matching `tables` entry.
262
+ */
263
+ export const buildSessionUserFields = (
264
+ tables: Record<string, UIDLAuthTableColumn[]> | undefined,
265
+ customProps: UIDLCustomUserProperty[]
266
+ ): string[] => {
267
+ const declared = (tables?.users || []).map((column) => column.name)
268
+ const custom = customProps.map((prop) => prop.key)
269
+ const denied = new Set<string>(SENSITIVE_USER_FIELDS)
270
+
271
+ return Array.from(new Set([...SESSION_SAFE_USER_FIELDS, ...declared, ...custom])).filter(
272
+ (field) => Boolean(field) && field !== ID_ALIAS_FIELD && !denied.has(field)
273
+ )
274
+ }
275
+
276
+ const generateSanitizeUserFunction = (
277
+ tables: Record<string, UIDLAuthTableColumn[]> | undefined,
278
+ customProps: UIDLCustomUserProperty[]
279
+ ): string => {
280
+ // ALLOW-list, not a deny-list. `sanitizeUser` feeds the JWT, and the session
281
+ // callback copies the whole token onto `session.user`, so every column the
282
+ // `SELECT *` returned used to be readable by any script on the page. A
283
+ // two-entry deny-list (`password`, `_id`) could never keep up with a table
284
+ // whose shape the project controls; enumerating what the project actually
285
+ // DECLARED is the version that stays correct as columns are added.
286
+ //
188
287
  // Preserve the native type of the id (integer vs UUID-string) — NextAuth
189
288
  // will JSON-serialize the session payload either way. Coercing with
190
289
  // \`String(rawId)\` would silently turn an integer PK into "1" and make
191
290
  // runtime comparisons against a DB-fetched \`user.id\` (still a number
192
291
  // on pages that read the row via \`getStaticProps\`) always false.
193
- return `function sanitizeUser(user) {
292
+ return `// The only \`users\` columns that may reach the browser: this project's declared
293
+ // user schema — canonical profile columns plus every custom account property —
294
+ // minus the credentials (password hash, OAuth access/refresh/id tokens), which
295
+ // stay server-side. Anything else the row carries never reaches the session.
296
+ const SESSION_USER_FIELDS = ${JSON.stringify(buildSessionUserFields(tables, customProps))};
297
+
298
+ function sanitizeUser(user) {
194
299
  if (!user) return null;
195
300
  const safe = {};
196
- const keys = Object.keys(user);
197
- for (let i = 0; i < keys.length; i++) {
198
- if (keys[i] !== 'password' && keys[i] !== '_id') {
199
- safe[keys[i]] = user[keys[i]];
301
+ for (let i = 0; i < SESSION_USER_FIELDS.length; i++) {
302
+ const key = SESSION_USER_FIELDS[i];
303
+ if (user[key] !== undefined) {
304
+ safe[key] = user[key];
200
305
  }
201
306
  }
202
307
  const rawId = user.id != null ? user.id : user._id;
@@ -528,19 +633,46 @@ const generateProvidersSetup = (auth: UIDLAuthentication): string => {
528
633
  email: { label: 'Email', type: 'email' },
529
634
  password: { label: 'Password', type: 'password' }
530
635
  },
636
+ // Every failure used to \`return null\`, which NextAuth reports as the single
637
+ // opaque code \`CredentialsSignin\` — the same answer for a wrong password, an
638
+ // unknown email, and a database the app cannot reach. Project a62338f9 shipped
639
+ // with a DB credential Postgres rejected, and the only thing the user (or the
640
+ // sign-in form) ever saw was "credentialsSignin".
641
+ //
642
+ // NextAuth v4 surfaces a THROWN error's message as the \`error\` value, so each
643
+ // cause now gets its own code. \`describeAuthError\` in
644
+ // utils/auth/auth-error-messages turns them into copy; the raw cause is logged
645
+ // server-side only.
646
+ //
647
+ // Unknown email and wrong password deliberately share one code: telling them
648
+ // apart is a user-enumeration oracle.
531
649
  async authorize(credentials) {
532
650
  if (!credentials || !credentials.email || !credentials.password) {
533
- return null;
651
+ throw new Error('MissingCredentials');
534
652
  }
653
+ const { verifyPassword } = require('./hash-password');
654
+ const { classifyAuthInfrastructureError } = require('./db-health');
655
+ let user;
535
656
  try {
536
- const { verifyPassword } = require('./hash-password');
537
- const user = await findUserByEmail(String(credentials.email));
538
- if (!user) return null;
539
- if (!verifyPassword(String(credentials.password), user.password)) return null;
657
+ user = await findUserByEmail(String(credentials.email));
658
+ } catch (err) {
659
+ const kind = classifyAuthInfrastructureError(err);
660
+ console.error('[auth] Could not reach the user store (' + kind + '):', err && err.message ? err.message : err);
661
+ throw new Error('ServiceUnavailable');
662
+ }
663
+ try {
664
+ if (!user) throw new Error('InvalidCredentials');
665
+ if (!verifyPassword(String(credentials.password), user.password)) {
666
+ throw new Error('InvalidCredentials');
667
+ }
540
668
  return sanitizeUser(user);
541
669
  } catch (err) {
542
- console.error('Authorize error:', err);
543
- return null;
670
+ if (err && err.message === 'InvalidCredentials') throw err;
671
+ // A hashing/serialisation fault is an infrastructure problem, not a
672
+ // wrong password — saying "check your details" would send the user
673
+ // round in circles.
674
+ console.error('[auth] Credential check failed:', err && err.message ? err.message : err);
675
+ throw new Error('ServiceUnavailable');
544
676
  }
545
677
  }
546
678
  }));`)
@@ -590,7 +722,7 @@ export const generateAuthOptionsFile = (
590
722
  const findUserCode = auth.passwordAuthEnabled
591
723
  ? generateFindUserFunction(auth.dataSourceType, customProps)
592
724
  : ''
593
- const sanitizeUserCode = generateSanitizeUserFunction()
725
+ const sanitizeUserCode = generateSanitizeUserFunction(auth.tables, customProps)
594
726
  const signInRoute = auth.authPages.signIn?.route || '/auth/sign-in'
595
727
 
596
728
  return `${providerImports}
@@ -601,6 +733,23 @@ ${findUserCode}
601
733
 
602
734
  ${providersSetup}
603
735
 
736
+ // How long a JWT may serve profile fields before the next /api/auth/session
737
+ // request re-reads the \`users\` row. \`strategy: 'jwt'\` exists precisely so a
738
+ // session costs no database round trip; refreshing on EVERY request threw that
739
+ // away — each one opened a fresh unpooled pg connection (TCP + TLS handshake)
740
+ // for a single indexed SELECT, which measured ~715ms of the ~925ms that
741
+ // /api/auth/session took on a published Vercel deployment, against ~210ms for
742
+ // the same route when the token carried no email. Profile edits still land
743
+ // immediately whenever the app calls \`useSession().update()\` (NextAuth passes
744
+ // \`trigger === 'update'\`, which bypasses the interval); the interval is the
745
+ // backstop for changes made outside this browser, e.g. an admin editing a role.
746
+ const USER_REFRESH_INTERVAL_MS = ${USER_REFRESH_INTERVAL_MS};
747
+
748
+ // Bookkeeping the refresh policy writes onto the token. It must never be copied
749
+ // onto \`session.user\` — it is not a profile field, and leaking it would put an
750
+ // internal timestamp on every binding that enumerates the user object.
751
+ const TOKEN_REFRESH_STAMP = '__userRefreshedAt';
752
+
604
753
  const authOptions = {
605
754
  providers: providers,
606
755
  pages: {
@@ -616,6 +765,13 @@ const authOptions = {
616
765
  for (let i = 0; i < keys.length; i++) {
617
766
  token[keys[i]] = user[keys[i]];
618
767
  }
768
+ // Deliberately NOT stamped. An OAuth \`user\` is the PROVIDER's profile
769
+ // (id/name/email/image) — it carries no \`role\`, which only exists on
770
+ // the \`users\` row. Stamping here would make the first session request
771
+ // after an OAuth sign-in skip the database and leave the visitor
772
+ // role-less for a whole interval, silently failing role-protected
773
+ // routes. Leaving it unstamped means the next session request refreshes
774
+ // exactly as it does today, and the interval applies from there on.
619
775
  return token;
620
776
  }
621
777
  // Subsequent calls (every /api/auth/session): re-read the user from the
@@ -623,6 +779,22 @@ const authOptions = {
623
779
  // session. The JWT is otherwise a snapshot captured at login, which is why
624
780
  // the navbar avatar/name reverted to the old value after a refresh: the
625
781
  // navbar reads /api/auth/session, which is derived from this token.
782
+ //
783
+ // Rate-limited to USER_REFRESH_INTERVAL_MS, because that read is by far
784
+ // the most expensive thing a session request does. \`trigger === 'update'\`
785
+ // (fired by \`useSession().update()\`, which the auth bridge re-publishes
786
+ // as \`window.__teleportNextAuth.refreshSession\`) always refreshes, so a
787
+ // profile save is reflected at once rather than up to an interval later.
788
+ const now = Date.now();
789
+ const lastRefresh = token && typeof token[TOKEN_REFRESH_STAMP] === 'number'
790
+ ? token[TOKEN_REFRESH_STAMP]
791
+ : 0;
792
+ // \`now - lastRefresh < 0\` covers a clock that moved backwards: treat the
793
+ // stamp as stale rather than trusting it until the clock catches up.
794
+ const isFresh = now - lastRefresh >= 0 && now - lastRefresh < USER_REFRESH_INTERVAL_MS;
795
+ if (params.trigger !== 'update' && isFresh) {
796
+ return token;
797
+ }
626
798
  try {
627
799
  if (token && token.email && typeof findUserByEmail === 'function') {
628
800
  const fresh = await findUserByEmail(String(token.email));
@@ -637,6 +809,11 @@ const authOptions = {
637
809
  } catch (e) {
638
810
  // Keep the existing token on any DB hiccup — never sign the user out.
639
811
  }
812
+ // Stamped even when the read threw, so an unreachable database costs one
813
+ // attempt per interval instead of one per request.
814
+ if (token) {
815
+ token[TOKEN_REFRESH_STAMP] = now;
816
+ }
640
817
  return token;
641
818
  },
642
819
  async session(params) {
@@ -644,6 +821,7 @@ const authOptions = {
644
821
  const token = params.token;
645
822
  if (token && session.user) {
646
823
  const skip = { iat: 1, exp: 1, jti: 1, sub: 1 };
824
+ skip[TOKEN_REFRESH_STAMP] = 1;
647
825
  const keys = Object.keys(token);
648
826
  for (let i = 0; i < keys.length; i++) {
649
827
  if (!skip[keys[i]]) {
@@ -670,6 +848,125 @@ ${
670
848
  `
671
849
  }
672
850
 
851
+ /**
852
+ * Why a sign-in failed, in words, plus the one-line codes `authorize` throws.
853
+ *
854
+ * Project a62338f9 could not sign in on the published site OR in the exported
855
+ * project, and the only signal anywhere was NextAuth's generic
856
+ * `CredentialsSignin`. The real cause was that Postgres rejected the DB
857
+ * credential baked into `TELEPORT_DB_CONNECTION_STRING` — a configuration
858
+ * failure the form reported as if the user had mistyped their password.
859
+ *
860
+ * Every code NextAuth can produce is mapped, not just the new ones, so the form
861
+ * never shows a machine token again.
862
+ */
863
+ export const generateAuthErrorMessagesFile = (): string => {
864
+ return `// Codes thrown by the credentials provider's authorize().
865
+ const AUTH_ERROR_MESSAGES = {
866
+ // Ours.
867
+ MissingCredentials: 'Please enter both your email and your password.',
868
+ InvalidCredentials: 'That email and password do not match an account.',
869
+ ServiceUnavailable:
870
+ 'We could not reach the account service. Please try again in a moment — if it keeps happening, the site owner needs to check its database configuration.',
871
+
872
+ // NextAuth's own.
873
+ CredentialsSignin: 'That email and password do not match an account.',
874
+ SessionRequired: 'Please sign in to continue.',
875
+ AccessDenied: 'This account is not allowed to sign in.',
876
+ Verification: 'That sign-in link is no longer valid. Please request a new one.',
877
+ Configuration:
878
+ 'Sign-in is not configured correctly for this site. The site owner needs to check its authentication settings.',
879
+ OAuthSignin: 'We could not start sign-in with that provider. Please try again.',
880
+ OAuthCallback: 'That provider could not complete sign-in. Please try again.',
881
+ OAuthCreateAccount: 'We could not create an account from that provider.',
882
+ OAuthAccountNotLinked:
883
+ 'An account with this email already exists. Sign in the way you did originally, then link this provider from your profile.',
884
+ EmailCreateAccount: 'We could not create an account with that email address.',
885
+ EmailSignin: 'We could not send the sign-in email. Please try again.',
886
+ Callback: 'Sign-in could not be completed. Please try again.',
887
+ Default: 'Something went wrong while signing in. Please try again.',
888
+ };
889
+
890
+ /**
891
+ * Human copy for a NextAuth error code. Anything unrecognised — including a
892
+ * message a future provider invents — falls back to the generic line rather
893
+ * than being shown raw.
894
+ */
895
+ function describeAuthError(code) {
896
+ if (!code) { return ''; }
897
+ var key = String(code);
898
+ if (Object.prototype.hasOwnProperty.call(AUTH_ERROR_MESSAGES, key)) {
899
+ return AUTH_ERROR_MESSAGES[key];
900
+ }
901
+ return AUTH_ERROR_MESSAGES.Default;
902
+ }
903
+
904
+ module.exports = describeAuthError;
905
+ module.exports.describeAuthError = describeAuthError;
906
+ module.exports.AUTH_ERROR_MESSAGES = AUTH_ERROR_MESSAGES;
907
+ `
908
+ }
909
+
910
+ /**
911
+ * Tells a database that is UNREACHABLE from one that REFUSED the credential.
912
+ *
913
+ * Both surface to the user as "we could not reach the account service", but the
914
+ * server log has to name which one: run a62338f9's published site and its
915
+ * exported project both failed with `password authentication failed for user
916
+ * "p_<project>_usr"`, and nothing in the app ever said so.
917
+ */
918
+ export const generateAuthDbHealthFile = (): string => {
919
+ return `var AUTH_DB_ERROR_KINDS = {
920
+ AUTH_FAILED: 'db-auth-failed',
921
+ UNREACHABLE: 'db-unreachable',
922
+ MISCONFIGURED: 'db-misconfigured',
923
+ UNKNOWN: 'db-unknown',
924
+ };
925
+
926
+ /** Postgres SQLSTATEs for "the server said no to these credentials". */
927
+ var AUTH_REJECTION_CODES = ['28P01', '28000', '3D000'];
928
+
929
+ function classifyAuthInfrastructureError(err) {
930
+ if (!err) { return AUTH_DB_ERROR_KINDS.UNKNOWN; }
931
+ var code = err.code ? String(err.code) : '';
932
+ var message = err.message ? String(err.message).toLowerCase() : '';
933
+ if (AUTH_REJECTION_CODES.indexOf(code) !== -1 || message.indexOf('password authentication failed') !== -1) {
934
+ return AUTH_DB_ERROR_KINDS.AUTH_FAILED;
935
+ }
936
+ if (code === 'ENOTFOUND' || code === 'ECONNREFUSED' || code === 'ETIMEDOUT' || code === 'EAI_AGAIN') {
937
+ return AUTH_DB_ERROR_KINDS.UNREACHABLE;
938
+ }
939
+ if (message.indexOf('connection string') !== -1 || message.indexOf('client password must be a string') !== -1) {
940
+ return AUTH_DB_ERROR_KINDS.MISCONFIGURED;
941
+ }
942
+ return AUTH_DB_ERROR_KINDS.UNKNOWN;
943
+ }
944
+
945
+ /**
946
+ * True when a value is still the build-time placeholder the deploy step was
947
+ * supposed to replace. A placeholder is WORSE than an empty value: code that
948
+ * treats "set" as "configured" then trusts a string that means nothing.
949
+ */
950
+ function isUnresolvedSecretPlaceholder(value) {
951
+ return typeof value === 'string' && value.indexOf('teleporthq.secrets.') === 0;
952
+ }
953
+
954
+ /** \`NEXTAUTH_URL\` is only usable when it is an absolute http(s) origin. */
955
+ function isUsableNextAuthUrl(value) {
956
+ if (typeof value !== 'string' || !value) { return false; }
957
+ if (isUnresolvedSecretPlaceholder(value)) { return false; }
958
+ return /^https?:\\/\\//i.test(value);
959
+ }
960
+
961
+ module.exports = {
962
+ AUTH_DB_ERROR_KINDS: AUTH_DB_ERROR_KINDS,
963
+ classifyAuthInfrastructureError: classifyAuthInfrastructureError,
964
+ isUnresolvedSecretPlaceholder: isUnresolvedSecretPlaceholder,
965
+ isUsableNextAuthUrl: isUsableNextAuthUrl,
966
+ };
967
+ `
968
+ }
969
+
673
970
  export const generateHashPasswordFile = (): string => {
674
971
  return `const bcrypt = require('bcryptjs');
675
972
  const crypto = require('crypto');
@@ -707,24 +1004,54 @@ const authOptions = require('../../../utils/auth/auth-options');
707
1004
 
708
1005
  const authHandler = NextAuth(authOptions);
709
1006
 
1007
+ // Inlined rather than required from utils/auth/db-health: this route is the
1008
+ // entry point for ALL authentication, so it must not depend on a sibling module
1009
+ // resolving. Three lines, and the shared copy still backs authorize().
1010
+ function isUsableNextAuthUrl(value) {
1011
+ if (typeof value !== 'string' || !value) { return false; }
1012
+ if (value.indexOf('teleporthq.secrets.') === 0) { return false; }
1013
+ return /^https?:\\/\\//i.test(value);
1014
+ }
1015
+
710
1016
  // NextAuth builds OAuth callback / redirect URLs from process.env.NEXTAUTH_URL.
711
1017
  // At build time the real deployment domain is unknown, so the generated .env
712
1018
  // ships a localhost default. Derive the correct origin from the incoming
713
1019
  // request here so OAuth works on whatever domain the project is published to —
714
1020
  // WITHOUT hardcoding it. An explicitly-configured (non-local) NEXTAUTH_URL is
715
1021
  // always respected; local dev (host = localhost) is left untouched.
1022
+ //
1023
+ // "Explicitly configured" means a REAL absolute http(s) origin. Project
1024
+ // a62338f9 shipped \`NEXTAUTH_URL=teleporthq.secrets.NEXTAUTH_URL\` — an
1025
+ // unresolved placeholder — and the old check saw a non-empty, non-localhost
1026
+ // string and refused to override it. NextAuth then normalised it to
1027
+ // \`https://teleporthq.secrets.nextauth_url\`, advertised that as the sign-in
1028
+ // origin and issued \`__Host-\`/\`__Secure-\` cookies against it. Treating anything
1029
+ // that is not a usable URL as unset lets an already-published site self-heal on
1030
+ // its next request.
716
1031
  module.exports = function nextAuthRoute(req, res) {
717
1032
  try {
718
1033
  const fwdHost = req.headers['x-forwarded-host'] || req.headers.host || '';
719
1034
  const host = Array.isArray(fwdHost) ? fwdHost[0] : fwdHost;
720
1035
  const hostIsLocal = host.indexOf('localhost') === 0 || host.indexOf('127.0.0.1') === 0;
721
1036
  const current = process.env.NEXTAUTH_URL || '';
1037
+ if (current && !isUsableNextAuthUrl(current)) {
1038
+ console.error(
1039
+ '[auth] NEXTAUTH_URL is not a usable origin (' + current + ') — deriving it from the request instead.'
1040
+ );
1041
+ }
722
1042
  const currentIsLocalOrEmpty =
723
- !current || current.indexOf('localhost') !== -1 || current.indexOf('127.0.0.1') !== -1;
1043
+ !isUsableNextAuthUrl(current) ||
1044
+ current.indexOf('localhost') !== -1 ||
1045
+ current.indexOf('127.0.0.1') !== -1;
724
1046
  if (host && !hostIsLocal && currentIsLocalOrEmpty) {
725
1047
  const fwdProto = req.headers['x-forwarded-proto'];
726
1048
  const proto = (Array.isArray(fwdProto) ? fwdProto[0] : fwdProto) || 'https';
727
1049
  process.env.NEXTAUTH_URL = proto + '://' + host;
1050
+ } else if (hostIsLocal && !isUsableNextAuthUrl(current)) {
1051
+ // Local dev with an unusable value would otherwise leave NextAuth
1052
+ // deriving \`https://…\` from the placeholder, so its cookies get the
1053
+ // \`Secure\` prefix and the browser drops them over plain http.
1054
+ process.env.NEXTAUTH_URL = 'http://' + (host || 'localhost:3000');
728
1055
  }
729
1056
  } catch (e) {
730
1057
  /* fall back to the configured NEXTAUTH_URL */
@@ -1273,6 +1600,55 @@ export const config = {
1273
1600
  `
1274
1601
  }
1275
1602
 
1603
+ // A side-effect-only module that MUST evaluate before `next-auth/react` is
1604
+ // imported. It is emitted at utils/auth/nextauth-url-guard.js and imported as the
1605
+ // FIRST import of session-provider.js (the only module that imports
1606
+ // next-auth/react). ES module imports evaluate in source order, so this runs
1607
+ // first.
1608
+ //
1609
+ // Why it exists: next-auth v4's `next-auth/react` builds its `__NEXTAUTH` config
1610
+ // at MODULE LOAD by calling `parseUrl(process.env.NEXTAUTH_URL)` (and the
1611
+ // NEXTAUTH_URL_INTERNAL / VERCEL_URL variants). `parseUrl('')` runs `new URL('')`,
1612
+ // which throws "Invalid URL" — so an EMPTY-STRING env value crashes the import
1613
+ // and, with it, server-side rendering for every page that mounts SessionProvider
1614
+ // (the terminal shows `TypeError: Invalid URL … input: '' … page: '/products'`).
1615
+ // An UNSET var is safe: next-auth defaults it to http://localhost:3000. But a
1616
+ // generated `.env` can ship `NEXTAUTH_URL=` (empty), which Next.js loads into
1617
+ // process.env as "" rather than undefined — the crashing case. Deleting an
1618
+ // empty/whitespace value restores the safe "unset" state; a real configured
1619
+ // value is left untouched. On the browser these are already undefined, so this
1620
+ // is a no-op there.
1621
+ export const generateNextAuthUrlGuardModule = (): string => {
1622
+ return `// GENERATED — see generateNextAuthUrlGuardModule in
1623
+ // @teleporthq/teleport-plugin-next-workflows/src/auth-generator.ts.
1624
+ //
1625
+ // next-auth v4's \`next-auth/react\` reads \`parseUrl(process.env.NEXTAUTH_URL)\` at
1626
+ // MODULE LOAD. \`new URL('')\` throws "Invalid URL", so an EMPTY-STRING value
1627
+ // crashes the import — and server-side rendering for every page that mounts
1628
+ // SessionProvider. An UNSET var is fine (next-auth defaults it to
1629
+ // http://localhost:3000); only an empty string is fatal. A generated \`.env\` may
1630
+ // ship \`NEXTAUTH_URL=\` (empty), which Next.js loads as "", not undefined.
1631
+ //
1632
+ // This is the FIRST import of session-provider.js — the only module that imports
1633
+ // next-auth/react — and ES module imports evaluate in source order, so this runs
1634
+ // before next-auth reads the value. It removes an empty / whitespace value from
1635
+ // the server's process.env so next-auth falls back to its default. On the client
1636
+ // these are already undefined, so it is a no-op.
1637
+ if (typeof process !== 'undefined' && process && process.env) {
1638
+ var __TQ_NEXTAUTH_URL_KEYS = ['NEXTAUTH_URL', 'NEXTAUTH_URL_INTERNAL', 'VERCEL_URL']
1639
+ for (var __i = 0; __i < __TQ_NEXTAUTH_URL_KEYS.length; __i++) {
1640
+ var __k = __TQ_NEXTAUTH_URL_KEYS[__i]
1641
+ var __v = process.env[__k]
1642
+ if (typeof __v === 'string' && __v.trim() === '') {
1643
+ delete process.env[__k]
1644
+ }
1645
+ }
1646
+ }
1647
+
1648
+ export {}
1649
+ `
1650
+ }
1651
+
1276
1652
  export const generateSessionProviderWrapper = (): string => {
1277
1653
  // Authored as pure ESM. _app.js imports this with an ESM default import
1278
1654
  // (`import AuthSessionProvider from '.../session-provider'`). When the file
@@ -1284,8 +1660,15 @@ export const generateSessionProviderWrapper = (): string => {
1284
1660
  // it worked locally). Keeping a single, consistent module system removes the
1285
1661
  // fragile boundary. `SessionProvider` is imported by name (the SWC-safe form
1286
1662
  // even though next-auth/react ships CommonJS).
1287
- return `import React from 'react'
1288
- import { SessionProvider, signIn, signOut } from 'next-auth/react'
1663
+ //
1664
+ // The `nextauth-url-guard` import MUST stay first: it normalizes an empty
1665
+ // NEXTAUTH_URL out of process.env before `next-auth/react` evaluates and calls
1666
+ // `parseUrl('')`, which would otherwise throw "Invalid URL" at module load and
1667
+ // crash SSR. ES imports run in source order, so first = before next-auth/react.
1668
+ return `import './nextauth-url-guard'
1669
+ import React from 'react'
1670
+ import { SessionProvider, signIn, signOut, useSession } from 'next-auth/react'
1671
+ import describeAuthError from './auth-error-messages'
1289
1672
 
1290
1673
  // Bridge for the workflow account handlers (account-login / -logout / -signup /
1291
1674
  // -social-login). Those handlers are emitted via fn.toString() and re-bundled
@@ -1298,14 +1681,83 @@ import { SessionProvider, signIn, signOut } from 'next-auth/react'
1298
1681
  // next-auth/react that is reliably bundled into the app shell) guarantees the
1299
1682
  // handlers can read them off \`window\` without any fragile require/import of
1300
1683
  // their own. The assignment runs at module-eval time, before any click.
1684
+ // \`describeAuthError\` rides the same bridge for the same reason. The sign-in
1685
+ // handler used to surface NextAuth's raw code — project a62338f9's users were
1686
+ // shown the literal string "credentialsSignin" — and it cannot require the
1687
+ // message table itself without reintroducing exactly the fragile require this
1688
+ // bridge exists to avoid. Published from here, where a normal module import is
1689
+ // safe, so there is ONE table rather than a copy inlined per handler.
1690
+ // A stable object, assigned to \`window\` exactly once at module-eval time.
1691
+ // \`SessionSnapshotBridge\` below mutates it in place, so a handler that grabbed
1692
+ // \`window.__teleportNextAuth\` earlier always observes the current session.
1693
+ const teleportNextAuth = {
1694
+ signIn: signIn,
1695
+ signOut: signOut,
1696
+ describeAuthError: describeAuthError,
1697
+ // The session SessionProvider is ALREADY holding in memory, republished so
1698
+ // that workflow handlers can read it synchronously instead of paying an HTTP
1699
+ // round trip to /api/auth/session for something the page has had since it
1700
+ // mounted. On a published deployment that request measured ~925ms — the
1701
+ // \`account-get-current\` node fired one on every click that resolves the
1702
+ // current user (favourites, cart, reviews, ...), strictly serial with the
1703
+ // workflow's own request. \`status\` is next-auth's: 'loading' until the
1704
+ // provider's first fetch settles, then 'authenticated' / 'unauthenticated'.
1705
+ session: null,
1706
+ status: 'loading',
1707
+ getSession: function () {
1708
+ return { status: teleportNextAuth.status, session: teleportNextAuth.session }
1709
+ },
1710
+ // \`useSession().update()\`. Calling it re-reads the user server-side (NextAuth
1711
+ // passes \`trigger: 'update'\` to the jwt callback, which bypasses the refresh
1712
+ // interval) and updates the in-memory session. This is how a profile save
1713
+ // makes its change visible immediately rather than at the next interval.
1714
+ refreshSession: function () {
1715
+ return Promise.resolve(null)
1716
+ },
1717
+ }
1718
+
1301
1719
  if (typeof window !== 'undefined') {
1302
- window.__teleportNextAuth = { signIn: signIn, signOut: signOut }
1720
+ window.__teleportNextAuth = teleportNextAuth
1721
+ }
1722
+
1723
+ // Renders nothing; it exists only to subscribe to the session context and mirror
1724
+ // it onto the bridge. It must live INSIDE SessionProvider for useSession() to
1725
+ // resolve. Mirroring happens in an effect (never during render, which React may
1726
+ // discard or replay) — effects flush on the commit that follows the provider's
1727
+ // fetch, long before any user click.
1728
+ function SessionSnapshotBridge() {
1729
+ const sessionContext = useSession()
1730
+ const status = sessionContext ? sessionContext.status : 'loading'
1731
+ const data = sessionContext ? sessionContext.data : null
1732
+ const update = sessionContext ? sessionContext.update : null
1733
+
1734
+ React.useEffect(
1735
+ function () {
1736
+ teleportNextAuth.status = status
1737
+ teleportNextAuth.session = data || null
1738
+ if (typeof update === 'function') {
1739
+ teleportNextAuth.refreshSession = update
1740
+ }
1741
+ },
1742
+ [status, data, update]
1743
+ )
1744
+
1745
+ return null
1303
1746
  }
1304
1747
 
1305
1748
  export default function AuthSessionProvider(props) {
1306
1749
  return React.createElement(
1307
1750
  SessionProvider,
1308
- { session: props.pageProps && props.pageProps.session ? props.pageProps.session : undefined },
1751
+ {
1752
+ session: props.pageProps && props.pageProps.session ? props.pageProps.session : undefined,
1753
+ // Every regained window focus re-fetched /api/auth/session, and each of
1754
+ // those is a server round trip for a session the page already has. Tabbing
1755
+ // away and back was enough to trigger one. Cross-tab sign-in/sign-out
1756
+ // still propagates: next-auth broadcasts those over its storage channel,
1757
+ // which is independent of this flag.
1758
+ refetchOnWindowFocus: false,
1759
+ },
1760
+ React.createElement(SessionSnapshotBridge, { key: 'teleport-session-bridge' }),
1309
1761
  props.children
1310
1762
  )
1311
1763
  }
@@ -0,0 +1,52 @@
1
+ import { UIDLWorkflowNode } from '@teleporthq/teleport-types'
2
+ import { WorkflowSegment } from './types'
3
+
4
+ /**
5
+ * Every node in the `data` category. Mirrors `DATA_NODE_TYPES` in
6
+ * teleport-gui's `@teleport/workflow-schema` (`constants/data-node-await.ts`) —
7
+ * the two repos cannot import each other, so this list is a PAIRED EDIT.
8
+ */
9
+ export const DATA_NODE_TYPES: ReadonlyArray<string> = [
10
+ 'data-select',
11
+ 'data-count',
12
+ 'data-raw-query',
13
+ 'data-create-item',
14
+ 'data-update-item',
15
+ 'data-delete-item',
16
+ ]
17
+
18
+ /**
19
+ * Config key carrying the author's await choice. Only `false` opts out —
20
+ * `undefined` (never configured) and `true` both mean "await", so every
21
+ * project generated before this option existed keeps its old behaviour.
22
+ */
23
+ export const AWAIT_RESULT_CONFIG_KEY = 'awaitResult'
24
+
25
+ const DATA_NODE_TYPE_SET = new Set<string>(DATA_NODE_TYPES)
26
+
27
+ /**
28
+ * True when this node runs fire-and-forget: the runtime starts the query,
29
+ * publishes `null` under the node's id and moves straight on to the next node.
30
+ */
31
+ export const isFireAndForgetNode = (node: UIDLWorkflowNode | undefined | null): boolean => {
32
+ if (!node || !DATA_NODE_TYPE_SET.has(node.type)) {
33
+ return false
34
+ }
35
+ const config = node.config as Record<string, unknown> | undefined
36
+ return !!config && config[AWAIT_RESULT_CONFIG_KEY] === false
37
+ }
38
+
39
+ /**
40
+ * True when a whole SERVER segment can be dispatched without awaiting the
41
+ * response — i.e. every node it holds is fire-and-forget, so nothing
42
+ * downstream can read anything the segment produces.
43
+ *
44
+ * The API route itself still awaits each query before replying (a serverless
45
+ * function may be frozen the moment it responds, which would drop an in-flight
46
+ * write); what this flag removes is the CLIENT's wait on that round trip, which
47
+ * is where the latency the visitor feels actually comes from.
48
+ */
49
+ export const isFireAndForgetSegment = (segment: WorkflowSegment): boolean =>
50
+ segment.env === 'server' &&
51
+ segment.nodes.length > 0 &&
52
+ segment.nodes.every((node) => isFireAndForgetNode(node))