@friggframework/core 2.0.0--canary.731.ffe61d3.0 → 2.0.0--canary.656.6eb85ab.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 (94) hide show
  1. package/CLAUDE.md +14 -42
  2. package/application/commands/README.md +11 -17
  3. package/application/commands/entity-commands.js +60 -18
  4. package/application/commands/integration-commands.js +0 -63
  5. package/core/CLAUDE.md +3 -1
  6. package/core/create-handler.js +3 -0
  7. package/core/index.js +6 -0
  8. package/core/invocation-deadline.js +91 -0
  9. package/core/invocation-scope.js +30 -24
  10. package/database/documentdb-encryption-service.js +33 -2
  11. package/database/documentdb-utils.js +1 -4
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/encryption-schema-registry.js +29 -109
  14. package/database/encryption/field-encryption-service.js +16 -55
  15. package/database/encryption/prisma-encryption-extension.js +9 -6
  16. package/database/prisma.js +1 -10
  17. package/encrypt/Cryptor.js +38 -90
  18. package/errors/fetch-error.js +11 -18
  19. package/errors/index.js +2 -4
  20. package/errors/rate-limit-error.js +45 -0
  21. package/generated/prisma-mongodb/edge.js +2 -6
  22. package/generated/prisma-mongodb/index.js +2 -10
  23. package/generated/prisma-mongodb/package.json +1 -1
  24. package/generated/prisma-mongodb/schema.prisma +1 -1
  25. package/generated/prisma-mongodb/wasm.js +2 -6
  26. package/generated/prisma-postgresql/edge.js +2 -6
  27. package/generated/prisma-postgresql/index.js +2 -10
  28. package/generated/prisma-postgresql/package.json +1 -1
  29. package/generated/prisma-postgresql/schema.prisma +1 -1
  30. package/generated/prisma-postgresql/wasm.js +2 -6
  31. package/handlers/WEBHOOKS.md +0 -29
  32. package/handlers/app-definition-loader.js +2 -9
  33. package/handlers/app-handler-helpers.js +1 -12
  34. package/handlers/backend-utils.js +2 -1
  35. package/handlers/workers/integration-defined-workers.js +2 -0
  36. package/index.js +18 -2
  37. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +13 -67
  38. package/integrations/integration-base.js +9 -52
  39. package/integrations/integration-router.js +22 -30
  40. package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
  41. package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
  42. package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
  43. package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
  44. package/integrations/repositories/integration-mapping-repository.js +0 -29
  45. package/integrations/repositories/integration-repository-documentdb.js +0 -32
  46. package/integrations/repositories/integration-repository-interface.js +0 -30
  47. package/integrations/repositories/integration-repository-mongo.js +1 -53
  48. package/integrations/repositories/integration-repository-postgres.js +0 -58
  49. package/integrations/repositories/process-repository-mongo.js +1 -1
  50. package/integrations/use-cases/create-integration.js +19 -57
  51. package/integrations/use-cases/delete-integration-for-user.js +11 -8
  52. package/integrations/use-cases/get-integration-instance.js +12 -12
  53. package/integrations/use-cases/update-integration.js +12 -12
  54. package/jest-setup.js +2 -13
  55. package/jest-teardown.js +2 -5
  56. package/jest.config.js +0 -4
  57. package/logs/serialize.js +15 -0
  58. package/modules/requester/rate-limit/index.js +4 -0
  59. package/modules/requester/rate-limit/parsers.js +245 -0
  60. package/modules/requester/rate-limit/policy.js +304 -0
  61. package/modules/requester/requester.js +187 -9
  62. package/modules/use-cases/get-entity-options-by-id.js +5 -7
  63. package/modules/use-cases/get-module.js +8 -29
  64. package/modules/use-cases/process-authorization-callback.js +27 -78
  65. package/modules/use-cases/refresh-entity-options.js +5 -7
  66. package/modules/use-cases/test-module-auth.js +5 -7
  67. package/modules/utils/map-module-dto.js +3 -5
  68. package/package.json +7 -10
  69. package/prisma-mongodb/schema.prisma +1 -1
  70. package/prisma-postgresql/schema.prisma +1 -1
  71. package/queues/queuer-util.js +5 -6
  72. package/telemetry/otel-telemetry.js +3 -76
  73. package/telemetry/telemetry-config.js +5 -16
  74. package/telemetry/telemetry-runtime.js +1 -14
  75. package/token/repositories/token-repository-documentdb.js +1 -13
  76. package/token/repositories/token-repository-mongo.js +1 -13
  77. package/token/repositories/token-repository-postgres.js +1 -13
  78. package/types/core/index.d.ts +33 -0
  79. package/types/errors/index.d.ts +47 -0
  80. package/types/module-plugin/index.d.ts +43 -0
  81. package/user/tests/doubles/test-user-repository.js +1 -1
  82. package/user/use-cases/authenticate-user.js +7 -23
  83. package/user/use-cases/get-user-from-bearer-token.js +2 -7
  84. package/database/encryption/ciphertext-format.js +0 -24
  85. package/errors/mapping-already-exists-error.js +0 -14
  86. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  87. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  88. package/integrations/use-cases/add-entities-to-integration.js +0 -92
  89. package/integrations/use-cases/remove-entities-from-integration.js +0 -70
  90. package/integrations/utils/assert-entity-ids-input.js +0 -42
  91. package/jest.db.config.js +0 -23
  92. package/modules/use-cases/create-entity-from-credential.js +0 -105
  93. package/modules/utils/find-module-definition.js +0 -23
  94. package/modules/utils/to-credential-id.js +0 -14
