@friggframework/core 2.0.0--canary.657.f16d20b.0 → 2.0.0--canary.737.83b4e17.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 (102) hide show
  1. package/CLAUDE.md +48 -93
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/core/CLAUDE.md +1 -33
  6. package/core/Worker.js +11 -317
  7. package/core/create-handler.js +0 -3
  8. package/core/index.js +0 -6
  9. package/core/invocation-scope.js +24 -30
  10. package/database/documentdb-encryption-service.js +2 -33
  11. package/database/documentdb-utils.js +4 -1
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/ciphertext-format.js +24 -0
  14. package/database/encryption/encryption-schema-registry.js +109 -29
  15. package/database/encryption/field-encryption-service.js +55 -16
  16. package/database/encryption/prisma-encryption-extension.js +6 -9
  17. package/database/prisma.js +10 -1
  18. package/encrypt/Cryptor.js +90 -38
  19. package/errors/fetch-error.js +18 -11
  20. package/errors/index.js +4 -2
  21. package/errors/mapping-already-exists-error.js +14 -0
  22. package/generated/prisma-mongodb/edge.js +6 -2
  23. package/generated/prisma-mongodb/index.js +10 -2
  24. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  25. package/generated/prisma-mongodb/package.json +1 -1
  26. package/generated/prisma-mongodb/schema.prisma +1 -1
  27. package/generated/prisma-mongodb/wasm.js +6 -2
  28. package/generated/prisma-postgresql/edge.js +6 -2
  29. package/generated/prisma-postgresql/index.js +10 -2
  30. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  31. package/generated/prisma-postgresql/package.json +1 -1
  32. package/generated/prisma-postgresql/schema.prisma +1 -1
  33. package/generated/prisma-postgresql/wasm.js +6 -2
  34. package/handlers/WEBHOOKS.md +29 -0
  35. package/handlers/app-definition-loader.js +9 -2
  36. package/handlers/app-handler-helpers.js +12 -1
  37. package/handlers/backend-utils.js +1 -30
  38. package/handlers/workers/integration-defined-workers.js +0 -2
  39. package/index.js +2 -18
  40. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -15
  41. package/integrations/integration-base.js +52 -9
  42. package/integrations/integration-router.js +30 -22
  43. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  44. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  45. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  46. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  47. package/integrations/repositories/integration-mapping-repository.js +29 -0
  48. package/integrations/repositories/integration-repository-documentdb.js +32 -0
  49. package/integrations/repositories/integration-repository-interface.js +30 -0
  50. package/integrations/repositories/integration-repository-mongo.js +53 -1
  51. package/integrations/repositories/integration-repository-postgres.js +58 -0
  52. package/integrations/repositories/process-repository-mongo.js +1 -1
  53. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  54. package/integrations/use-cases/create-integration.js +57 -19
  55. package/integrations/use-cases/delete-integration-for-user.js +8 -11
  56. package/integrations/use-cases/get-integration-instance.js +12 -12
  57. package/integrations/use-cases/index.js +1 -5
  58. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  59. package/integrations/use-cases/update-integration.js +12 -12
  60. package/integrations/utils/assert-entity-ids-input.js +42 -0
  61. package/jest-setup.js +13 -2
  62. package/jest-teardown.js +5 -2
  63. package/jest.config.js +4 -0
  64. package/jest.db.config.js +23 -0
  65. package/logs/serialize.js +0 -15
  66. package/modules/requester/oauth-2.js +0 -7
  67. package/modules/requester/requester.js +9 -187
  68. package/modules/use-cases/create-entity-from-credential.js +105 -0
  69. package/modules/use-cases/get-entity-options-by-id.js +7 -5
  70. package/modules/use-cases/get-module.js +29 -8
  71. package/modules/use-cases/process-authorization-callback.js +78 -27
  72. package/modules/use-cases/refresh-entity-options.js +7 -5
  73. package/modules/use-cases/test-module-auth.js +7 -5
  74. package/modules/utils/find-module-definition.js +23 -0
  75. package/modules/utils/map-module-dto.js +5 -3
  76. package/modules/utils/to-credential-id.js +14 -0
  77. package/package.json +9 -8
  78. package/prisma-mongodb/schema.prisma +1 -1
  79. package/prisma-postgresql/schema.prisma +1 -1
  80. package/queues/queue-delivery.js +0 -1
  81. package/queues/queuer-util.js +10 -8
  82. package/queues/sqs-message-body.js +17 -0
  83. package/telemetry/otel-telemetry.js +76 -3
  84. package/telemetry/telemetry-config.js +16 -5
  85. package/telemetry/telemetry-runtime.js +14 -1
  86. package/token/repositories/token-repository-documentdb.js +13 -1
  87. package/token/repositories/token-repository-mongo.js +13 -1
  88. package/token/repositories/token-repository-postgres.js +13 -1
  89. package/types/core/index.d.ts +0 -52
  90. package/types/errors/index.d.ts +0 -47
  91. package/types/module-plugin/index.d.ts +0 -43
  92. package/user/tests/doubles/test-user-repository.js +1 -1
  93. package/user/use-cases/authenticate-user.js +23 -7
  94. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  95. package/core/invocation-deadline.js +0 -91
  96. package/errors/rate-limit-error.js +0 -46
  97. package/integrations/use-cases/clear-rate-limit-wait.js +0 -28
  98. package/integrations/use-cases/record-rate-limit-wait.js +0 -36
  99. package/modules/requester/rate-limit/index.js +0 -4
  100. package/modules/requester/rate-limit/parsers.js +0 -245
  101. package/modules/requester/rate-limit/policy.js +0 -304
  102. package/queues/queue-deferral.js +0 -74
