@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
@@ -398,6 +398,38 @@ function finalizeResolvedConfig(nodeType, config) {
398
398
  config.filters = keptFilters;
399
399
  }
400
400
 
401
+ // BACKSTOP for WRITES: a columnMapping whose resolved value is STILL a whole
402
+ // {{…}} token would insert the literal token text into the column. Run
403
+ // 02783f65 declared state defaults of '{{url.character_id}}' and
404
+ // '{{url.event_id}}' — a token vocabulary that does not exist — and both fed
405
+ // event_responses.event_id / .character_id (both uuid) through a state-get,
406
+ // so every Accept / Decline / Tentative died on Postgres 22P02.
407
+ //
408
+ // Deliberately stricter than the filters rule above: only a WHOLE-string
409
+ // token counts. An embedded '{{' inside longer prose is text a user may have
410
+ // legitimately typed into a form; a value that is nothing but a moustache is
411
+ // unambiguously an unresolved token.
412
+ //
413
+ // Erroring (rather than nulling) matches the write posture above: the column
414
+ // may be a NOT NULL foreign key, so dropping it trades 22P02 for a constraint
415
+ // violation. The error surfaces through the workflow error handler with the
416
+ // column named, instead of a driver-level failure nobody can attribute.
417
+ if (isDataNode && config && Array.isArray(config.columnMappings)) {
418
+ for (var ci = 0; ci < config.columnMappings.length; ci++) {
419
+ var mapping = config.columnMappings[ci];
420
+ if (!mapping || typeof mapping !== 'object') continue;
421
+ var mval = mapping.value;
422
+ if (typeof mval === 'string' && /^\\s*\\{\\{[\\s\\S]*\\}\\}\\s*$/.test(mval)) {
423
+ if (!error) {
424
+ error =
425
+ 'Column "' + (mapping.column || 'unknown') +
426
+ '" would be written the unresolved template ' + mval.trim() +
427
+ ' as literal text. That token resolves nowhere at runtime.';
428
+ }
429
+ }
430
+ }
431
+ }
432
+
401
433
  return error;
402
434
  }
403
435
 