package/package.json CHANGED
@@ -1,17 +1,15 @@
1
1
  {
2
2
  "name": "@friggframework/core",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.731.ffe61d3.0",
4
+ "version": "2.0.0--canary.656.6eb85ab.0",
5
5
  "dependencies": {
6
6
  "@aws-sdk/client-apigatewaymanagementapi": "^3.588.0",
7
7
  "@aws-sdk/client-kms": "^3.588.0",
8
8
  "@aws-sdk/client-lambda": "^3.714.0",
9
9
  "@aws-sdk/client-s3": "^3.588.0",
10
- "@aws-sdk/client-scheduler": "^3.588.0",
11
10
  "@aws-sdk/client-sqs": "^3.588.0",
12
11
  "@aws-sdk/client-ssm": "^3.588.0",
13
12
  "@aws-sdk/s3-request-presigner": "^3.588.0",
14
- "@friggframework/schemas": "2.0.0--canary.731.ffe61d3.0",
15
13
  "@hapi/boom": "^10.0.1",
16
14
  "@opentelemetry/api": "^1.9.1",
17
15
  "@opentelemetry/context-async-hooks": "^2.9.0",
@@ -21,12 +19,12 @@
21
19
  "@opentelemetry/sdk-metrics": "^2.9.0",
22
20
  "@opentelemetry/sdk-trace-base": "^2.9.0",
23
21
  "bcryptjs": "^2.4.3",
24
- "body-parser": "^1.20.9",
22
+ "body-parser": "^1.20.5",
25
23
  "bson": "^4.7.2",
26
24
  "chalk": "^4.1.2",
27
25
  "cors": "^2.8.5",
28
26
  "dotenv": "^16.4.7",
29
- "express": "^4.22.3",
27
+ "express": "^4.22.2",
30
28
  "express-async-handler": "^1.2.0",
31
29
  "form-data": "^4.0.6",
32
30
  "fs-extra": "^11.2.0",
@@ -49,9 +47,9 @@
49
47
  }
50
48
  },