package/core/Worker.js CHANGED
@@ -1,38 +1,15 @@
1
- const {
2
- SQSClient,
3
- GetQueueUrlCommand,
4
- SendMessageCommand,
5
- ChangeMessageVisibilityCommand,
6
- } = require('@aws-sdk/client-sqs');
1
+ const { SQSClient, GetQueueUrlCommand, SendMessageCommand } = require('@aws-sdk/client-sqs');
7
2
  const _ = require('lodash');
8
3
  const { RequiredPropertyError } = require('../errors');
9
4
  const { get } = require('../assertions');
10
5
  const { readQueueDelivery } = require('../queues/queue-delivery');
11
- const { awsConfigOptions } = require('../queues/queuer-util');
12
- const {
13
- MAX_DEFERRED_VISIBILITY_SECONDS,
14
- MAX_DELAY_SECONDS,
15
- deferredMs,
16
- isDeferralCapped,
17
- nextDeferral,
18
- readDeferral,
19
- readDeferralLimits,
20
- withDeferral,
21
- } = require('../queues/queue-deferral');
6
+ const { toSqsMessageBody } = require('../queues/sqs-message-body');
22
7
  const { runMessageScope } = require('./invocation-scope');
23
8
  const { getLogger } = require('../logs');
24
9
 
25
- const sqs = new SQSClient({
26
- region: process.env.AWS_REGION,
27
- ...awsConfigOptions(),
28
- });
10
+ const sqs = new SQSClient({ region: process.env.AWS_REGION });
29
11
  const log = getLogger('frigg.worker');
30
12
 
