@teleporthq/teleport-plugin-next-workflows 0.44.7 → 0.44.8

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 (48) hide show
  1. package/__tests__/credential-result-reply.test.ts +509 -0
  2. package/dist/cjs/api-route-generator.d.ts.map +1 -1
  3. package/dist/cjs/api-route-generator.js +5 -2
  4. package/dist/cjs/api-route-generator.js.map +1 -1
  5. package/dist/cjs/credential-results.d.ts +18 -0
  6. package/dist/cjs/credential-results.d.ts.map +1 -0
  7. package/dist/cjs/credential-results.js +72 -0
  8. package/dist/cjs/credential-results.js.map +1 -0
  9. package/dist/cjs/executor-generator.d.ts.map +1 -1
  10. package/dist/cjs/executor-generator.js +8 -1
  11. package/dist/cjs/executor-generator.js.map +1 -1
  12. package/dist/cjs/nodes/account/account-hash-password.d.ts.map +1 -1
  13. package/dist/cjs/nodes/account/account-hash-password.js +1 -0
  14. package/dist/cjs/nodes/account/account-hash-password.js.map +1 -1
  15. package/dist/cjs/nodes/types.d.ts +6 -0
  16. package/dist/cjs/nodes/types.d.ts.map +1 -1
  17. package/dist/cjs/server-runtime-code.d.ts +8 -0
  18. package/dist/cjs/server-runtime-code.d.ts.map +1 -1
  19. package/dist/cjs/server-runtime-code.js +106 -0
  20. package/dist/cjs/server-runtime-code.js.map +1 -1
  21. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  22. package/dist/esm/api-route-generator.d.ts.map +1 -1
  23. package/dist/esm/api-route-generator.js +5 -2
  24. package/dist/esm/api-route-generator.js.map +1 -1
  25. package/dist/esm/credential-results.d.ts +18 -0
  26. package/dist/esm/credential-results.d.ts.map +1 -0
  27. package/dist/esm/credential-results.js +68 -0
  28. package/dist/esm/credential-results.js.map +1 -0
  29. package/dist/esm/executor-generator.d.ts.map +1 -1
  30. package/dist/esm/executor-generator.js +8 -1
  31. package/dist/esm/executor-generator.js.map +1 -1
  32. package/dist/esm/nodes/account/account-hash-password.d.ts.map +1 -1
  33. package/dist/esm/nodes/account/account-hash-password.js +1 -0
  34. package/dist/esm/nodes/account/account-hash-password.js.map +1 -1
  35. package/dist/esm/nodes/types.d.ts +6 -0
  36. package/dist/esm/nodes/types.d.ts.map +1 -1
  37. package/dist/esm/server-runtime-code.d.ts +8 -0
  38. package/dist/esm/server-runtime-code.d.ts.map +1 -1
  39. package/dist/esm/server-runtime-code.js +106 -0
  40. package/dist/esm/server-runtime-code.js.map +1 -1
  41. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  42. package/package.json +2 -2
  43. package/src/api-route-generator.ts +5 -2
  44. package/src/credential-results.ts +71 -0
  45. package/src/executor-generator.ts +8 -1
  46. package/src/nodes/account/account-hash-password.ts +1 -0
  47. package/src/nodes/types.ts +6 -0
  48. package/src/server-runtime-code.ts +106 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teleporthq/teleport-plugin-next-workflows",
3
- "version": "0.44.7",
3
+ "version": "0.44.8",
4
4
  "description": "A plugin for workflow code generation in Next.js projects.",
5
5
  "author": "teleportHQ",
6
6
  "license": "MIT",
@@ -69,5 +69,5 @@
69
69
  "@teleporthq/teleport-shared": "^0.44.7",
70
70
  "@teleporthq/teleport-types": "^0.44.0"
71
71
  },
72
- "gitHead": "a279c1bd1e268a8b7302e2c4fafd45748a1d242a"
72
+ "gitHead": "81bb230e4f5c7b6c339850a8589fa29c78602d66"
73
73
  }
@@ -527,9 +527,12 @@ function __isStreamingAI(node, config) {
527
527
  return config && config.streaming && __streamingAITypes.indexOf(node.type) >= 0;
528
528
  }
529
529
 