51
49
  "devDependencies": {
52
- "@friggframework/eslint-config": "2.0.0--canary.731.ffe61d3.0",
53
- "@friggframework/prettier-config": "2.0.0--canary.731.ffe61d3.0",
54
- "@friggframework/test": "2.0.0--canary.731.ffe61d3.0",
50
+ "@friggframework/eslint-config": "2.0.0--canary.656.6eb85ab.0",
51
+ "@friggframework/prettier-config": "2.0.0--canary.656.6eb85ab.0",
52
+ "@friggframework/test": "2.0.0--canary.656.6eb85ab.0",
55
53
  "@prisma/client": "^6.19.3",
56
54
  "@types/lodash": "4.17.15",
57
55
  "@typescript-eslint/eslint-plugin": "^8.0.0",
@@ -69,7 +67,6 @@
69
67
  "scripts": {
70
68
  "lint:fix": "prettier --write --loglevel error . && eslint . --fix",
71
69
  "test": "jest --passWithNoTests # TODO",
72
- "test:db": "jest --config jest.db.config.js --runInBand",
73
70
  "prisma:generate:mongo": "npx prisma generate --schema ./prisma-mongodb/schema.prisma",
74
71
  "prisma:generate:postgres": "npx prisma generate --schema ./prisma-postgresql/schema.prisma",
75
72
  "prisma:generate": "npm run prisma:generate:mongo && npm run prisma:generate:postgres",
@@ -92,5 +89,5 @@
92
89
  "publishConfig": {
93
90
  "access": "public"
94
91
  },
95
- "gitHead": "ffe61d3981e0f6a83e9c8063efcb77ce121c1286"
92
+ "gitHead": "6eb85ab403f6a3aa18fc5ad49c63c1799890ec55"
96
93
  }
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-mongodb"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with
@@ -5,7 +5,7 @@
5
5
  generator client {
6
6
  provider = "prisma-client-js"
7
7
  output = "../generated/prisma-postgresql"
8
- binaryTargets = ["native", "rhel-openssl-3.0.x", "linux-arm64-openssl-3.0.x"] // native for local dev, rhel for x86_64 Lambda, linux-arm64 for arm64 Lambda
8
+ binaryTargets = ["native", "rhel-openssl-3.0.x"] // native for local dev, rhel for Lambda deployment
9
9
  // Library engine (default since Prisma 3.x): Rust query engine loads as a
10
10
  // Node-API addon inside the same process. The binary engine forks a child
11
11
  // query-engine subprocess and communicates over a local HTTP/IPC pipe with
@@ -97,17 +97,16 @@ const QueuerUtil = {
97
97
  Id: uuid(),
98
98
  MessageBody: JSON.stringify(entry),
99
99
  });
100
- // Sends 10, then starts a fresh buffer. Each command gets its own
101
- // array: clearing the shared buffer in place would also empty the
102
- // Entries of a command that was already sent.
100
+ // Sends 10, then purges the buffer
103
101
  if (buffer.length === batchSize) {
104
- const batch = buffer.splice(0, buffer.length);
105
102
  const command = new SendMessageBatchCommand({
106
- Entries: batch,
103
+ Entries: buffer,
107
104
  QueueUrl: queueUrl,
108
105
  });
109
106
  const result = await sqs.send(command);
110
- inspectBatchResult(result, queueUrl, batch);
107
+ inspectBatchResult(result, queueUrl, buffer);
108
+ // Purge the buffer
109
+ buffer.splice(0, buffer.length);
111
110
  }
112
111
  }
113
112
 
@@ -16,7 +16,6 @@ const { createTelemetryEventBus } = require('./telemetry-event-bus');
16
16
  const {
17
17
  runWithTelemetryContext,
18
18
  mergeTelemetryContext,
19
- getTelemetryContextStore,
20
19
  } = require('./telemetry-context');
21
20
  const { serializeError } = require('../logs/serialize');
22
21
  const { LOGGER_SCOPE_KEY } = require('../logs/context');
@@ -28,74 +27,6 @@ const TRACER_NAME = 'frigg';
28
27
  const METRIC_EXPORT_INTERVAL_MS =
29
28
  Number(process.env.OTEL_METRIC_EXPORT_INTERVAL_MS) || 60000;
30
29
 
