@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.
- package/CLAUDE.md +48 -93
- package/application/commands/README.md +17 -11
- package/application/commands/entity-commands.js +18 -60
- package/application/commands/integration-commands.js +63 -0
- package/core/CLAUDE.md +1 -33
- package/core/Worker.js +11 -317
- package/core/create-handler.js +0 -3
- package/core/index.js +0 -6
- package/core/invocation-scope.js +24 -30
- package/database/documentdb-encryption-service.js +2 -33
- package/database/documentdb-utils.js +4 -1
- package/database/encryption/README.md +3 -3
- package/database/encryption/ciphertext-format.js +24 -0
- package/database/encryption/encryption-schema-registry.js +109 -29
- package/database/encryption/field-encryption-service.js +55 -16
- package/database/encryption/prisma-encryption-extension.js +6 -9
- package/database/prisma.js +10 -1
- package/encrypt/Cryptor.js +90 -38
- package/errors/fetch-error.js +18 -11
- package/errors/index.js +4 -2
- package/errors/mapping-already-exists-error.js +14 -0
- package/generated/prisma-mongodb/edge.js +6 -2
- package/generated/prisma-mongodb/index.js +10 -2
- package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +1 -1
- package/generated/prisma-mongodb/wasm.js +6 -2
- package/generated/prisma-postgresql/edge.js +6 -2
- package/generated/prisma-postgresql/index.js +10 -2
- package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +1 -1
- package/generated/prisma-postgresql/wasm.js +6 -2
- package/handlers/WEBHOOKS.md +29 -0
- package/handlers/app-definition-loader.js +9 -2
- package/handlers/app-handler-helpers.js +12 -1
- package/handlers/backend-utils.js +1 -30
- package/handlers/workers/integration-defined-workers.js +0 -2
- package/index.js +2 -18
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -15
- package/integrations/integration-base.js +52 -9
- package/integrations/integration-router.js +30 -22
- package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
- package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
- package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
- package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
- package/integrations/repositories/integration-mapping-repository.js +29 -0
- package/integrations/repositories/integration-repository-documentdb.js +32 -0
- package/integrations/repositories/integration-repository-interface.js +30 -0
- package/integrations/repositories/integration-repository-mongo.js +53 -1
- package/integrations/repositories/integration-repository-postgres.js +58 -0
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/add-entities-to-integration.js +92 -0
- package/integrations/use-cases/create-integration.js +57 -19
- package/integrations/use-cases/delete-integration-for-user.js +8 -11
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/index.js +1 -5
- package/integrations/use-cases/remove-entities-from-integration.js +70 -0
- package/integrations/use-cases/update-integration.js +12 -12
- package/integrations/utils/assert-entity-ids-input.js +42 -0
- package/jest-setup.js +13 -2
- package/jest-teardown.js +5 -2
- package/jest.config.js +4 -0
- package/jest.db.config.js +23 -0
- package/logs/serialize.js +0 -15
- package/modules/requester/oauth-2.js +0 -7
- package/modules/requester/requester.js +9 -187
- package/modules/use-cases/create-entity-from-credential.js +105 -0
- package/modules/use-cases/get-entity-options-by-id.js +7 -5
- package/modules/use-cases/get-module.js +29 -8
- package/modules/use-cases/process-authorization-callback.js +78 -27
- package/modules/use-cases/refresh-entity-options.js +7 -5
- package/modules/use-cases/test-module-auth.js +7 -5
- package/modules/utils/find-module-definition.js +23 -0
- package/modules/utils/map-module-dto.js +5 -3
- package/modules/utils/to-credential-id.js +14 -0
- package/package.json +9 -8
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queue-delivery.js +0 -1
- package/queues/queuer-util.js +10 -8
- package/queues/sqs-message-body.js +17 -0
- package/telemetry/otel-telemetry.js +76 -3
- package/telemetry/telemetry-config.js +16 -5
- package/telemetry/telemetry-runtime.js +14 -1
- package/token/repositories/token-repository-documentdb.js +13 -1
- package/token/repositories/token-repository-mongo.js +13 -1
- package/token/repositories/token-repository-postgres.js +13 -1
- package/types/core/index.d.ts +0 -52
- package/types/errors/index.d.ts +0 -47
- package/types/module-plugin/index.d.ts +0 -43
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +23 -7
- package/user/use-cases/get-user-from-bearer-token.js +7 -2
- package/core/invocation-deadline.js +0 -91
- package/errors/rate-limit-error.js +0 -46
- package/integrations/use-cases/clear-rate-limit-wait.js +0 -28
- package/integrations/use-cases/record-rate-limit-wait.js +0 -36
- package/modules/requester/rate-limit/index.js +0 -4
- package/modules/requester/rate-limit/parsers.js +0 -245
- package/modules/requester/rate-limit/policy.js +0 -304
- package/queues/queue-deferral.js +0 -74
|
@@ -16,6 +16,7 @@ const { createTelemetryEventBus } = require('./telemetry-event-bus');
|
|
|
16
16
|
const {
|
|
17
17
|
runWithTelemetryContext,
|
|
18
18
|
mergeTelemetryContext,
|
|
19
|
+
getTelemetryContextStore,
|
|
19
20
|
} = require('./telemetry-context');
|
|
20
21
|
const { serializeError } = require('../logs/serialize');
|
|
21
22
|
const { LOGGER_SCOPE_KEY } = require('../logs/context');
|
|
@@ -27,6 +28,74 @@ const TRACER_NAME = 'frigg';
|
|
|
27
28
|
const METRIC_EXPORT_INTERVAL_MS =
|
|
28
29
|
Number(process.env.OTEL_METRIC_EXPORT_INTERVAL_MS) || 60000;
|
|
29
30
|
|
|
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
|
+
|
|
30
99
|
/**
|
|
31
100
|
* Register an AsyncLocalStorage-backed OTel context manager once per process.
|
|
32
101
|
* Without it `BasicTracerProvider` uses the Noop context manager, so
|
|
@@ -83,12 +152,16 @@ class OtelTelemetry {
|
|
|
83
152
|
})
|
|
84
153
|
: new AlwaysOnSampler();
|
|
85
154
|
|
|
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
|
+
}
|
|
86
161
|
this._tracerProvider = new BasicTracerProvider({
|
|
87
162
|
resource: res,
|
|
88
163
|
sampler,
|
|
89
|
-
spanProcessors
|
|
90
|
-
? [new BatchSpanProcessor(traceExporter)]
|
|
91
|
-
: [],
|
|
164
|
+
spanProcessors,
|
|
92
165
|
});
|
|
93
166
|
|
|
94
167
|
const metricReader = metricExporter
|
|
@@ -3,11 +3,14 @@
|
|
|
3
3
|
* into a normalized config the TelemetryService and
|
|
4
4
|
* usage rollup consume: `{ exporter, northStar, sampleRatio }`.
|
|
5
5
|
*
|
|
6
|
-
* Exporter default
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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.
|
|
11
14
|
*/
|
|
12
15
|
const VALID_EXPORTER_TYPES = [
|
|
13
16
|
'none',
|
|
@@ -18,8 +21,16 @@ const VALID_EXPORTER_TYPES = [
|
|
|
18
21
|
'datadog',
|
|
19
22
|
];
|
|
20
23
|
|
|
24
|
+
function hasOtlpEndpointEnv() {
|
|
25
|
+
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
|
26
|
+
return typeof endpoint === 'string' && endpoint.trim().length > 0;
|
|
27
|
+
}
|
|
28
|
+
|
|
21
29
|
function normalizeExporterConfig(exporter, stage) {
|
|
22
30
|
if (!exporter) {
|
|
31
|
+
if (hasOtlpEndpointEnv()) {
|
|
32
|
+
return { type: 'otlp' };
|
|
33
|
+
}
|
|
23
34
|
return stage === 'local' ? { type: 'console' } : { type: 'none' };
|
|
24
35
|
}
|
|
25
36
|
|
|
@@ -47,8 +47,21 @@ 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
|
+
}
|
|
50
63
|
state.telemetry = createTelemetry({
|
|
51
|
-
exporter
|
|
64
|
+
exporter,
|
|
52
65
|
sampleRatio: telemetry.sampleRatio,
|
|
53
66
|
resource: { service: process.env.FRIGG_STACK || 'frigg', stage },
|
|
54
67
|
});
|
|
@@ -119,7 +119,19 @@ class TokenRepositoryDocumentDB extends TokenRepositoryInterface {
|
|
|
119
119
|
|
|
120
120
|
getJSONTokenFromBase64BufferToken(buffer) {
|
|
121
121
|
const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
|
|
122
|
-
|
|
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;
|
|
123
135
|
}
|
|
124
136
|
|
|
125
137
|
_mapToken(record) {
|
|
@@ -212,7 +212,19 @@ class TokenRepositoryMongo extends TokenRepositoryInterface {
|
|
|
212
212
|
*/
|
|
213
213
|
getJSONTokenFromBase64BufferToken(buffer) {
|
|
214
214
|
const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
|
|
215
|
-
|
|
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;
|
|
216
228
|
}
|
|
217
229
|
}
|
|
218
230
|
|
|
@@ -257,7 +257,19 @@ class TokenRepositoryPostgres extends TokenRepositoryInterface {
|
|
|
257
257
|
*/
|
|
258
258
|
getJSONTokenFromBase64BufferToken(buffer) {
|
|
259
259
|
const tokenStr = Buffer.from(buffer.trim(), 'base64').toString('ascii');
|
|
260
|
-
|
|
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;
|
|
261
273
|
}
|
|
262
274
|
}
|
|
263
275
|
|
package/types/core/index.d.ts
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
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";
|
|
8
3
|
|
|
9
4
|
export class Delegate implements IFriggDelegate {
|
|
10
5
|
delegate: any;
|
|
@@ -47,27 +42,8 @@ declare module "@friggframework/core" {
|
|
|
47
42
|
send(params: object & { QueueUrl: any }, delay?: number): Promise<string>;
|
|
48
43
|
|
|
49
44
|
sendAsyncSQSMessage(params: SendSQSMessageParams): Promise<string>;
|
|
50
|
-
|
|
51
|
-
recordRateLimitWait(
|
|
52
|
-
body: object,
|
|
53
|
-
error: Error,
|
|
54
|
-
state: RateLimitWaitState
|
|
55
|
-
): Promise<void>;
|
|
56
|
-
|
|
57
|
-
clearRateLimitWait(
|
|
58
|
-
body: object,
|
|
59
|
-
options?: { deferralId?: string }
|
|
60
|
-
): Promise<void>;
|
|
61
45
|
}
|
|
62
46
|
|
|
63
|
-
export type RateLimitWaitState = {
|
|
64
|
-
status: "WAITING" | "EXHAUSTED";
|
|
65
|
-
mechanism: "delay" | "schedule" | "visibility" | "none";
|
|
66
|
-
deferrals: number;
|
|
67
|
-
deferralId?: string;
|
|
68
|
-
retryAt: Date;
|
|
69
|
-
};
|
|
70
|
-
|
|
71
47
|
interface IWorker {
|
|
72
48
|
getQueueURL(params: GetQueueURLParams): Promise<string | undefined>;
|
|
73
49
|
run(params: { Records: any }, context?: object): Promise<BatchItemFailuresResponse>;
|
|
@@ -77,34 +53,6 @@ declare module "@friggframework/core" {
|
|
|
77
53
|
|
|
78
54
|
export function loadInstalledModules(): any[];
|
|
79
55
|
|
|
80
|
-
export function runWithInvocationDeadline<T>(
|
|
81
|
-
limits: { deadlineAt?: number; maxInProcessWaitMs?: number },
|
|
82
|
-
fn: () => T
|
|
83
|
-
): T;
|
|
84
|
-
|
|
85
|
-
export function remainingInvocationMs(now?: number): number;
|
|
86
|
-
|
|
87
|
-
export function classifyRateLimit(
|
|
88
|
-
policy: RateLimitPolicy | undefined,
|
|
89
|
-
signal: RateLimitSignal,
|
|
90
|
-
options?: { now?: number; onClassifyError?: (error: Error) => void }
|
|
91
|
-
): RateLimitHint | null;
|
|
92
|
-
|
|
93
|
-
export function parseRetryAfter(
|
|
94
|
-
value: string | null | undefined,
|
|
95
|
-
options?: { now?: number }
|
|
96
|
-
): RateLimitHint | null;
|
|
97
|
-
|
|
98
|
-
export function parseResetHeaders(
|
|
99
|
-
headers: object | undefined,
|
|
100
|
-
options?: { now?: number }
|
|
101
|
-
): RateLimitHint | null;
|
|
102
|
-
|
|
103
|
-
export function parseIetfRateLimit(
|
|
104
|
-
headers: object | undefined,
|
|
105
|
-
options?: { now?: number }
|
|
106
|
-
): RateLimitHint | null;
|
|
107
|
-
|
|
108
56
|
type GetQueueURLParams = {
|
|
109
57
|
QueueName: string;
|
|
110
58
|
QueueOwnerAWSAccountId?: string;
|
package/types/errors/index.d.ts
CHANGED
|
@@ -16,57 +16,10 @@ declare module "@friggframework/errors" {
|
|
|
16
16
|
readonly body: any;
|
|
17
17
|
isTimeout?: boolean;
|
|
18
18
|
timeoutMs?: number;
|
|
19
|
-
isRateLimited?: boolean;
|
|
20
|
-
reason?: RateLimitReason;
|
|
21
19
|
|
|
22
20
|
static create(options?: CreateFetchErrorParams): Promise<FetchError>;
|
|
23
21
|
}
|
|
24
22
|
|
|
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
|
-
|
|
70
23
|
type FetchErrorResponse = {
|
|
71
24
|
headers?: object;
|
|
72
25
|
status?: number;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
declare module "@friggframework/module-plugin" {
|
|
2
2
|
import { Delegate, IFriggDelegate } from "@friggframework/core";
|
|
3
|
-
import type { RateLimitHint } from "@friggframework/errors";
|
|
4
3
|
|
|
5
4
|
export interface Credential {
|
|
6
5
|
id?: string;
|
|
@@ -23,49 +22,8 @@ declare module "@friggframework/module-plugin" {
|
|
|
23
22
|
export type MappedEntity = Entity & { id: string; type: any };
|
|
24
23
|
|
|
25
24
|
|
|
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
|
-
|
|
63
25
|
export class Requester implements IFriggRequester {
|
|
64
|
-
static rateLimit?: RateLimitPolicy;
|
|
65
|
-
static requestTimeoutMs?: number;
|
|
66
|
-
|
|
67
26
|
DLGT_INVALID_AUTH: string;
|
|
68
|
-
requestTimeoutMs: number;
|
|
69
27
|
backOff: number[];
|
|
70
28
|
fetch: any;
|
|
71
29
|
isRefreshable: boolean;
|
|
@@ -129,7 +87,6 @@ declare module "@friggframework/module-plugin" {
|
|
|
129
87
|
type RequesterConstructor = {
|
|
130
88
|
backOff?: number[];
|
|
131
89
|
fetch?: any;
|
|
132
|
-
random?: () => number;
|
|
133
90
|
};
|
|
134
91
|
|
|
135
92
|
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, {
|
|
26
|
+
this.tokens.set(token, { id: token, userId, rawToken });
|
|
27
27
|
return token;
|
|
28
28
|
}
|
|
29
29
|
|
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
const Boom = require('@hapi/boom');
|
|
2
|
+
const { getLogger } = require('../../logs');
|
|
3
|
+
|
|
4
|
+
const log = getLogger('frigg.user.authentication');
|
|
2
5
|
|
|
3
6
|
/**
|
|
4
7
|
* Use case for authenticating a user using multiple authentication strategies.
|
|
5
|
-
*
|
|
8
|
+
*
|
|
6
9
|
* Supports three authentication modes in priority order:
|
|
7
10
|
* 1. Shared Secret (backend-to-backend with x-frigg-api-key + x-frigg headers)
|
|
8
11
|
* 2. Adopter JWT (custom JWT authentication)
|
|
9
12
|
* 3. Frigg Native Token (bearer token from /user/login)
|
|
10
|
-
*
|
|
13
|
+
*
|
|
11
14
|
* x-frigg-appUserId and x-frigg-appOrgId headers are automatically supported
|
|
12
15
|
* for user identification with any auth mode. When present with JWT or Frigg
|
|
13
16
|
* tokens, they are validated to match the authenticated user.
|
|
@@ -50,12 +53,18 @@ class AuthenticateUser {
|
|
|
50
53
|
const authModes = this.userConfig.authModes || { friggToken: true };
|
|
51
54
|
const appUserId = req.headers['x-frigg-appuserid'];
|
|
52
55
|
const appOrgId = req.headers['x-frigg-apporgid'];
|
|
53
|
-
|
|
56
|
+
log.debug('Request headers received', {
|
|
57
|
+
eventName: `${log.name}.headers_received`,
|
|
58
|
+
headerNames: Object.keys(req.headers),
|
|
59
|
+
});
|
|
54
60
|
|
|
55
61
|
// Priority 1: Shared Secret (backend-to-backend with API key)
|
|
56
62
|
if (authModes.sharedSecret !== false) {
|
|
57
63
|
const apiKey = req.headers['x-frigg-api-key'];
|
|
58
64
|
if (apiKey) {
|
|
65
|
+
log.debug('Attempting shared secret authentication', {
|
|
66
|
+
eventName: `${log.name}.shared_secret_attempted`,
|
|
67
|
+
});
|
|
59
68
|
// Validate the API key (authentication)
|
|
60
69
|
await this.authenticateWithSharedSecret.execute(apiKey);
|
|
61
70
|
// Get user from x-frigg headers (authorization)
|
|
@@ -64,6 +73,9 @@ class AuthenticateUser {
|
|
|
64
73
|
appOrgId
|
|
65
74
|
);
|
|
66
75
|
}
|
|
76
|
+
log.debug('No x-frigg-api-key header, skipping shared secret', {
|
|
77
|
+
eventName: `${log.name}.shared_secret_skipped`,
|
|
78
|
+
});
|
|
67
79
|
}
|
|
68
80
|
|
|
69
81
|
// Priority 2: Adopter JWT (if enabled)
|
|
@@ -71,10 +83,13 @@ class AuthenticateUser {
|
|
|
71
83
|
authModes.adopterJwt === true &&
|
|
72
84
|
req.headers.authorization?.startsWith('Bearer ')
|
|
73
85
|
) {
|
|
86
|
+
log.debug('Attempting adopter JWT authentication', {
|
|
87
|
+
eventName: `${log.name}.adopter_jwt_attempted`,
|
|
88
|
+
});
|
|
74
89
|
const token = req.headers.authorization.split(' ')[1];
|
|
75
90
|
// Detect JWT format (3 parts separated by dots)
|
|
76
91
|
if (token && token.split('.').length === 3) {
|
|
77
|
-
user = await this.getUserFromAdopterJwt.execute(token);
|
|
92
|
+
const user = await this.getUserFromAdopterJwt.execute(token);
|
|
78
93
|
// Validate x-frigg headers match JWT claims if present
|
|
79
94
|
if (appUserId || appOrgId) {
|
|
80
95
|
this.validateUserMatch(user, appUserId, appOrgId);
|
|
@@ -85,7 +100,10 @@ class AuthenticateUser {
|
|
|
85
100
|
|
|
86
101
|
// Priority 3: Frigg native token (default)
|
|
87
102
|
if (authModes.friggToken !== false && req.headers.authorization) {
|
|
88
|
-
|
|
103
|
+
log.debug('Attempting Frigg native token authentication', {
|
|
104
|
+
eventName: `${log.name}.frigg_token_attempted`,
|
|
105
|
+
});
|
|
106
|
+
const user = await this.getUserFromBearerToken.execute(
|
|
89
107
|
req.headers.authorization
|
|
90
108
|
);
|
|
91
109
|
// Validate x-frigg headers match token user if present
|
|
@@ -123,5 +141,3 @@ class AuthenticateUser {
|
|
|
123
141
|
}
|
|
124
142
|
|
|
125
143
|
module.exports = { AuthenticateUser };
|
|
126
|
-
|
|
127
|
-
|
|
@@ -40,8 +40,13 @@ 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
|
+
|
|
43
48
|
if (this.userConfig.primary === 'organization') {
|
|
44
|
-
const organizationUserData = await this.userRepository.findOrganizationUserById(
|
|
49
|
+
const organizationUserData = await this.userRepository.findOrganizationUserById(tokenUserId);
|
|
45
50
|
|
|
46
51
|
if (!organizationUserData) {
|
|
47
52
|
throw Boom.unauthorized('Organization User Not Found');
|
|
@@ -57,7 +62,7 @@ class GetUserFromBearerToken {
|
|
|
57
62
|
);
|
|
58
63
|
}
|
|
59
64
|
|
|
60
|
-
const individualUserData = await this.userRepository.findIndividualUserById(
|
|
65
|
+
const individualUserData = await this.userRepository.findIndividualUserById(tokenUserId);
|
|
61
66
|
|
|
62
67
|
if (!individualUserData) {
|
|
63
68
|
throw Boom.unauthorized('Individual User Not Found');
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
const { AsyncLocalStorage } = require('node:async_hooks');
|
|
2
|
-
|
|
3
|
-
const STORE_KEY = Symbol.for('@friggframework/core.invocation-deadline');
|
|
4
|
-
|
|
5
|
-
function storage() {
|
|
6
|
-
if (!globalThis[STORE_KEY]) {
|
|
7
|
-
globalThis[STORE_KEY] = new AsyncLocalStorage();
|
|
8
|
-
}
|
|
9
|
-
return globalThis[STORE_KEY];
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
const MAX_IN_PROCESS_WAIT_MS = Object.freeze({
|
|
13
|
-
outsideInvocation: 300_000,
|
|
14
|
-
http: 10_000,
|
|
15
|
-
queueWorker: 60_000,
|
|
16
|
-
});
|
|
17
|
-
|
|
18
|
-
const validDeadline = (value) =>
|
|
19
|
-
typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
20
|
-
|
|
21
|
-
const validWait = (value) =>
|
|
22
|
-
typeof value === 'number' && Number.isFinite(value) && value >= 0
|
|
23
|
-
? value
|
|
24
|
-
: undefined;
|
|
25
|
-
|
|
26
|
-
const lower = (outer, next) =>
|
|
27
|
-
outer === undefined
|
|
28
|
-
? next
|
|
29
|
-
: next === undefined
|
|
30
|
-
? outer
|
|
31
|
-
: Math.min(outer, next);
|
|
32
|
-
|
|
33
|
-
function runWithInvocationDeadline(
|
|
34
|
-
{ deadlineAt, maxInProcessWaitMs } = {},
|
|
35
|
-
fn
|
|
36
|
-
) {
|
|
37
|
-
const outer = storage().getStore();
|
|
38
|
-
const effectiveDeadline = lower(
|
|
39
|
-
outer?.deadlineAt,
|
|
40
|
-
validDeadline(deadlineAt)
|
|
41
|
-
);
|
|
42
|
-
const effectiveWait = lower(
|
|
43
|
-
outer?.maxInProcessWaitMs,
|
|
44
|
-
validWait(maxInProcessWaitMs)
|
|
45
|
-
);
|
|
46
|
-
if (effectiveDeadline === undefined && effectiveWait === undefined) {
|
|
47
|
-
return fn();
|
|
48
|
-
}
|
|
49
|
-
return storage().run(
|
|
50
|
-
Object.freeze({
|
|
51
|
-
deadlineAt: effectiveDeadline ?? Infinity,
|
|
52
|
-
maxInProcessWaitMs: effectiveWait,
|
|
53
|
-
}),
|
|
54
|
-
fn
|
|
55
|
-
);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function remainingTimeMs(context) {
|
|
59
|
-
try {
|
|
60
|
-
const remaining = context?.getRemainingTimeInMillis?.();
|
|
61
|
-
return typeof remaining === 'number' ? remaining : Infinity;
|
|
62
|
-
} catch (_) {
|
|
63
|
-
return Infinity;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function deadlineFromContext(context) {
|
|
68
|
-
const remaining = remainingTimeMs(context);
|
|
69
|
-
return Number.isFinite(remaining) ? Date.now() + remaining : undefined;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
function remainingInvocationMs(now = Date.now()) {
|
|
73
|
-
const store = storage().getStore();
|
|
74
|
-
return store ? Math.max(0, store.deadlineAt - now) : Infinity;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function invocationMaxInProcessWaitMs() {
|
|
78
|
-
return (
|
|
79
|
-
storage().getStore()?.maxInProcessWaitMs ??
|
|
80
|
-
MAX_IN_PROCESS_WAIT_MS.outsideInvocation
|
|
81
|
-
);
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
module.exports = {
|
|
85
|
-
MAX_IN_PROCESS_WAIT_MS,
|
|
86
|
-
deadlineFromContext,
|
|
87
|
-
invocationMaxInProcessWaitMs,
|
|
88
|
-
remainingInvocationMs,
|
|
89
|
-
remainingTimeMs,
|
|
90
|
-
runWithInvocationDeadline,
|
|
91
|
-
};
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
const { FetchError } = require('./fetch-error');
|
|
2
|
-
|
|
3
|
-
function resolveTiming({ hint, waitMs, now }) {
|
|
4
|
-
if (waitMs !== undefined) {
|
|
5
|
-
return { waitMs, retryAt: new Date(now + waitMs) };
|
|
6
|
-
}
|
|
7
|
-
if (hint?.retryAt) {
|
|
8
|
-
const retryAt = new Date(hint.retryAt);
|
|
9
|
-
if (!Number.isNaN(retryAt.getTime())) {
|
|
10
|
-
return { waitMs: Math.max(0, retryAt.getTime() - now), retryAt };
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
if (hint?.waitMs !== undefined) {
|
|
14
|
-
return {
|
|
15
|
-
waitMs: hint.waitMs,
|
|
16
|
-
retryAt: new Date(now + hint.waitMs),
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
return { waitMs: undefined, retryAt: undefined };
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
class RateLimitError extends FetchError {
|
|
23
|
-
constructor({
|
|
24
|
-
hint,
|
|
25
|
-
waitMs,
|
|
26
|
-
module,
|
|
27
|
-
scopeKey,
|
|
28
|
-
now = Date.now(),
|
|
29
|
-
...fetchErrorArgs
|
|
30
|
-
} = {}) {
|
|
31
|
-
super(fetchErrorArgs);
|
|
32
|
-
|
|
33
|
-
const timing = resolveTiming({ hint, waitMs, now });
|
|
34
|
-
this.statusCode ??= fetchErrorArgs.cause?.statusCode;
|
|
35
|
-
this.isRateLimited = true;
|
|
36
|
-
this.waitMs = timing.waitMs;
|
|
37
|
-
this.retryAt = timing.retryAt;
|
|
38
|
-
this.reason = hint?.reason ?? 'unknown';
|
|
39
|
-
this.policy = hint?.policy;
|
|
40
|
-
this.source = hint?.source ?? 'unknown';
|
|
41
|
-
this.module = module;
|
|
42
|
-
this.scopeKey = scopeKey;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
module.exports = { RateLimitError };
|