31
- const validDate = (value) =>
32
- value instanceof Date && !Number.isNaN(value.getTime()) ? value : null;
33
- const queueNameOf = (arn) =>
34
- typeof arn === 'string' && arn ? arn.split(':').pop() : undefined;
35
-
36
13
  class Worker {
37
14
  async getQueueURL(params) {
38
15
  // Passing params in because there will be multiple QueueNames
@@ -57,31 +34,12 @@ class Worker {
57
34
  // messageId, receiveCount and the event come from the scope.
58
35
  log.debug('Record started', { eventName: 'frigg.worker.record_started' });
59
36
 
60
- const delivery = readQueueDelivery(record);
61
- let runParams;
62
37
  try {
63
- runParams = JSON.parse(record.body);
38
+ const runParams = JSON.parse(record.body);
64
39
  this._validateParams(runParams);
65
- await this._run(runParams, context, delivery);
66
- await this._clearDeferredState(record, runParams, delivery);
40
+ await this._run(runParams, context, readQueueDelivery(record));
67
41
  log.debug('Record succeeded', { eventName: 'frigg.worker.record_succeeded' });
68
42
  } catch (error) {
69
- let deferralResult;
70
- if (error.isRateLimited && runParams) {
71
- deferralResult = await this.defer(
72
- record,
73
- runParams,
74
- error,
75
- delivery
76
- );
77
- if (deferralResult.outcome === 'acked') return;
78
- if (deferralResult.outcome === 'failed') {
79
- batchItemFailures.push({
80
- itemIdentifier: record.messageId,
81
- });
82
- return;
83
- }
84
- }
85
43
  if (error.isHaltError) {
86
44
  // HaltError means "discard this message, don't retry".
87
45
  // Treat as success so SQS deletes it from the queue.
@@ -94,30 +52,11 @@ class Worker {
94
52
  });
95
53
  return;
96
54
  }
97
- const skippedDeferral = deferralResult && {
98
- deferral: {
99
- skipped: deferralResult.skipped,
100
- ...(deferralResult.cause && {
101
- cause: deferralResult.cause,
102
- }),
103
- },
104
- };
105
- if (skippedDeferral && delivery.isLastAttempt) {
106
- this._logLost({
107
- retryAt: validDate(error.retryAt)?.toISOString(),
108
- reason: error.reason,
109
- module: error.module,
110
- ...skippedDeferral,
111
- error,
112
- });
113
- } else {
114
- // The message goes back to SQS, so WARN (ADR-048 §4).
115
- log.warn('Record failed, returned for retry', {
116
- eventName: 'frigg.worker.record_failed',
117
- error,
118
- ...skippedDeferral,
119
- });
120
- }
55
+ // The message goes back to SQS, so WARN (ADR-048 §4).
56
+ log.warn('Record failed, returned for retry', {
57
+ eventName: 'frigg.worker.record_failed',
58
+ error,
59
+ });
121
60
  batchItemFailures.push({ itemIdentifier: record.messageId });
122
61
  }
123
62
  });
@@ -137,251 +76,6 @@ class Worker {
137
76
  // parameters
138
77
  }
139
78
 