31
- // ADR-011 §2: high-cardinality ids ride baggage/ALS; copy onto SPANS only
32
- // (never metric labels). Keys match withContext baggage entry names.
33
- const BAGGAGE_TO_SPAN_ATTR = Object.freeze({
34
- integrationId: 'frigg.integration_id',
35
- userId: 'frigg.user_id',
36
- integrationType: 'integration_type',
37
- version: 'frigg.version',
38
- });
39
-
40
- function nonEmptyString(value) {
41
- if (value === undefined || value === null) return null;
42
- const s = String(value).trim();
43
- return s.length > 0 ? s : null;
44
- }
45
-
46
- /**
47
- * Built-in processor: stamp active baggage (fallback ALS) onto each new span
48
- * as Frigg span attributes. Runs ahead of BatchSpanProcessor so exported OTLP
49
- * spans carry attribution Watchtower/backends can index. Never touches metrics.
50
- */
51
- class BaggageAttributeSpanProcessor {
52
- onStart(span, parentContext) {
53
- try {
54
- const baggage = otelApi.propagation.getBaggage(parentContext);
55
- const als = getTelemetryContextStore();
56
- const existing =
57
- span && span.attributes && typeof span.attributes === 'object'
58
- ? span.attributes
59
- : null;
60
-
61
- for (const [baggageKey, attrName] of Object.entries(
62
- BAGGAGE_TO_SPAN_ATTR
63
- )) {
64
- if (
65
- existing &&
66
- existing[attrName] !== undefined &&
67
- existing[attrName] !== null
68
- ) {
69
- continue; // explicit span attribute wins
70
- }
71
- let value = null;
72
- if (baggage) {
73
- const entry = baggage.getEntry(baggageKey);
74
- value = nonEmptyString(entry && entry.value);
75
- }
76
- if (!value && als) {
77
- value = nonEmptyString(als[baggageKey]);
78
- }
79
- if (value) {
80
- span.setAttribute(attrName, value);
81
- }
82
- }
83
- } catch (_) {
84
- // Telemetry must never break the wrapped path.
85
- }
86
- }
87
-
88
- onEnd() {}
89
-
90
- shutdown() {
91
- return Promise.resolve();
92
- }
93
-
94
- forceFlush() {
95
- return Promise.resolve();
96
- }
97
- }
98
-
99
30
  /**
100
31
  * Register an AsyncLocalStorage-backed OTel context manager once per process.
101
32
  * Without it `BasicTracerProvider` uses the Noop context manager, so
@@ -152,16 +83,12 @@ class OtelTelemetry {
152
83
  })
153
84
  : new AlwaysOnSampler();
154
85
 
155
- // Attribution processor ahead of the batch exporter so every exported
156
- // span (handler, apimodule, adopter) carries frigg.* ids from baggage.
157
- const spanProcessors = [new BaggageAttributeSpanProcessor()];
158
- if (traceExporter) {
159
- spanProcessors.push(new BatchSpanProcessor(traceExporter));
160
- }
161
86
  this._tracerProvider = new BasicTracerProvider({
162
87
  resource: res,
163
88
  sampler,
164
- spanProcessors,
89
+ spanProcessors: traceExporter
90
+ ? [new BatchSpanProcessor(traceExporter)]
91
+ : [],
165
92
  });
166
93
 
167
94
  const metricReader = metricExporter
@@ -3,14 +3,11 @@
3
3
  * into a normalized config the TelemetryService and
4
4
  * usage rollup consume: `{ exporter, northStar, sampleRatio }`.
5
5
  *
6
- * Exporter default when `Definition.telemetry.exporter` is omitted:
7
- * 1. `OTEL_EXPORTER_OTLP_ENDPOINT` set (non-empty after trim) → `{ type: 'otlp' }`
8
- * (zero-code Watchtower / collector activation on any stage, including local)
9
- * 2. else STAGE=local → `{ type: 'console' }` (visible, free)
10
- * 3. else → `{ type: 'none' }` (deployed stages must not surprise-write to
11
- * CloudWatch; `dev` is a deployed AWS stage)
12
- * An explicit `Definition.telemetry.exporter` always wins over the env var, so
13
- * `{ type: 'none' }` still disables export even when the endpoint is set.
6
+ * Exporter default is keyed off STAGE: only a genuinely LOCAL run (STAGE=local)
7
+ * gets `console` (visible, free); every deployed stage — including `dev` —
8
+ * defaults to `none`. `dev` is a deployed AWS stage, and `console` there would
9
+ * write full spans to CloudWatch by default (cost + a data-exposure surface).
10
+ * Adopters opt into `console`/`otlp` explicitly for deployed stages.
14
11
  */