530
- // One node's result to the browser — never one kept on the server, and a data
531
- // node's rows without the users table's credentials (see segmentReply).
530
+ // One node's result to the browser — never one kept on the server nor a
531
+ // credential (the closing reply carries that one sealed), and a data node's
532
+ // rows without the users table's credentials (see segmentReply).
533
+ const __credentialResultIds = utils.credentialResultNodeIds(SEGMENT_CONFIG);
532
534
  function __streamNodeResult(res, nodeId, result) {
535
+ if (__credentialResultIds[nodeId]) return;
533
536
  const kept = SEGMENT_CONFIG.nodes.find(function(nd) { return nd.id === nodeId; });
534
537
  if (kept && kept.config && kept.config.keepResultOnServer === true && !utils.isBranchingNodeType(kept.type)) return;
535
538
  res.write('data: ' + JSON.stringify({ type: 'node-result', nodeId: nodeId, result: utils.withoutCredentialColumns(kept, result) }) + '\\n\\n');
@@ -0,0 +1,71 @@
1
+ import { nodeRegistry } from './nodes'
2
+
3
+ /**
4
+ * The node types whose result is a credential, read off the node registry
5
+ * (`resultIsCredential`): today the password-hashing node. Its result stays on
6
+ * the server. A server segment replies it to the browser only sealed —
7
+ * encrypted with a key derived from the app secret, signed like every other
8
+ * result — and a later server segment opens it again, so a workflow that
9
+ * hashes in one segment and writes in another still works (see the server
10
+ * runtime: `sealResult`, `openSealedResults`).
11
+ */
12
+ export const CREDENTIAL_RESULT_NODE_TYPES: string[] = Object.keys(nodeRegistry).filter(
13
+ (nodeType) => nodeRegistry[nodeType].resultIsCredential === true
14
+ )
15
+
16
+ /**
17
+ * `credentialResultNodeIds(segmentConfig)`: the nodes of a segment whose
18
+ * result is a credential — every node of a credential type, and every map
19
+ * loop whose results are such a node's results (the loop's last body step, as
20
+ * the route runs it; a loop of loops follows its inner loop).
21
+ */
22
+ export const generateCredentialResultsCode = (): string => `
23
+ var __CREDENTIAL_RESULT_NODE_TYPES = ${JSON.stringify(CREDENTIAL_RESULT_NODE_TYPES)};
24
+
25
+ function lastLoopBodyNodeId(loopId, sortedNodes, edges) {
26
+ var start = edges.find(function(e) { return e.source === loopId && e.sourceHandle === 'loop'; });
27
+ if (!start) return null;
28
+ var body = {};
29
+ var queue = [start.target];
30
+ while (queue.length > 0) {
31
+ var current = queue.shift();
32
+ if (body[current] || current === loopId) continue;
33
+ body[current] = true;
34
+ edges.forEach(function(e) {
35
+ if (e.source === current && (e.sourceHandle === 'loop-body-out' || !e.sourceHandle) && e.target !== loopId) {
36
+ queue.push(e.target);
37
+ }
38
+ });
39
+ }
40
+ var last = null;
41
+ sortedNodes.forEach(function(n) { if (body[n.id]) last = n.id; });
42
+ return last;
43
+ }
44
+
45
+ function credentialResultNodeIds(segmentConfig) {
46
+ var nodes = (segmentConfig && segmentConfig.nodes) || [];
47
+ var edges = (segmentConfig && segmentConfig.edges) || [];
48
+ var ids = {};
49
+ nodes.forEach(function(n) {
50
+ if (__CREDENTIAL_RESULT_NODE_TYPES.indexOf(n.type) !== -1) ids[n.id] = true;
51
+ });
52
+ var sortedNodes = nodes.slice().sort(function(a, b) { return (a.stepNumber || 0) - (b.stepNumber || 0); });
53
+ var mapLoops = nodes.filter(function(n) {
54
+ var loopType = n.config && n.config.loopType;
55
+ return n.type === 'general-loop' && !!loopType && loopType !== 'forEach';
56
+ });
57
+ var grew = true;
58
+ while (grew) {
59
+ grew = false;
60
+ mapLoops.forEach(function(loop) {
61
+ if (ids[loop.id]) return;
62
+ var last = lastLoopBodyNodeId(loop.id, sortedNodes, edges);
63
+ if (last && ids[last]) {
64
+ ids[loop.id] = true;
65
+ grew = true;
66
+ }
67
+ });
68
+ }
69
+ return ids;
70
+ }
71
+ `
@@ -5,6 +5,7 @@ import {
5
5
  } from './email-locale'
6
6
  import { generateSignedInDestinationCode } from './auth-return/signed-in-destination-code'
7
7
  import { generateCredentialColumnsCode } from './credential-columns-code'
8
+ import { generateCredentialResultsCode } from './credential-results'
8
9
 
9
10
  export interface SharedRuntimeUtilsOptions {
10
11
  /**
@@ -1418,7 +1419,12 @@ var SEGMENT_REPLY_PRIVATE_KEYS = {
1418
1419
  //
1419
1420
  // A data node's rows are replied without the auth users table's credentials
1420
1421
  // (see credential-columns-code.ts).
1422
+ //
1423
+ // A node whose result is a credential (a password hash) is left out here too,
1424
+ // whatever its config says: the server runtime replies it sealed, readable by
1425
+ // a later server segment only (see credential-results.ts).
1421
1426
  ${generateCredentialColumnsCode()}
1427
+ ${generateCredentialResultsCode()}
1422
1428
  // The nodes whose result the client branches on: never kept on the server.
1423
1429
  function isBranchingNodeType(type) {
1424
1430
  return type === 'general-if-statement' || type === 'general-switch';
@@ -1427,7 +1433,7 @@ function isBranchingNodeType(type) {
1427
1433
  function segmentReply(segmentConfig, context, snapshot) {
1428
1434
  var reply = {};
1429
1435
  var own = {};
1430
- var kept = {};
1436
+ var kept = credentialResultNodeIds(segmentConfig);
1431
1437
  var nodes = (segmentConfig && segmentConfig.nodes) || [];
1432
1438
  for (var ni = 0; ni < nodes.length; ni++) {
1433
1439
  own[nodes[ni].id] = nodes[ni];
@@ -1514,6 +1520,7 @@ module.exports = {
1514
1520
  snapshotIncomingContext,
1515
1521
  segmentReply,
1516
1522
  withoutCredentialColumns,
1523
+ credentialResultNodeIds,
1517
1524
  evaluateCondition,
1518
1525
  evaluateSingleComparison,
1519
1526
  normalizeComparisonOperator,
@@ -47,6 +47,7 @@ async function account_hash_password(config: any, context: Record<string, unknow
47
47
  export const accountHashPassword: NodeHandlerGenerator = {
48
48
  nodeType: 'account-hash-password',
49
49
  executionEnv: 'server',
50
+ resultIsCredential: true,
50
51
  dependencies: {
51
52
  bcryptjs: '^2.4.3',
52
53
  },
@@ -114,6 +114,12 @@ export interface NodeHandlerGenerator {
114
114
  nodeType: string
115
115
  executionEnv: 'client' | 'server' | 'universal'
116
116
  isTerminal?: boolean
117
+ /**
118
+ * The node's result is a credential (a password hash). A server segment
119
+ * never replies it as it is: the browser receives it sealed, and only the
120
+ * app's own later server segments can open it (see credential-results.ts).
121
+ */
122
+ resultIsCredential?: boolean
117
123
  dependencies?: Record<string, string>
118
124
  generateHandler(): string
119
125
  generateServerHandler?(): string
@@ -27,6 +27,14 @@
27
27
  * that needs a trustworthy figure (a price, an owner) reads it from the
28
28
  * database itself.
29
29
  *
30
+ * A result that is a credential (a password hash, see credential-results.ts)
31
+ * makes the same trip SEALED: `segmentReply` replies it encrypted with a key
32
+ * derived from NEXTAUTH_SECRET (AES-256-GCM) and signs the sealed form, and
33
+ * `claimSegmentContext` opens every sealed value a request hands it (a
34
+ * relayed result once its signature holds). The browser relays it without
35
+ * ever reading it, and a later segment's reply hands back the sealed form,
36
+ * never the opened one.
37
+ *
30
38
  * The facts about the graph each route needs are baked into its
31
39
  * SEGMENT_CONFIG at generation time (see segment-trust.ts).
32
40
  */
@@ -51,6 +59,59 @@ function mac(text) {
51
59
  return crypto.createHmac('sha256', stepKey()).update(text).digest('hex');
52
60
  }
53
61
 
62
+ var __sealKeyCache = { secret: null, key: null };
63
+
64
+ function sealKey() {
65
+ var secret = process.env.NEXTAUTH_SECRET || '';
66
+ if (__sealKeyCache.secret !== secret) {
67
+ __sealKeyCache = {
68
+ secret: secret,
69
+ key: crypto.createHmac('sha256', secret).update('teleport-workflow-seal:v1').digest()
70
+ };
71
+ }
72
+ return __sealKeyCache.key;
73
+ }
74
+
75
+ var SEAL_IV_BYTES = 12;
76
+ var SEAL_TAG_BYTES = 16;
77
+
78
+ var SEAL_AAD = Buffer.from('teleport-workflow-sealed-result:v1', 'utf8');
79
+
80
+ // The sealed form of a credential result; undefined (the result is then not
81
+ // replied at all) without an app secret, whose key anyone could derive.
82
+ function sealResult(value) {
83
+ if (!process.env.NEXTAUTH_SECRET) return undefined;
84
+ var serialized;
85
+ try { serialized = JSON.stringify(value); } catch (e) { return undefined; }
86
+ if (serialized === undefined) return undefined;
87
+ var iv = crypto.randomBytes(SEAL_IV_BYTES);
88
+ var cipher = crypto.createCipheriv('aes-256-gcm', sealKey(), iv);
89
+ cipher.setAAD(SEAL_AAD);
90
+ var data = Buffer.concat([cipher.update(serialized, 'utf8'), cipher.final()]);
91
+ return { __sealed: Buffer.concat([iv, cipher.getAuthTag(), data]).toString('base64') };
92
+ }
93
+
94
+ function isSealedResult(value) {
95
+ return !!value && typeof value === 'object' && !Array.isArray(value) &&
96
+ typeof value.__sealed === 'string' && Object.keys(value).length === 1;
97
+ }
98
+
99
+ // { value } when the sealed form opens under this app's key, else null.
100
+ function openSealedResult(sealed) {
101
+ if (!process.env.NEXTAUTH_SECRET) return null;
102
+ try {
103
+ var raw = Buffer.from(sealed.__sealed, 'base64');
104
+ if (raw.length <= SEAL_IV_BYTES + SEAL_TAG_BYTES) return null;
105
+ var decipher = crypto.createDecipheriv('aes-256-gcm', sealKey(), raw.subarray(0, SEAL_IV_BYTES));
106
+ decipher.setAAD(SEAL_AAD);
107
+ decipher.setAuthTag(raw.subarray(SEAL_IV_BYTES, SEAL_IV_BYTES + SEAL_TAG_BYTES));
108
+ var data = Buffer.concat([decipher.update(raw.subarray(SEAL_IV_BYTES + SEAL_TAG_BYTES)), decipher.final()]);
109
+ return { value: JSON.parse(data.toString('utf8')) };
110
+ } catch (e) {
111
+ return null;
112
+ }
113
+ }
114
+
54
115
  // Without an app secret every key here would derive from '' — a value anyone
55
116
  // can compute — so nothing verifies: relayed server results are dropped and no
56
117
  // request passes as an internal call. (The generator gives every app with
@@ -206,10 +267,48 @@ function resetPreviousResult(segmentConfig, context) {
206
267
  // merge will.
207
268
  var __incomingOrders = new WeakMap();
208
269
 
270
+ // The sealed results this segment opened, so its reply hands the caller back
271
+ // the sealed form it relayed (see resealRelayedResults).
272
+ var __openedResults = new WeakMap();
273
+
274
+ // Opens every sealed value the request hands this segment, so its nodes read
275
+ // the credential itself: a relayed server result (whose signature
276
+ // dropUnsignedResults checked first), or a value the browser holds from one
277
+ // (a custom node's output, the previous result). Only this app's server
278
+ // seals, so what opens is what it sealed.
279
+ function openSealedResults(context) {
280
+ var opened = [];
281
+ Object.keys(context).forEach(function(key) {
282
+ if (isControlKey(key) && key !== '__previousNodeResult') return;
283
+ if (!isSealedResult(context[key])) return;
284
+ var result = openSealedResult(context[key]);
285
+ if (!result) return;
286
+ opened.push({ sealed: context[key], value: result.value });
287
+ context[key] = result.value;
288
+ });
289
+ __openedResults.set(context, opened);
290
+ }
291
+
292
+ // Every reply entry that is an opened value (the value itself, or the previous
293
+ // result taken from it) goes back sealed.
294
+ function resealRelayedResults(context, reply) {
295
+ var opened = __openedResults.get(context) || [];
296
+ if (opened.length === 0) return;
297
+ Object.keys(reply).forEach(function(key) {
298
+ for (var i = 0; i < opened.length; i++) {
299
+ if (reply[key] === opened[i].value) {
300
+ reply[key] = opened[i].sealed;
301
+ return;
302
+ }
303
+ }
304
+ });
305
+ }
306
+
209
307
  function claimSegmentContext(segmentConfig, context) {
210
308
  var orderKeys = readSignedOrder(context);
211
309
  if (orderKeys) restoreOrder(context, orderKeys);
212
310
  dropUnsignedResults(segmentConfig, context, orderKeys);
311
+ openSealedResults(context);
213
312
  stripForeignControlKeys(segmentConfig, context);
214
313
  __incomingOrders.set(context, Object.keys(context).filter(function(k) { return !isControlKey(k); }));
215
314
  utils.claimSegmentContext(segmentConfig, context);
@@ -219,6 +318,13 @@ function claimSegmentContext(segmentConfig, context) {
219
318
 
220
319
  function segmentReply(segmentConfig, context, snapshot) {
221
320
  var reply = utils.segmentReply(segmentConfig, context, snapshot);
321
+ resealRelayedResults(context, reply);
322
+ var credentialIds = utils.credentialResultNodeIds(segmentConfig);
323
+ Object.keys(credentialIds).forEach(function(id) {
324
+ if (context[id] === undefined) return;
325
+ var sealed = sealResult(context[id]);
326
+ if (sealed) reply[id] = sealed;
327
+ });
222
328
  var sigs = {};
223
329
  var incoming = context.__sig && typeof context.__sig === 'object' && !Array.isArray(context.__sig) ? context.__sig : {};
224
330
  Object.keys(incoming).forEach(function(id) {