140
- async defer(record, body, error, delivery) {
141
- const retryAt = validDate(error.retryAt);
142
- if (!retryAt) return { outcome: 'skipped', skipped: 'no_retry_at' };
143
- const queueName = queueNameOf(record.eventSourceARN);
144
- if (!queueName || queueName.endsWith('.fifo')) {
145
- return { outcome: 'skipped', skipped: 'no_event_source' };
146
- }
147
-
148
- const now = Date.now();
149
- const counters = nextDeferral(body, now, record.messageId);
150
- const deferral = {
151
- record,
152
- queueName,
153
- body,
154
- deferredBody: withDeferral(body, counters),
155
- error,
156
- delivery,
157
- retryAt,
158
- waitMs: Math.max(0, retryAt.getTime() - now),
159
- counters,
160
- };
161
-
162
- const limits = readDeferralLimits();
163
- if (isDeferralCapped({ ...counters, retryAt }, limits)) {
164
- await this._recordWait(deferral, 'EXHAUSTED', 'none');
165
- this._logUnacked(
166
- deferral,
167
- 'record_deferral_capped',
168
- 'Rate-limit deferral capped',
169
- {
170
- maxDeferrals: limits.maxDeferrals,
171
- maxDeferredMs: limits.maxDeferredMs,
172
- deferredMs: deferredMs({ ...counters, retryAt }),
173
- }
174
- );
175
- return { outcome: 'failed' };
176
- }
177
-
178
- if (deferral.waitMs <= MAX_DELAY_SECONDS * 1000)
179
- return this._deferWithDelay(deferral);
180
- const scheduled = await this._deferWithSchedule(deferral);
181
- if (scheduled?.outcome) return scheduled;
182
- return this._deferWithVisibility(deferral, scheduled?.scheduleError);
183
- }
184
-
185
- async _deferWithDelay(deferral) {
186
- const delaySeconds = Math.ceil(deferral.waitMs / 1000);
187
- // Write the wait before the send: with a short delay the new message
188
- // can run, and clear the wait, before a later write lands.
189
- await this._recordWait(deferral, 'WAITING', 'delay');
190
- try {
191
- const queueUrl = await this._queueUrl(deferral.queueName);
192
- await this.send(
193
- { ...deferral.deferredBody, QueueUrl: queueUrl },
194
- delaySeconds
195
- );
196
- } catch (cause) {
197
- await this._clearWait(deferral.body, deferral.counters.deferralId);
198
- return { outcome: 'skipped', skipped: 'send_failed', cause };
199
- }
200
- return this._acknowledgeDeferral(deferral, 'delay', { delaySeconds });
201
- }
202
-
203
- async _deferWithSchedule(deferral) {
204
- const { record, retryAt, deferredBody } = deferral;
205
- const scheduleName = `frigg-defer-${record.messageId}`;
206
- try {
207
- const scheduler = this.getSchedulerService();
208
- if (!scheduler) return null;
209
- await scheduler.scheduleOneTime({
210
- scheduleName,
211
- scheduleAt: retryAt,
212
- queueResourceId: record.eventSourceARN,
213
- payload: deferredBody,
214
- });
215
- } catch (cause) {
216
- if (cause?.name !== 'ConflictException')
217
- return { scheduleError: cause };
218
- }
219
- await this._recordWait(deferral, 'WAITING', 'schedule');
220
- return this._acknowledgeDeferral(deferral, 'schedule', {
221
- scheduleName,
222
- });
223
- }
224
-
225
- async _deferWithVisibility(deferral, scheduleError) {
226
- const { record, queueName, delivery, waitMs } = deferral;
227
- const visibilityTimeout = Math.min(
228
- Math.ceil(waitMs / 1000),
229
- MAX_DEFERRED_VISIBILITY_SECONDS
230
- );
231
- try {
232
- const queueUrl = await this._queueUrl(queueName);
233
- await sqs.send(
234
- new ChangeMessageVisibilityCommand({
235
- QueueUrl: queueUrl,
236
- ReceiptHandle: record.receiptHandle,
237
- VisibilityTimeout: visibilityTimeout,
238
- })
239
- );
240
- } catch (cause) {
241
- return { outcome: 'skipped', skipped: 'visibility_failed', cause };
242
- }
243
- await this._recordWait(
244
- deferral,
245
- delivery.isLastAttempt ? 'EXHAUSTED' : 'WAITING',
246
- 'visibility'
247
- );
248
- this._logUnacked(
249
- deferral,
250
- 'record_visibility_extended',
251
- 'Record visibility extended',
252
- {
253
- mechanism: 'visibility',
254
- visibilityTimeout,
255
- ...(scheduleError && { scheduleError }),
256
- }
257
- );
258
- return { outcome: 'failed' };
259
- }
260
-
261
- async _acknowledgeDeferral(deferral, mechanism, fields) {
262
- log.warn('Record deferred', {
263
- eventName: 'frigg.worker.record_deferred',
264
- mechanism,
265
- ...fields,
266
- ...this._deferralLogFields(deferral),
267
- error: deferral.error,
268
- });
269
- return { outcome: 'acked' };
270
- }
271
-
272
- getSchedulerService() {
273
- if (this._schedulerService !== undefined) return this._schedulerService;
274
- if (
275
- !process.env.SCHEDULER_ROLE_ARN ||
276
- process.env.SCHEDULER_PROVIDER === 'mock'
277
- ) {
278
- this._schedulerService = null;
279
- return null;
280
- }
281
- const {
282
- createSchedulerService,
283
- SCHEDULER_PROVIDERS,
284
- } = require('../infrastructure/scheduler/scheduler-service-factory');
285
- this._schedulerService = createSchedulerService({
286
- provider: SCHEDULER_PROVIDERS.EVENTBRIDGE,
287
- });
288
- return this._schedulerService;
289
- }
290
-
291
- recordRateLimitWait() {
292
- return Promise.resolve();
293
- }
294
-
295
- clearRateLimitWait() {
296
- return Promise.resolve();
297
- }
298
-
299
- _queueUrl(queueName) {
300
- this._queueUrls ??= new Map();
301
- if (!this._queueUrls.has(queueName)) {
302
- const lookup = this.getQueueURL({ QueueName: queueName }).catch(
303
- (error) => {
304
- this._queueUrls.delete(queueName);
305
- throw error;
306
- }
307
- );
308
- this._queueUrls.set(queueName, lookup);
309
- }
310
- return this._queueUrls.get(queueName);
311
- }
312
-
313
- async _recordWait({ body, error, counters, retryAt }, status, mechanism) {
314
- await this._runStateHook('record', () =>
315
- this.recordRateLimitWait(body, error, {
316
- status,
317
- mechanism,
318
- deferrals: counters.deferrals,
319
- deferralId: counters.deferralId,
320
- retryAt,
321
- })
322
- );
323
- }
324
-
325
- async _clearDeferredState(record, body, delivery) {
326
- const redelivered = delivery.receiveCount > 1;
327
- const { deferrals, deferralId } = readDeferral(body);
328
- if (deferrals === 0 && !redelivered) return;
329
- await this._clearWait(body, deferralId ?? record.messageId);
330
- }
331
-
332
- async _clearWait(body, deferralId) {
333
- await this._runStateHook('clear', () =>
334
- this.clearRateLimitWait(body, { deferralId })
335
- );
336
- }
337
-
338
- async _runStateHook(operation, hook) {
339
- try {
340
- await hook();
341
- } catch (error) {
342
- log.warn('Rate-limit run state not written', {
343
- eventName: 'frigg.worker.rate_limit_state_failed',
344
- operation,
345
- error,
346
- });
347
- }
348
- }
349
-
350
- _deferralLogFields({ error, retryAt, waitMs, counters }) {
351
- return {
352
- waitMs,
353
- retryAt: retryAt.toISOString(),
354
- deferrals: counters.deferrals,
355
- firstDeferredAt: counters.firstDeferredAt,
356
- reason: error.reason,
357
- module: error.module,
358
- statusCode: error.statusCode,
359
- };
360
- }
361
-
362
- _logUnacked(deferral, eventName, message, fields) {
363
- const logFields = {
364
- ...fields,
365
- ...this._deferralLogFields(deferral),
366
- error: deferral.error,
367
- };
368
- if (deferral.delivery.isLastAttempt) {
369
- this._logLost(logFields);
370
- return;
371
- }
372
- log.warn(message, {
373
- eventName: `frigg.worker.${eventName}`,
374
- ...logFields,
375
- });
376
- }
377
-
378
- _logLost(fields) {
379
- log.error(
380
- 'Rate-limited record lost: the message goes to the dead-letter queue next',
381
- { eventName: 'frigg.worker.record_lost_rate_limited', ...fields }
382
- );
383
- }
384
-
385
79
  // returns the message id