15
12
  const VALID_EXPORTER_TYPES = [
16
13
  'none',
@@ -21,16 +18,8 @@ const VALID_EXPORTER_TYPES = [
21
18
  'datadog',
22
19
  ];
23
20
 
24
- function hasOtlpEndpointEnv() {
25
- const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
26
- return typeof endpoint === 'string' && endpoint.trim().length > 0;
27
- }
28
-
29
21
  function normalizeExporterConfig(exporter, stage) {
30
22
  if (!exporter) {
31
- if (hasOtlpEndpointEnv()) {
32
- return { type: 'otlp' };
33
- }
34
23
  return stage === 'local' ? { type: 'console' } : { type: 'none' };
35
24
  }
36
25
 
@@ -47,21 +47,8 @@ function getTelemetry() {
47
47
  try {
48
48
  const { telemetry = {} } = loadTelemetryConfig();
49
49
  const stage = process.env.STAGE || process.env.NODE_ENV || 'production';
50
- // loadAppDefinition normally resolves via resolveTelemetryConfig. When the
51
- // loader returns an unresolved block (exporter unset) — e.g. tests, or a
52
- // Definition with no telemetry key — apply the same env-aware default so
53
- // OTEL_EXPORTER_OTLP_ENDPOINT still auto-activates `{ type: 'otlp' }`.
54
- // Explicit exporter (incl. `{ type: 'none' }`) always wins.
55
- let exporter = telemetry.exporter;
56
- if (exporter === undefined || exporter === null) {
57
- const { resolveTelemetryConfig } = require('./telemetry-config');
58
- exporter = resolveTelemetryConfig(
59
- { telemetry: {} },
60
- { stage }
61
- ).exporter;
62
- }
63
50
  state.telemetry = createTelemetry({
64
- exporter,
51
+ exporter: telemetry.exporter,
65
52
  sampleRatio: telemetry.sampleRatio,
66
53
  resource: { service: process.env.FRIGG_STACK || 'frigg', stage },
67
54
  });
@@ -119,19 +119,7 @@ class TokenRepositoryDocumentDB extends TokenRepositoryInterface {
119
119
 
120
120
  getJSONTokenFromBase64BufferToken(buffer) {
121
121
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
122
- let jsonToken;
123
- try {
124
- jsonToken = JSON.parse(tokenStr);
125
- } catch {
126
- jsonToken = null;
127
- }
128
- if (
129
- !['string', 'number'].includes(typeof jsonToken?.id) ||
130
- typeof jsonToken?.token !== 'string'
131
- ) {
132
- throw new ClientSafeError('Invalid Token: Token is malformed', 401);
133
- }
134
- return jsonToken;
122
+ return JSON.parse(tokenStr);
135
123
  }
136
124
 
137
125
  _mapToken(record) {
@@ -212,19 +212,7 @@ class TokenRepositoryMongo extends TokenRepositoryInterface {
212
212
  */
213
213
  getJSONTokenFromBase64BufferToken(buffer) {
214
214
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
215
- let jsonToken;
216
- try {
217
- jsonToken = JSON.parse(tokenStr);
218
- } catch {
219
- jsonToken = null;
220
- }
221
- if (
222
- !['string', 'number'].includes(typeof jsonToken?.id) ||
223
- typeof jsonToken?.token !== 'string'
224
- ) {
225
- throw new ClientSafeError('Invalid Token: Token is malformed', 401);
226
- }
227
- return jsonToken;
215
+ return JSON.parse(tokenStr);
228
216
  }
229
217
  }
230
218
 
@@ -257,19 +257,7 @@ class TokenRepositoryPostgres extends TokenRepositoryInterface {
257
257
  */
258
258
  getJSONTokenFromBase64BufferToken(buffer) {
259
259
  const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
260
- let jsonToken;
261
- try {
262
- jsonToken = JSON.parse(tokenStr);
263
- } catch {
264
- jsonToken = null;
265
- }
266
- if (
267
- !['string', 'number'].includes(typeof jsonToken?.id) ||
268
- typeof jsonToken?.token !== 'string'
269
- ) {
270
- throw new ClientSafeError('Invalid Token: Token is malformed', 401);
271
- }
272
- return jsonToken;
260
+ return JSON.parse(tokenStr);
273
261
  }
274
262
  }
275
263
 
@@ -1,5 +1,10 @@
1
1
  declare module "@friggframework/core" {
2
2
  import type { SendMessageCommandInput } from "@aws-sdk/client-sqs";
3
+ import type { RateLimitHint } from "@friggframework/errors";
4
+ import type {
5
+ RateLimitPolicy,
6
+ RateLimitSignal,
7
+ } from "@friggframework/module-plugin";
3
8
 
4
9
  export class Delegate implements IFriggDelegate {
5
10
  delegate: any;
@@ -53,6 +58,34 @@ declare module "@friggframework/core" {
53
58
 
54
59
  export function loadInstalledModules(): any[];
55
60
 
61
+ export function runWithInvocationDeadline<T>(
62
+ limits: { deadlineAt?: number; maxInProcessWaitMs?: number },
63
+ fn: () => T
64
+ ): T;
65
+
66
+ export function remainingInvocationMs(now?: number): number;
67
+
68
+ export function classifyRateLimit(
69
+ policy: RateLimitPolicy | undefined,
70
+ signal: RateLimitSignal,
71
+ options?: { now?: number; onClassifyError?: (error: Error) => void }
72
+ ): RateLimitHint | null;
73
+
74
+ export function parseRetryAfter(
75
+ value: string | null | undefined,
76
+ options?: { now?: number }
77
+ ): RateLimitHint | null;
78
+
79
+ export function parseResetHeaders(
80
+ headers: object | undefined,
81
+ options?: { now?: number }
82
+ ): RateLimitHint | null;
83
+
84
+ export function parseIetfRateLimit(
85
+ headers: object | undefined,
86
+ options?: { now?: number }
87
+ ): RateLimitHint | null;
88
+
56
89
  type GetQueueURLParams = {
57
90
  QueueName: string;
58
91
  QueueOwnerAWSAccountId?: string;
@@ -16,10 +16,57 @@ declare module "@friggframework/errors" {
16
16
  readonly body: any;
17
17
  isTimeout?: boolean;
18
18
  timeoutMs?: number;
19
+ isRateLimited?: boolean;
20
+ reason?: RateLimitReason;
19
21
 
20
22
  static create(options?: CreateFetchErrorParams): Promise<FetchError>;
21
23
  }
22
24
 
25
+ export type RateLimitReason =
26
+ | "burst"
27
+ | "daily"
28
+ | "monthly"
29
+ | "concurrency"
30
+ | "unknown";
31
+
32
+ export type RateLimitSource = "header" | "body" | "static" | "backoff";
33
+
34
+ export type RateLimitHint = {
35
+ retryAt: Date;
36
+ waitMs: number;
37
+ reason: RateLimitReason;
38
+ policy?: string;
39
+ remaining?: number;
40
+ source: RateLimitSource;
41
+ };
42
+
43
+ export class RateLimitError extends FetchError {
44
+ constructor(options?: RateLimitErrorConstructor);
45
+
46
+ isRateLimited: true;
47
+ retryAt?: Date;
48
+ waitMs?: number;
49
+ reason: RateLimitReason;
50
+ policy?: string;
51
+ source: RateLimitSource | "unknown";
52
+ module?: string;
53
+ scopeKey?: string;
54
+
55
+ static create(
56
+ options?: CreateRateLimitErrorParams
57
+ ): Promise<RateLimitError>;
58
+ }
59
+
60
+ type RateLimitErrorConstructor = FetchErrorConstructor & {
61
+ hint?: Partial<RateLimitHint>;
62
+ waitMs?: number;
63
+ module?: string;
64
+ scopeKey?: string;
65
+ now?: number;
66
+ };
67
+
68
+ type CreateRateLimitErrorParams = RateLimitErrorConstructor;
69
+
23
70
  type FetchErrorResponse = {
24
71
  headers?: object;
25
72
  status?: number;
@@ -1,5 +1,6 @@
1
1
  declare module "@friggframework/module-plugin" {
2
2
  import { Delegate, IFriggDelegate } from "@friggframework/core";
3
+ import type { RateLimitHint } from "@friggframework/errors";
3
4
 
4
5
  export interface Credential {
5
6
  id?: string;
@@ -22,8 +23,49 @@ declare module "@friggframework/module-plugin" {
22
23
  export type MappedEntity = Entity & { id: string; type: any };
23
24
 
24
25
 
26
+ export type RateLimitScope =
27
+ | "credential"
28
+ | "entity"
29
+ | "app"
30
+ | ((requester: Requester) => string | number | null | undefined);
31
+
32
+ export type RateLimitSignal = {
33
+ status?: number;
34
+ headers?: { get(name: string): string | null } | object;
35
+ body?: unknown;
36
+ };
37
+
38
+ export type RateLimitWindow = {
39
+ name: string;
40
+ limit?: number;
41
+ perMs?: number;
42
+ rollingMs?: number;
43
+ resets?: { at: string; tz: string };
44
+ };
45
+
46
+ export type RateLimitPolicy = {
47
+ scope?: RateLimitScope;
48
+ windows?: RateLimitWindow[];
49
+ maxConcurrency?: number;
50
+ minRetryAfterMs?: number;
51
+ parsers?: Array<"retryAfter" | "resetHeaders" | "ietf">;
52
+ classify?(
53
+ signal: RateLimitSignal
54
+ ): Partial<Omit<RateLimitHint, "source">> & {
55
+ source?: "header" | "body" | "static";
56
+ } | null | undefined;
57
+ userHints?: Record<
58
+ string,
59
+ { links?: Array<{ label: string; url: string }> }
60
+ >;
61
+ };
62
+
25
63
  export class Requester implements IFriggRequester {
64
+ static rateLimit?: RateLimitPolicy;
65
+ static requestTimeoutMs?: number;
66
+
26
67
  DLGT_INVALID_AUTH: string;
68
+ requestTimeoutMs: number;
27
69
  backOff: number[];
28
70
  fetch: any;
29
71
  isRefreshable: boolean;
@@ -87,6 +129,7 @@ declare module "@friggframework/module-plugin" {
87
129
  type RequesterConstructor = {
88
130
  backOff?: number[];
89
131
  fetch?: any;
132
+ random?: () => number;
90
133
  };
91
134
 
92
135
  export class ApiKeyRequester
@@ -23,7 +23,7 @@ class TestUserRepository {
23
23
 
24
24
  async createToken(userId, rawToken, minutes = 120) {
25
25
  const token = `token-for-${userId}-for-${minutes}-mins`;
26
- this.tokens.set(token, { id: token, userId, rawToken });
26
+ this.tokens.set(token, { user: userId, rawToken });
27
27
  return token;
28
28
  }
29
29
 
@@ -1,16 +1,13 @@
1
1
  const Boom = require('@hapi/boom');
2
- const { getLogger } = require('../../logs');
3
-
4
- const log = getLogger('frigg.user.authentication');
5
2
 
6
3
  /**
7
4
  * Use case for authenticating a user using multiple authentication strategies.
8
- *
5
+ *
9
6
  * Supports three authentication modes in priority order:
10
7
  * 1. Shared Secret (backend-to-backend with x-frigg-api-key + x-frigg headers)
11
8
  * 2. Adopter JWT (custom JWT authentication)
12
9
  * 3. Frigg Native Token (bearer token from /user/login)
13
- *
10
+ *
14
11
  * x-frigg-appUserId and x-frigg-appOrgId headers are automatically supported
15
12
  * for user identification with any auth mode. When present with JWT or Frigg
16
13
  * tokens, they are validated to match the authenticated user.
@@ -53,18 +50,12 @@ class AuthenticateUser {
53
50
  const authModes = this.userConfig.authModes || { friggToken: true };
54
51
  const appUserId = req.headers['x-frigg-appuserid'];
55
52
  const appOrgId = req.headers['x-frigg-apporgid'];
56
- log.debug('Request headers received', {
57
- eventName: `${log.name}.headers_received`,
58
- headerNames: Object.keys(req.headers),
59
- });
53
+ let user = null;
60
54
 
61
55
  // Priority 1: Shared Secret (backend-to-backend with API key)
62
56
  if (authModes.sharedSecret !== false) {
63
57
  const apiKey = req.headers['x-frigg-api-key'];
64
58
  if (apiKey) {
65
- log.debug('Attempting shared secret authentication', {
66
- eventName: `${log.name}.shared_secret_attempted`,
67
- });
68
59
  // Validate the API key (authentication)
69
60
  await this.authenticateWithSharedSecret.execute(apiKey);
70
61
  // Get user from x-frigg headers (authorization)
@@ -73,9 +64,6 @@ class AuthenticateUser {
73
64
  appOrgId
74
65
  );
75
66
  }
76
- log.debug('No x-frigg-api-key header, skipping shared secret', {
77
- eventName: `${log.name}.shared_secret_skipped`,
78
- });
79
67
  }
80
68
 
81
69
  // Priority 2: Adopter JWT (if enabled)
@@ -83,13 +71,10 @@ class AuthenticateUser {
83
71
  authModes.adopterJwt === true &&
84
72
  req.headers.authorization?.startsWith('Bearer ')
85
73
  ) {
86
- log.debug('Attempting adopter JWT authentication', {
87
- eventName: `${log.name}.adopter_jwt_attempted`,
88
- });
89
74
  const token = req.headers.authorization.split(' ')[1];
90
75
  // Detect JWT format (3 parts separated by dots)
91
76
  if (token && token.split('.').length === 3) {
92
- const user = await this.getUserFromAdopterJwt.execute(token);
77
+ user = await this.getUserFromAdopterJwt.execute(token);
93
78
  // Validate x-frigg headers match JWT claims if present
94
79
  if (appUserId || appOrgId) {
95
80
  this.validateUserMatch(user, appUserId, appOrgId);
@@ -100,10 +85,7 @@ class AuthenticateUser {
100
85
 
101
86
  // Priority 3: Frigg native token (default)
102
87
  if (authModes.friggToken !== false && req.headers.authorization) {
103
- log.debug('Attempting Frigg native token authentication', {
104
- eventName: `${log.name}.frigg_token_attempted`,
105
- });
106
- const user = await this.getUserFromBearerToken.execute(
88
+ user = await this.getUserFromBearerToken.execute(
107
89
  req.headers.authorization
108
90
  );
109
91
  // Validate x-frigg headers match token user if present
@@ -141,3 +123,5 @@ class AuthenticateUser {
141
123
  }
142
124
 
143
125
  module.exports = { AuthenticateUser };
126
+
127
+
@@ -40,13 +40,8 @@ class GetUserFromBearerToken {
40
40
  throw Boom.unauthorized('Session Token Not Found');
41
41
  }
42
42
 
43
- const tokenUserId = sessionToken.userId;
44
- if (!tokenUserId) {
45
- throw Boom.unauthorized('Session Token Has No User');
46
- }
47
-
48
43
  if (this.userConfig.primary === 'organization') {
49
- const organizationUserData = await this.userRepository.findOrganizationUserById(tokenUserId);
44
+ const organizationUserData = await this.userRepository.findOrganizationUserById(sessionToken.user);
50
45
 
51
46
  if (!organizationUserData) {
52
47
  throw Boom.unauthorized('Organization User Not Found');
@@ -62,7 +57,7 @@ class GetUserFromBearerToken {
62
57
  );
63
58
  }
64
59
 
65
- const individualUserData = await this.userRepository.findIndividualUserById(tokenUserId);
60
+ const individualUserData = await this.userRepository.findIndividualUserById(sessionToken.user);
66
61
 
67
62
  if (!individualUserData) {
68
63
  throw Boom.unauthorized('Individual User Not Found');
@@ -1,24 +0,0 @@
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 };
@@ -1,14 +0,0 @@
1
- const { BaseError } = require('./base-error');
2
-
3
- class MappingAlreadyExistsError extends BaseError {
4
- constructor(integrationId, sourceId, ...errorOptions) {
5
- super(
6
- `Mapping already exists for integration ${integrationId} and sourceId ${sourceId}`,
7
- ...errorOptions
8
- );
9
- this.integrationId = integrationId;
10
- this.sourceId = sourceId;
11
- }
12
- }
13
-
14
- module.exports = { MappingAlreadyExistsError };