@@ -564,6 +596,8 @@ function evaluateSingleComparison(config, context) {
564
596
  async function executeWorkflow(workflowConfig, triggerContext, nodeHandlers, options) {
565
597
  options = options || {};
566
598
  const context = {};
599
+ // See buildContext — one shared fire-and-forget queue for the whole run.
600
+ context.__pendingNodePromises = [];
567
601
  const executionId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);
568
602
  context[workflowConfig.triggerNodeId] = triggerContext;
569
603
  if (triggerContext && triggerContext.__stateValues) {
@@ -659,6 +693,72 @@ function topoSortNodes(nodes, edges) {
659
693
  return sorted;
660
694
  }
661
695
 
696
+ // Data-category node types. Mirrors DATA_NODE_TYPES in await-result.ts (and in
697
+ // teleport-gui's workflow-schema) — PAIRED EDIT.
698
+ var __DATA_NODE_TYPES = {
699
+ 'data-select': true,
700
+ 'data-count': true,
701
+ 'data-raw-query': true,
702
+ 'data-create-item': true,
703
+ 'data-update-item': true,
704
+ 'data-delete-item': true
705
+ };
706
+
707
+ // A data node the author opted out of awaiting. Only an explicit \`false\` opts
708
+ // out, so a config written before the option existed keeps awaiting.
709
+ function isFireAndForgetNode(node) {
710
+ if (!node || !__DATA_NODE_TYPES[node.type]) return false;
711
+ return !!node.config && node.config.awaitResult === false;
712
+ }
713
+
714
+ // Starts a fire-and-forget node and returns a promise that ALWAYS resolves.
715
+ // The workflow has already moved on, so a failure here can neither abort it nor
716
+ // reach the error handler — it is reported to the console and swallowed, which
717
+ // is exactly what "do not await" means.
718
+ function startFireAndForgetNode(node, handler, resolvedConfig, context) {
719
+ var label = (node && (node.label || node.type)) || 'node';
720
+ var started;
721
+ try {
722
+ started = Promise.resolve(handler(resolvedConfig, context));
723
+ } catch (syncErr) {
724
+ started = Promise.reject(syncErr);
725
+ }
726
+ return started.then(function(result) {
727
+ if (isFatalNodeResult(result)) {
728
+ console.error('[workflow] "' + label + '" failed (not awaited): ' + fatalNodeResultMessage(result));
729
+ }
730
+ }).catch(function(err) {
731
+ console.error('[workflow] "' + label + '" threw (not awaited):', err);
732
+ });
733
+ }
734
+
735
+ // Keeps every in-flight fire-and-forget promise on the execution context so a
736
+ // server route can settle them BEFORE it responds. A serverless function may be
737
+ // frozen the moment its response is sent, which would silently drop an
738
+ // in-flight write; the visitor still never waits for it, because the client
739
+ // dispatches such a segment without awaiting the round trip.
740
+ function registerPendingNodePromise(context, promise) {
741
+ if (!context || !promise) return promise;
742
+ if (!context.__pendingNodePromises) context.__pendingNodePromises = [];
743
+ context.__pendingNodePromises.push(promise);
744
+ return promise;
745
+ }
746
+
747
+ async function settlePendingNodePromises(context) {
748
+ if (!context) return;
749
+ // Bounded drain: a settled promise can only enqueue more work through a
750
+ // nested custom node, so a handful of passes is always enough and a runaway
751
+ // producer can never hang the response.
752
+ for (var pass = 0; pass < 5; pass++) {
753
+ var pending = context.__pendingNodePromises;
754
+ if (!pending || pending.length === 0) return;
755
+ context.__pendingNodePromises = [];
756
+ // Every entry swallows its own rejection (see startFireAndForgetNode), so
757
+ // this can never reject.
758
+ await Promise.all(pending);
759
+ }
760
+ }
761
+
662
762
  // A node result signals failure either through the legacy string contract
663
763
  // ({ error: '...' } / { success: false }) or through the AI-node contract
664
764
  // ({ error: true, message, code } — provider/auth failures). Both must halt
@@ -809,6 +909,20 @@ async function executeNodes(nodes, edges, context, nodeHandlers, workflowConfig,
809
909
  continue;
810
910
  }
811
911
 
912
+ if (isFireAndForgetNode(node)) {
913
+ registerPendingNodePromise(
914
+ context,
915
+ startFireAndForgetNode(node, handler, resolvedConfig, context)
916
+ );
917
+ // The workflow never waits for this query, so it has no value to
918
+ // publish: downstream references resolve to null rather than to a
919
+ // half-finished or stale result.
920
+ context[node.id] = null;
921
+ executed[node.id] = true;
922
+ context.__previousNodeResult = null;
923
+ continue;
924
+ }
925
+
812
926
  let result = await handler(resolvedConfig, context);
813
927
 
814
928
  if (result && result.__customNode && result.customNodeId && workflowConfig.customNodes) {
@@ -1116,7 +1230,11 @@ module.exports = {
1116
1230
  markAllBranchNodes,
1117
1231
  isStreamingAINode,
1118
1232
  isFatalNodeResult,
1119
- fatalNodeResultMessage
1233
+ fatalNodeResultMessage,
1234
+ isFireAndForgetNode,
1235
+ startFireAndForgetNode,
1236
+ registerPendingNodePromise,
1237
+ settlePendingNodePromises
1120
1238
  };
1121
1239
  `
1122
1240
  }
@@ -1165,6 +1283,10 @@ function pruneContext(context) {
1165
1283
  const val = context[key];
1166
1284
  if (val === undefined || val === null) continue;
1167
1285
  if (typeof val === 'function') continue;
1286
+ // In-flight fire-and-forget promises are local to whichever runtime started
1287
+ // them; serializing them would ship a list of empty objects and let a
1288
+ // server response overwrite the client's live list.
1289
+ if (key === '__pendingNodePromises') continue;
1168
1290
  try {
1169
1291
  // Replace DOM nodes with serializable snapshots as we stringify, then
1170
1292
  // re-parse so the request body itself (JSON.stringify(prunedContext) in
@@ -1267,6 +1389,9 @@ async function callServerSegment(segmentUrl, context) {
1267
1389
 
1268
1390
  function buildContext(workflowConfig, triggerContext) {
1269
1391
  const context = {};
1392
+ // Created eagerly so every nested custom node (which shallow-copies this
1393
+ // object) pushes into the SAME fire-and-forget queue instead of its own.
1394
+ context.__pendingNodePromises = [];
1270
1395
  context[workflowConfig.triggerNodeId] = triggerContext;
1271
1396
  if (triggerContext) {
1272
1397
  if (triggerContext.__stateValues) context.__stateValues = triggerContext.__stateValues;
@@ -1472,6 +1597,30 @@ async function executeWorkflowWithSegments(workflowConfig, triggerContext, clien
1472
1597
  var allSkipped = seg.nodes.every(function(n) { return context.__skippedNodes[n.id]; });
1473
1598
  if (allSkipped) continue;
1474
1599
  }
1600
+ // Every node in this segment is fire-and-forget, so nothing downstream
1601
+ // can read anything it produces — dispatch it and keep going instead of
1602
+ // making the visitor wait for the database round trip. The route itself
1603
+ // still awaits each query before it responds; we simply ignore the
1604
+ // response. Errors are logged, never routed to the error handler:
1605
+ // the workflow already moved past this point.
1606
+ if (seg.fireAndForget) {
1607
+ const ffUrl = serverSegmentUrls[seg.id];
1608
+ if (!ffUrl) throw new Error('No server URL for segment: ' + seg.id);
1609
+ utils.registerPendingNodePromise(
1610
+ context,
1611
+ callServerSegment(ffUrl, context).catch(function(err) {
1612
+ console.error('[workflow] Segment "' + seg.id + '" failed (not awaited):', err);
1613
+ })
1614
+ );
1615
+ for (var ffi = 0; ffi < seg.nodes.length; ffi++) {
1616
+ // A node on a branch that was not taken must stay absent from the
1617
+ // context, exactly as it would if the segment had been awaited.
1618
+ if (context.__skippedNodes && context.__skippedNodes[seg.nodes[ffi].id]) continue;
1619
+ context[seg.nodes[ffi].id] = null;
1620
+ }
1621
+ context.__previousNodeResult = null;
1622
+ continue;
1623
+ }
1475
1624
  const hasStreaming = seg.hasStreamingAI || seg.nodes.some(function(n) {
1476
1625
  return streamingInfo[n.id];
1477
1626
  });
@@ -21,21 +21,56 @@ async function account_get_current(_config: unknown, context: Record<string, unk
21
21
  o.user = user || null
22
22
  return o
23
23
  }
24
+ // Mirror of the last known user, read when the session endpoint is
25
+ // unreachable so an offline click still knows who is signed in.
26
+ const __cache = (user: any) => {
27
+ if (typeof window === 'undefined') {
28
+ return
29
+ }
30
+ try {
31
+ if (user) {
32
+ window.localStorage.setItem('teleport_auth_user', JSON.stringify(user))
33
+ } else {
34
+ window.localStorage.removeItem('teleport_auth_user')
35
+ }
36
+ } catch (_e) {}
37
+ }
38
+
39
+ // `_app` renders NextAuth's SessionProvider on every page, so the browser has
40
+ // already fetched and is holding the session in memory; session-provider.js
41
+ // republishes it on `window.__teleportNextAuth`. Re-fetching it over HTTP cost
42
+ // a full round trip (~925ms on a published deployment, because the jwt
43
+ // callback re-reads the `users` row) BEFORE the workflow's own request could
44
+ // start — for data the page had since it mounted.
45
+ //
46
+ // Only 'authenticated' short-circuits. 'loading' means the provider's first
47
+ // fetch has not settled; 'unauthenticated' is also what next-auth reports when
48
+ // that fetch FAILED, and treating a transient error as "signed out" would send
49
+ // a signed-in visitor down the guest branch. Both fall through to the fetch —
50
+ // which for a guest is the cheap case anyway, since the jwt callback returns
51
+ // before touching the database when there is no token.
52
+ if (typeof window !== 'undefined') {
53
+ try {
54
+ const bridge = (window as any).__teleportNextAuth
55
+ const snapshot =
56
+ bridge && typeof bridge.getSession === 'function' ? bridge.getSession() : null
57
+ if (snapshot && snapshot.status === 'authenticated') {
58
+ const liveUser = snapshot.session && snapshot.session.user ? snapshot.session.user : null
59
+ if (liveUser) {
60
+ __cache(liveUser)
61
+ return __out(liveUser)
62
+ }
63
+ }
64
+ } catch (_e) {}
65
+ }
66
+
24
67
  try {
25
68
  const response = await fetch(baseUrl + '/api/auth/session')
26
69
  if (response.ok) {
27
70
  const session = await response.json()
28
71
  const user = session && session.user ? session.user : null
29
72
 
30
- if (typeof window !== 'undefined') {
31
- try {
32
- if (user) {
33
- window.localStorage.setItem('teleport_auth_user', JSON.stringify(user))
34
- } else {
35
- window.localStorage.removeItem('teleport_auth_user')
36
- }
37
- } catch (_e) {}
38
- }
73
+ __cache(user)
39
74
 
40
75
  return __out(user)
41
76
  }
@@ -33,7 +33,18 @@ async function account_login(config: any, context: Record<string, unknown>) {
33
33
  })
34
34
 
35
35
  if (result && result.error) {
36
- throw new Error(result.error)
36
+ // NextAuth hands back a CODE (`CredentialsSignin`, `Configuration`, or one
37
+ // of the codes the credentials provider throws). It used to be rethrown
38
+ // verbatim, so the sign-in form showed users the literal string
39
+ // "credentialsSignin" with no idea whether they had mistyped a password or
40
+ // the site could not reach its database. `describeAuthError` rides the same
41
+ // window bridge as `signIn` — see session-provider — so this handler needs
42
+ // no require of its own; the raw code is the fallback if an older bridge is
43
+ // on the page.
44
+ const describe = nextAuthReact.describeAuthError
45
+ throw new Error(
46
+ typeof describe === 'function' ? describe(result.error) || result.error : result.error
47
+ )
37
48
  }
38
49
 
39
50
  let user = null
@@ -50,6 +50,14 @@ const SENTINEL_EXPAND_RE = new RegExp(
50
50
  )
51
51
 
52
52
  const VALUE_OPERATOR_CHARS = '=<>(,+-*/%|~'
53
+ // CASE/WHEN/THEN/ELSE are value positions: the sanctioned sort idiom the
54
+ // raw-sql node spec itself prescribes ("ORDER BY CASE {{ sortKey }} WHEN
55
+ // 'name' THEN name …" / "CASE WHEN {{ sortKey }} = 'x' THEN col") puts the
56
+ // bound token right after them. Round-7 run 3d75cfa9 refused three {{sortKey}}
57
+ // tokens in exactly that shape — the model had followed the spec verbatim and
58
+ // every sortable list's workflow was dropped. A bound parameter in these
59
+ // positions is valid SQL; a model that MEANT a dynamic identifier there gets a
60
+ // harmless value comparison, never SQL text.
53
61
  const VALUE_KEYWORDS: ReadonlySet<string> = new Set([
54
62
  'LIKE',
55
63
  'ILIKE',
@@ -60,8 +68,30 @@ const VALUE_KEYWORDS: ReadonlySet<string> = new Set([
60
68
  'AND',
61
69
  'OR',
62
70
  'BETWEEN',
71
+ // A token directly after CASE/WHEN/THEN/ELSE is a VALUE being compared or
72
+ // produced — never an identifier — so it binds as `$N` like any other value.
73
+ //
74
+ // Run d27cd823: the Dashboard's date-range filter wrote
75
+ // CASE WHEN {{ dateRange }} = 'today' THEN … WHEN {{ dateRange }} = '7d' THEN … END
76
+ // Without `WHEN` here, `isValueContext` said "not a value", the token stayed
77
+ // literal, and the whole workflow was REJECTED as un-parameterisable — three
78
+ // Dashboard filter workflows were dropped and the quick date filters shipped
79
+ // dead. Binding them is also the SAFER outcome: a bound parameter can never be
80
+ // interpreted as an identifier, which is exactly what the guard protects against.
81
+ 'CASE',
82
+ 'WHEN',
83
+ 'THEN',
84
+ 'ELSE',
63
85
  ])
64
86
 
87
+ // `FROM` normally introduces a table name, so it is deliberately absent from
88
+ // VALUE_KEYWORDS — but inside `TRIM([BOTH|LEADING|TRAILING] [chars] FROM expr)`
89
+ // the word after FROM is the VALUE being trimmed, not an identifier. The alerts
90
+ // filter fixture wrote `TRIM(BOTH FROM {{statusFilterSegment}})` and the whole
91
+ // project generation was refused. Matching the trim-function prefix keeps
92
+ // `SELECT * FROM {{table}}` rejected while binding the trim operand.
93
+ const TRIM_FROM_VALUE_RE = /\bTRIM\s*\(\s*(?:(?:BOTH|LEADING|TRAILING)\b[^()]*?)?FROM$/i
94
+
65
95
  function isValueContext(prefix: string): boolean {
66
96
  const trimmed = prefix.replace(/\s+$/, '')
67
97
  if (trimmed.length === 0) {
@@ -75,6 +105,9 @@ function isValueContext(prefix: string): boolean {
75
105
  if (wordMatch && VALUE_KEYWORDS.has(wordMatch[1].toUpperCase())) {
76
106
  return true
77
107
  }
108
+ if (wordMatch && wordMatch[1].toUpperCase() === 'FROM' && TRIM_FROM_VALUE_RE.test(trimmed)) {
109
+ return true
110
+ }
78
111
  return false
79
112
  }
80
113
 
@@ -2,6 +2,7 @@ import { UIDLWorkflow, UIDLWorkflowNode, UIDLWorkflowEdge } from '@teleporthq/te
2
2
  import { WorkflowSegment, WorkflowExecutionEnv } from './types'
3
3
  import { getLoopBodyNodes, getNodeById, getTopologicalOrder } from './graph-utils'
4
4
  import { nodeRegistry } from './nodes'
5
+ import { AWAIT_RESULT_CONFIG_KEY } from './await-result'
5
6
 
6
7
  const CLIENT_ONLY_NODE_TYPES = new Set([
7
8
  'account-login',
@@ -289,14 +290,21 @@ const enforceLoopBodyIntegrity = (
289
290
  export const resolveNodeExecutionEnv = (node: UIDLWorkflowNode): WorkflowExecutionEnv =>
290
291
  resolveExecutionEnv(node, null)
291
292
 
292
- // The ONLY field of a server node's config the CLIENT executor ever reads is
293
+ // The ONLY fields of a server node's config the CLIENT executor ever reads are
293
294
  // the AI-streaming flag (findStreamingAINodes / callStreamingServerSegment in
294
- // executor-generator). Everything else — the raw SQL query, filters, table
295
- // name, bound params, column mappings, data source id, … — is consumed
296
- // exclusively inside the server API route (see api-route-generator's
297
- // SEGMENT_CONFIG, which keeps the full config server-side). None of it may
298
- // reach the browser bundle.
299
- export const CLIENT_SAFE_SERVER_CONFIG_KEYS: ReadonlyArray<string> = ['streaming']
295
+ // executor-generator) and the data-node await flag (the custom-node runtime
296
+ // skips a fire-and-forget node when picking its return value). Everything else
297
+ // — the raw SQL query, filters, table name, bound params, column mappings,
298
+ // data source id, … — is consumed exclusively inside the server API route (see
299
+ // api-route-generator's SEGMENT_CONFIG, which keeps the full config
300
+ // server-side). None of it may reach the browser bundle.
301
+ //
302
+ // `awaitResult` is a plain boolean choice, never a value or an identifier, so
303
+ // exposing it leaks nothing about the schema or the query.
304
+ export const CLIENT_SAFE_SERVER_CONFIG_KEYS: ReadonlyArray<string> = [
305
+ 'streaming',
306
+ AWAIT_RESULT_CONFIG_KEY,
307
+ ]
300
308
 
301
309
  /**
302
310
  * Strip a server node's config down to the client-safe whitelist before it is
@@ -0,0 +1,187 @@
1
+ import { UIDLWorkflowProtection } from '@teleporthq/teleport-types'
2
+
3
+ /**
4
+ * The shared, stateless auth guard for generated workflow API routes, emitted
5
+ * once at `utils/workflows/workflow-auth.js`.
6
+ *
7
+ * The policy is baked into each route at build time (from the workflow's page
8
+ * protection + a scan of its graph for user-owned writes), so enforcement is a
9
+ * single local JWT decode — `getToken` reads the session cookie the browser
10
+ * already sends and verifies it with `NEXTAUTH_SECRET`. No DB, no network, no
11
+ * round trip. `next-auth/jwt` is required LAZILY so a project generated without
12
+ * authentication (where the package is absent) never fails to load this file —
13
+ * such projects also carry no protected workflows, so the guard no-ops.
14
+ */
15
+ export const generateWorkflowAuthHelperFile = (): string => {
16
+ return `'use strict';
17
+
18
+ // GENERATED — see generateWorkflowAuthHelperFile in
19
+ // @teleporthq/teleport-plugin-next-workflows/src/workflow-auth-generator.ts.
20
+ //
21
+ // Stateless auth guard for workflow API routes. Each route bakes its own policy
22
+ // (const __WF_AUTH) computed by the GUI mapper from the protection of the
23
+ // page(s) that trigger the workflow plus a graph scan for user-owned writes.
24
+
25
+ function getSessionToken(req) {
26
+ var secret = process.env.NEXTAUTH_SECRET;
27
+ if (!secret) {
28
+ return Promise.resolve(null);
29
+ }
30
+ var getToken;
31
+ try {
32
+ getToken = require('next-auth/jwt').getToken;
33
+ } catch (e) {
34
+ return Promise.resolve(null);
35
+ }
36
+ if (typeof getToken !== 'function') {
37
+ return Promise.resolve(null);
38
+ }
39
+ // Local cookie decode — no DB, no network.
40
+ return Promise.resolve()
41
+ .then(function () { return getToken({ req: req, secret: secret }); })
42
+ .catch(function () { return null; });
43
+ }
44
+
45
+ function sessionUserId(token) {
46
+ if (!token || typeof token !== 'object') {
47
+ return null;
48
+ }
49
+ return token.id != null ? token.id : (token.sub != null ? token.sub : null);
50
+ }
51
+
52
+ function roleOf(token) {
53
+ if (!token || typeof token !== 'object') {
54
+ return null;
55
+ }
56
+ if (typeof token.role === 'string') {
57
+ return token.role;
58
+ }
59
+ if (typeof token.roleName === 'string') {
60
+ return token.roleName;
61
+ }
62
+ if (Array.isArray(token.roles) && token.roles.length > 0 && typeof token.roles[0] === 'string') {
63
+ return token.roles[0];
64
+ }
65
+ return null;
66
+ }
67
+
68
+ // Overwrites context[nodeId] drilled down \`path\` with the session user id.
69
+ function bindPath(root, path, value) {
70
+ if (!root || !path || path.length === 0) {
71
+ return;
72
+ }
73
+ var obj = root;
74
+ for (var i = 0; i < path.length - 1; i++) {
75
+ var key = path[i];
76
+ if (obj[key] == null || typeof obj[key] !== 'object') {
77
+ obj[key] = {};
78
+ }
79
+ obj = obj[key];
80
+ }
81
+ obj[path[path.length - 1]] = value;
82
+ }
83
+
84
+ // Returns null when the request may proceed, or { status, message } to reject.
85
+ // Mutates \`context\` in place to bind user-owned columns to the session user.
86
+ async function guardWorkflowRequest(req, context, policy) {
87
+ if (!policy) {
88
+ return null;
89
+ }
90
+
91
+ // Trusted internal server-to-server calls (e.g. password reset, server jobs)
92
+ // present the app secret in a header; only server code can read
93
+ // NEXTAUTH_SECRET, so a browser cannot forge it. These bypass the check.
94
+ var internal = req && req.headers && req.headers['x-internal-data-secret'];
95
+ if (internal && process.env.NEXTAUTH_SECRET && internal === process.env.NEXTAUTH_SECRET) {
96
+ return null;
97
+ }
98
+
99
+ var token = await getSessionToken(req);
100
+
101
+ if (policy.requiresAuth && !token) {
102
+ return { status: 401, message: 'Unauthenticated' };
103
+ }
104
+
105
+ var roles = policy.allowedRoles || [];
106
+ if (policy.requiresAuth && roles.length > 0) {
107
+ var role = roleOf(token);
108
+ if (!role || roles.indexOf(role) < 0) {
109
+ return { status: 403, message: 'Forbidden' };
110
+ }
111
+ }
112
+
113
+ // Identity binding: force every user-owned column to the AUTHENTICATED session
114
+ // id so a caller can never act on another user's rows. Only when a session is
115
+ // present — a guest keeps their (anonymous) client identity, which is why a
116
+ // guest-capable public write is not blocked here.
117
+ if (policy.userScoped && context) {
118
+ var sid = sessionUserId(token);
119
+ if (sid != null) {
120
+ var bindings = (policy.userScoped && policy.userScoped.bindings) || [];
121
+ for (var i = 0; i < bindings.length; i++) {
122
+ var b = bindings[i];
123
+ if (b && b.nodeId) {
124
+ if (context[b.nodeId] == null || typeof context[b.nodeId] !== 'object') {
125
+ context[b.nodeId] = {};
126
+ }
127
+ bindPath(context[b.nodeId], b.path || [], sid);
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+ return null;
134
+ }
135
+
136
+ module.exports = { guardWorkflowRequest: guardWorkflowRequest };
137
+ `
138
+ }
139
+
140
+ /**
141
+ * The route-side pieces that wire a workflow's protection policy into a
142
+ * generated API-route handler. Empty strings when the workflow has no policy,
143
+ * so an unprotected route is byte-identical to before.
144
+ */
145
+ export interface WorkflowAuthInjection {
146
+ // `require(...)` of the shared helper (placed with the other requires).
147
+ requireLine: string
148
+ // `const __WF_AUTH = {...};` — the baked policy.
149
+ policyConst: string
150
+ // The `await` guard call + early 401/403 response, placed after the request
151
+ // context is assembled and BEFORE any node runs / any stream starts.
152
+ guardCall: string
153
+ }
154
+
155
+ const EMPTY_INJECTION: WorkflowAuthInjection = { requireLine: '', policyConst: '', guardCall: '' }
156
+
157
+ export const buildWorkflowAuthInjection = (
158
+ protection: UIDLWorkflowProtection | undefined
159
+ ): WorkflowAuthInjection => {
160
+ if (!protection || (!protection.requiresAuth && !protection.userScoped)) {
161
+ return EMPTY_INJECTION
162
+ }
163
+
164
+ // Only the fields the runtime guard reads — `derivedFrom` is build-time only.
165
+ const policy: {
166
+ requiresAuth: boolean
167
+ allowedRoles: string[]
168
+ userScoped?: UIDLWorkflowProtection['userScoped']
169
+ } = {
170
+ requiresAuth: !!protection.requiresAuth,
171
+ allowedRoles: protection.allowedRoles || [],
172
+ }
173
+ if (protection.userScoped) {
174
+ policy.userScoped = protection.userScoped
175
+ }
176
+
177
+ return {
178
+ requireLine: `const __wfAuth = require('../../../utils/workflows/workflow-auth');\n`,
179
+ policyConst: `const __WF_AUTH = ${JSON.stringify(policy)};\n`,
180
+ guardCall: `
181
+ const __authError = await __wfAuth.guardWorkflowRequest(req, context, __WF_AUTH);
182
+ if (__authError) {
183
+ res.status(__authError.status).json({ error: __authError.message });
184
+ return;
185
+ }`,
186
+ }
187
+ }