386
80
  async send(params, delay = 0) {
387
81
  this._validateParams(params);
@@ -391,7 +85,7 @@ class Worker {
391
85
  const messageParams = _.omit(params, 'QueueUrl');
392
86
  const args = {
393
87
  DelaySeconds: delay,
394
- MessageBody: JSON.stringify(messageParams),
88
+ MessageBody: toSqsMessageBody(messageParams),
395
89
  QueueUrl: queueURL,
396
90
  };
397
91
  return this.sendAsyncSQSMessage(args);
@@ -12,7 +12,6 @@ const {
12
12
  runInvocationScope,
13
13
  DEFAULT_FLUSH_TIMEOUT_MS,
14
14
  } = require('./invocation-scope');
15
- const { MAX_IN_PROCESS_WAIT_MS } = require('./invocation-deadline');
16
15
  const { secretsToEnv } = require('./secrets-to-env');
17
16
  const { parametersToEnv } = require('./parameters-to-env');
18
17
  const {
@@ -32,7 +31,6 @@ const createHandler = (optionByName = {}) => {
32
31
  telemetry,
33
32
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
34
33
  usageRollup,
35
- maxInProcessWaitMs = MAX_IN_PROCESS_WAIT_MS.http,
36
34
  } = optionByName;
37
35
 
38
36
  if (!method) {
@@ -146,7 +144,6 @@ const createHandler = (optionByName = {}) => {
146
144
  shouldUseDatabase,
147
145
  flushTimeoutMs,
148
146
  context,
149
- maxInProcessWaitMs,
150
147
  }
151
148
  );
152
149
  };
package/core/index.js CHANGED
@@ -3,10 +3,6 @@ const { Worker } = require('./Worker');
3
3
  const { loadInstalledModules } = require('./load-installed-modules');
4
4
  const { createHandler } = require('./create-handler');
5
5
  const { runInvocationScope } = require('./invocation-scope');
6
- const {
7
- runWithInvocationDeadline,
8
- remainingInvocationMs,
9
- } = require('./invocation-deadline');
10
6
 
11
7
  module.exports = {
12
8
  Delegate,
@@ -14,6 +10,4 @@ module.exports = {
14
10
  loadInstalledModules,
15
11
  createHandler,
16
12
  runInvocationScope,
17
- runWithInvocationDeadline,
18
- remainingInvocationMs,
19
13
  };
@@ -1,11 +1,6 @@
1
1
  const { runInContext, LOGGER_SCOPE_KEY } = require('../logs/context');
2
2
  const { summarizeMessageBody } = require('../logs/summarize-event');
3
3
  const { flushSinks, hasFlushableSinks } = require('../logs/logger-runtime');
4
- const {
5
- deadlineFromContext,
6
- remainingTimeMs,
7
- runWithInvocationDeadline,
8
- } = require('./invocation-deadline');
9
4
 
10
5
  // Bounds the tail latency telemetry adds to every warm invocation. Kept low so
11
6
  // an unreachable OTLP endpoint (e.g. a VPC Lambda with no NAT/egress) costs at
@@ -116,6 +111,15 @@ function withDeadline(ms, fn) {
116
111
  });
117
112
  }
118
113
 
114
+ function remainingTimeMs(context) {
115
+ try {
116
+ const remaining = context?.getRemainingTimeInMillis?.();
117
+ return typeof remaining === 'number' ? remaining : Infinity;
118
+ } catch (_) {
119
+ return Infinity;
120
+ }
121
+ }
122
+
119
123
  async function flushInvocation({
120
124
  telemetry,
121
125
  usageRollup,
@@ -163,32 +167,22 @@ async function runInvocationScope(fields, fn, opts = {}) {
163
167
  shouldUseDatabase = true,
164
168
  flushTimeoutMs = DEFAULT_FLUSH_TIMEOUT_MS,
165
169
  context,
166
- maxInProcessWaitMs,
167
170
  } = opts;
168
- const deadline = {
169
- deadlineAt: deadlineFromContext(context),
170
- maxInProcessWaitMs,
171
- };
172
- return runWithInvocationDeadline(deadline, () =>
173
- runInContext(
174
- { [LOGGER_SCOPE_KEY]: { ...(fields || {}) } },
175
- async () => {
176
- try {
177
- return await fn();
178
- } finally {
179
- // Every step is guarded, so a flush never changes the result.
180
- await flushInvocation({
181
- telemetry,
182
- usageRollup,
183
- eventSummary,
184
- shouldUseDatabase,
185
- flushTimeoutMs,
186
- context,
187
- });
188
- }
189
- }
190
- )
191
- );
171
+ return runInContext({ [LOGGER_SCOPE_KEY]: { ...(fields || {}) } }, async () => {
172
+ try {
173
+ return await fn();
174
+ } finally {
175
+ // Every step is guarded, so a flush never changes the result.
176
+ await flushInvocation({
177
+ telemetry,
178
+ usageRollup,
179
+ eventSummary,
180
+ shouldUseDatabase,
181
+ flushTimeoutMs,
182
+ context,
183
+ });
184
+ }
185
+ });
192
186
  }
193
187
 
194
188
  function toCount(value) {
@@ -1,4 +1,5 @@
1
1
  const { Cryptor } = require('../encrypt/Cryptor');
2
+ const { isEncryptedEnvelope } = require('./encryption/ciphertext-format');
2
3
  const {
3
4
  getEncryptedFields,
4
5
  getFieldsToEncryptOnWrite,
@@ -295,39 +296,7 @@ class DocumentDBEncryptionService {
295
296
  * _isEncryptedValue({}) // false
296
297
  */
297
298
  _isEncryptedValue(value) {
298
- // Must be string
299
- if (typeof value !== 'string') {
300
- return false;
301
- }
302
-
303
- // Must have exactly 4 colon-separated parts
304
- const parts = value.split(':');
305
- if (parts.length !== 4) {
306
- return false;
307
- }
308
-
309
- // Enhanced validation: check for base64 pattern
310
- // This prevents false positives on URLs, connection strings, etc.
311
- const base64Pattern = /^[A-Za-z0-9+/=]+$/;
312
-
313
- // All parts should be base64-encoded
314
- if (!parts.every(part => base64Pattern.test(part))) {
315
- return false;
316
- }
317
-
318
- // Encrypted values should be sufficiently long to be valid
319
- // Real encrypted values from Cryptor are always >50 chars due to envelope encryption format:
320
- // - keyId (base64): ~12 chars minimum
321
- // - iv (base64): ~24 chars for 16-byte IV
322
- // - ciphertext (base64): varies, minimum ~16 chars for small values
323
- // - encryptedKey (base64): ~44 chars for 32-byte data key
324
- // Total minimum: ~96 chars, so 50 is a safe lower bound
325
- // This prevents false positives on non-encrypted strings that happen to have 4 colons
326
- if (value.length < 50) {
327
- return false;
328
- }
329
-
330
- return true;
299
+ return isEncryptedEnvelope(value);
331
300
  }
332
301
  }
333
302
 
@@ -58,7 +58,10 @@ async function insertOne(client, collection, document) {
58
58
 
59
59
  // Provide helpful context for common errors
60
60
  if (error.code === 11000) {
61
- throw new Error(`${errorMsg} - Duplicate key violation`);
61
+ throw Object.assign(
62
+ new Error(`${errorMsg} - Duplicate key violation`),
63
+ { code: 11000 }
64
+ );
62
65
  }
63
66
  throw new Error(errorMsg);
64
67
  }
@@ -508,9 +508,9 @@ return entities.map((e) => ({
508
508
 
509
509
  **Verified:**
510
510
 
511
- - ✅ `postgres-relation-decryption.test.js` - Proves the bug exists
512
- - ✅ `postgres-decryption-fix-verification.test.js` - Verifies separate queries work
513
- - ✅ `mongo-decryption-fix-verification.test.js` - Verifies fix for MongoDB
511
+ - ✅ `postgres-relation-decryption.db.test.js` - Proves the bug exists
512
+ - ✅ `postgres-decryption-fix-verification.db.test.js` - Verifies separate queries work
513
+ - ✅ `mongo-decryption-fix-verification.db.test.js` - Verifies fix for MongoDB
514
514
 
515
515
  **Implementation Examples:**
516
516
 
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Recognises values produced by Cryptor.encrypt():
3
+ * keyId:iv:ciphertext:encryptedKey
4
+ * keyId and encryptedKey are base64, iv and ciphertext are hex, so all four
5
+ * parts match the base64 alphabet. Real envelopes are well over 50
6
+ * characters (the encrypted data key alone is longer).
7
+ *
8
+ * Shared by the Prisma (FieldEncryptionService) and DocumentDB paths so a
9
+ * plaintext value that happens to contain colons (`a:b:c:d`, a URL with
10
+ * userinfo and a port) is never mistaken for ciphertext: on write it gets
11
+ * encrypted, on read it is returned as plaintext.
12
+ */
13
+ const BASE64_PART = /^[A-Za-z0-9+/=]+$/;
14
+ const MIN_ENVELOPE_LENGTH = 50;
15
+
16
+ function isEncryptedEnvelope(value) {
17
+ if (typeof value !== 'string' || value.length < MIN_ENVELOPE_LENGTH) {
18
+ return false;
19
+ }
20
+ const parts = value.split(':');
21
+ return parts.length === 4 && parts.every((part) => BASE64_PART.test(part));
22
+ }
23
+
24
+ module.exports = { isEncryptedEnvelope };