@friggframework/core 2.0.0--canary.730.f2ba24a.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.
- package/CLAUDE.md +14 -42
- package/application/commands/README.md +11 -17
- package/application/commands/entity-commands.js +60 -18
- package/application/commands/integration-commands.js +0 -63
- package/core/CLAUDE.md +3 -1
- package/core/create-handler.js +3 -0
- package/core/index.js +6 -0
- package/core/invocation-deadline.js +91 -0
- package/core/invocation-scope.js +30 -24
- package/database/documentdb-encryption-service.js +33 -2
- package/database/documentdb-utils.js +1 -4
- package/database/encryption/README.md +3 -3
- package/database/encryption/encryption-schema-registry.js +29 -109
- package/database/encryption/field-encryption-service.js +16 -55
- package/database/encryption/prisma-encryption-extension.js +9 -6
- package/database/prisma.js +1 -10
- package/encrypt/Cryptor.js +38 -90
- package/errors/fetch-error.js +11 -18
- package/errors/index.js +2 -4
- package/errors/rate-limit-error.js +45 -0
- package/handlers/WEBHOOKS.md +0 -29
- package/handlers/app-definition-loader.js +2 -9
- package/handlers/app-handler-helpers.js +1 -12
- package/handlers/backend-utils.js +2 -1
- package/handlers/workers/integration-defined-workers.js +2 -0
- package/index.js +18 -2
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +13 -67
- package/integrations/integration-base.js +9 -52
- package/integrations/integration-router.js +22 -30
- package/integrations/repositories/integration-mapping-repository-documentdb.js +0 -50
- package/integrations/repositories/integration-mapping-repository-interface.js +0 -15
- package/integrations/repositories/integration-mapping-repository-mongo.js +0 -29
- package/integrations/repositories/integration-mapping-repository-postgres.js +0 -30
- package/integrations/repositories/integration-mapping-repository.js +0 -29
- package/integrations/repositories/integration-repository-documentdb.js +0 -32
- package/integrations/repositories/integration-repository-interface.js +0 -30
- package/integrations/repositories/integration-repository-mongo.js +1 -53
- package/integrations/repositories/integration-repository-postgres.js +0 -58
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/create-integration.js +19 -57
- package/integrations/use-cases/delete-integration-for-user.js +11 -8
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/update-integration.js +12 -12
- package/jest-setup.js +2 -13
- package/jest-teardown.js +2 -5
- package/jest.config.js +0 -4
- package/logs/serialize.js +15 -0
- package/modules/requester/rate-limit/index.js +4 -0
- package/modules/requester/rate-limit/parsers.js +245 -0
- package/modules/requester/rate-limit/policy.js +304 -0
- package/modules/requester/requester.js +187 -9
- package/modules/use-cases/get-entity-options-by-id.js +5 -7
- package/modules/use-cases/get-module.js +8 -29
- package/modules/use-cases/process-authorization-callback.js +27 -78
- package/modules/use-cases/refresh-entity-options.js +5 -7
- package/modules/use-cases/test-module-auth.js +5 -7
- package/modules/utils/map-module-dto.js +3 -5
- package/package.json +7 -10
- package/queues/queuer-util.js +5 -6
- package/token/repositories/token-repository-documentdb.js +1 -13
- package/token/repositories/token-repository-mongo.js +1 -13
- package/token/repositories/token-repository-postgres.js +1 -13
- package/types/core/index.d.ts +33 -0
- package/types/errors/index.d.ts +47 -0
- package/types/module-plugin/index.d.ts +43 -0
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +7 -23
- package/user/use-cases/get-user-from-bearer-token.js +2 -7
- package/database/encryption/ciphertext-format.js +0 -24
- package/errors/mapping-already-exists-error.js +0 -14
- package/integrations/use-cases/add-entities-to-integration.js +0 -92
- package/integrations/use-cases/remove-entities-from-integration.js +0 -70
- package/integrations/utils/assert-entity-ids-input.js +0 -42
- package/jest.db.config.js +0 -23
- package/modules/use-cases/create-entity-from-credential.js +0 -105
- package/modules/utils/find-module-definition.js +0 -23
- 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.
|
|
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.730.f2ba24a.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.
|
|
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.
|
|
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.
|
|
53
|
-
"@friggframework/prettier-config": "2.0.0--canary.
|
|
54
|
-
"@friggframework/test": "2.0.0--canary.
|
|
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": "
|
|
92
|
+
"gitHead": "6eb85ab403f6a3aa18fc5ad49c63c1799890ec55"
|
|
96
93
|
}
|
package/queues/queuer-util.js
CHANGED
|
@@ -97,17 +97,16 @@ const QueuerUtil = {
|
|
|
97
97
|
Id: uuid(),
|
|
98
98
|
MessageBody: JSON.stringify(entry),
|
|
99
99
|
});
|
|
100
|
-
// Sends 10, then
|
|
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:
|
|
103
|
+
Entries: buffer,
|
|
107
104
|
QueueUrl: queueUrl,
|
|
108
105
|
});
|
|
109
106
|
const result = await sqs.send(command);
|
|
110
|
-
inspectBatchResult(result, queueUrl,
|
|
107
|
+
inspectBatchResult(result, queueUrl, buffer);
|
|
108
|
+
// Purge the buffer
|
|
109
|
+
buffer.splice(0, buffer.length);
|
|
111
110
|
}
|
|
112
111
|
}
|
|
113
112
|
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
package/types/core/index.d.ts
CHANGED
|
@@ -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;
|
package/types/errors/index.d.ts
CHANGED
|
@@ -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, {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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 };
|
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
const {
|
|
2
|
-
assertEntityIdsInput,
|
|
3
|
-
integrationNotFound,
|
|
4
|
-
loadIntegration,
|
|
5
|
-
} = require('../utils/assert-entity-ids-input');
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Attaches entities to an existing integration, e.g. when a user grants
|
|
9
|
-
* access to more accounts after the integration was created. Every entity
|
|
10
|
-
* must exist, belong to the integration's user, and be of a module the
|
|
11
|
-
* integration already holds (so hydration can load it). Entities that are
|
|
12
|
-
* already attached are left as they are.
|
|
13
|
-
* @class AddEntitiesToIntegration
|
|
14
|
-
*/
|
|
15
|
-
class AddEntitiesToIntegration {
|
|
16
|
-
/**
|
|
17
|
-
* @param {Object} params
|
|
18
|
-
* @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
|
|
19
|
-
* @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
|
|
20
|
-
*/
|
|
21
|
-
constructor({ integrationRepository, moduleRepository }) {
|
|
22
|
-
this.integrationRepository = integrationRepository;
|
|
23
|
-
this.moduleRepository = moduleRepository;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* @param {string} integrationId
|
|
28
|
-
* @param {string[]} entityIds
|
|
29
|
-
* @returns {Promise<Object>} The updated integration record.
|
|
30
|
-
*/
|
|
31
|
-
async execute(integrationId, entityIds) {
|
|
32
|
-
assertEntityIdsInput(integrationId, entityIds);
|
|
33
|
-
|
|
34
|
-
const integration = await loadIntegration(
|
|
35
|
-
this.integrationRepository,
|
|
36
|
-
integrationId
|
|
37
|
-
);
|
|
38
|
-
|
|
39
|
-
const entities = await this.moduleRepository.findEntitiesByIds(
|
|
40
|
-
entityIds
|
|
41
|
-
);
|
|
42
|
-
const foundIds = new Set(entities.map((e) => String(e.id)));
|
|
43
|
-
const missing = entityIds.filter((id) => !foundIds.has(String(id)));
|
|
44
|
-
if (missing.length > 0) {
|
|
45
|
-
const error = new Error(
|
|
46
|
-
`Entities not found: ${missing.join(', ')}`
|
|
47
|
-
);
|
|
48
|
-
error.code = 'ENTITIES_NOT_FOUND';
|
|
49
|
-
throw error;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const foreign = entities.filter(
|
|
53
|
-
(e) => String(e.userId) !== String(integration.userId)
|
|
54
|
-
);
|
|
55
|
-
if (foreign.length > 0) {
|
|
56
|
-
const error = new Error(
|
|
57
|
-
`Entities do not belong to the integration's user: ${foreign
|
|
58
|
-
.map((e) => e.id)
|
|
59
|
-
.join(', ')}`
|
|
60
|
-
);
|
|
61
|
-
error.code = 'ENTITY_USER_MISMATCH';
|
|
62
|
-
throw error;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const attached = await this.moduleRepository.findEntitiesByIds(
|
|
66
|
-
integration.entitiesIds ?? []
|
|
67
|
-
);
|
|
68
|
-
const heldModules = new Set(attached.map((e) => e.moduleName));
|
|
69
|
-
const otherModules = entities.filter(
|
|
70
|
-
(e) => !heldModules.has(e.moduleName)
|
|
71
|
-
);
|
|
72
|
-
if (otherModules.length > 0) {
|
|
73
|
-
const error = new Error(
|
|
74
|
-
`Entities belong to a module the integration does not hold: ${otherModules
|
|
75
|
-
.map((e) => `${e.id} (${e.moduleName})`)
|
|
76
|
-
.join(', ')}`
|
|
77
|
-
);
|
|
78
|
-
error.code = 'ENTITY_MODULE_MISMATCH';
|
|
79
|
-
throw error;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const updated =
|
|
83
|
-
await this.integrationRepository.addEntitiesToIntegration(
|
|
84
|
-
integrationId,
|
|
85
|
-
entityIds
|
|
86
|
-
);
|
|
87
|
-
if (!updated) throw integrationNotFound(integrationId);
|
|
88
|
-
return updated;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
module.exports = { AddEntitiesToIntegration };
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
const {
|
|
2
|
-
assertEntityIdsInput,
|
|
3
|
-
integrationNotFound,
|
|
4
|
-
loadIntegration,
|
|
5
|
-
} = require('../utils/assert-entity-ids-input');
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Detaches entities from an integration. Entities that are not attached are
|
|
9
|
-
* ignored, and detached entities are not deleted. Every module the
|
|
10
|
-
* integration holds must keep at least one entity, so the integration can
|
|
11
|
-
* still hydrate each of its modules.
|
|
12
|
-
* @class RemoveEntitiesFromIntegration
|
|
13
|
-
*/
|
|
14
|
-
class RemoveEntitiesFromIntegration {
|
|
15
|
-
/**
|
|
16
|
-
* @param {Object} params
|
|
17
|
-
* @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
|
|
18
|
-
* @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
|
|
19
|
-
*/
|
|
20
|
-
constructor({ integrationRepository, moduleRepository }) {
|
|
21
|
-
this.integrationRepository = integrationRepository;
|
|
22
|
-
this.moduleRepository = moduleRepository;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* @param {string} integrationId
|
|
27
|
-
* @param {string[]} entityIds
|
|
28
|
-
* @returns {Promise<Object>} The updated integration record.
|
|
29
|
-
*/
|
|
30
|
-
async execute(integrationId, entityIds) {
|
|
31
|
-
assertEntityIdsInput(integrationId, entityIds);
|
|
32
|
-
|
|
33
|
-
const integration = await loadIntegration(
|
|
34
|
-
this.integrationRepository,
|
|
35
|
-
integrationId
|
|
36
|
-
);
|
|
37
|
-
|
|
38
|
-
const removing = new Set(entityIds.map(String));
|
|
39
|
-
const attached = await this.moduleRepository.findEntitiesByIds(
|
|
40
|
-
integration.entitiesIds ?? []
|
|
41
|
-
);
|
|
42
|
-
const emptied = [...new Set(attached.map((e) => e.moduleName))].filter(
|
|
43
|
-
(moduleName) =>
|
|
44
|
-
!attached.some(
|
|
45
|
-
(e) =>
|
|
46
|
-
e.moduleName === moduleName &&
|
|
47
|
-
!removing.has(String(e.id))
|
|
48
|
-
)
|
|
49
|
-
);
|
|
50
|
-
if (emptied.length > 0) {
|
|
51
|
-
const error = new Error(
|
|
52
|
-
`Removing these entities would leave no entity for module(s): ${emptied.join(
|
|
53
|
-
', '
|
|
54
|
-
)}`
|
|
55
|
-
);
|
|
56
|
-
error.code = 'LAST_ENTITY_OF_MODULE';
|
|
57
|
-
throw error;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const updated =
|
|
61
|
-
await this.integrationRepository.removeEntitiesFromIntegration(
|
|
62
|
-
integrationId,
|
|
63
|
-
entityIds
|
|
64
|
-
);
|
|
65
|
-
if (!updated) throw integrationNotFound(integrationId);
|
|
66
|
-
return updated;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
module.exports = { RemoveEntitiesFromIntegration };
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Throws INVALID_INTEGRATION_DATA unless an integration id and a non-empty
|
|
3
|
-
* list of entity ids are given.
|
|
4
|
-
* @param {string} integrationId
|
|
5
|
-
* @param {string[]} entityIds
|
|
6
|
-
*/
|
|
7
|
-
function assertEntityIdsInput(integrationId, entityIds) {
|
|
8
|
-
if (!integrationId || !Array.isArray(entityIds) || entityIds.length === 0) {
|
|
9
|
-
const error = new Error(
|
|
10
|
-
'integrationId and a non-empty entityIds array are required'
|
|
11
|
-
);
|
|
12
|
-
error.code = 'INVALID_INTEGRATION_DATA';
|
|
13
|
-
throw error;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function integrationNotFound(integrationId) {
|
|
18
|
-
const error = new Error(`Integration ${integrationId} not found`);
|
|
19
|
-
error.code = 'INTEGRATION_NOT_FOUND';
|
|
20
|
-
return error;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Loads an integration, mapping the repositories' "not found" error to
|
|
25
|
-
* INTEGRATION_NOT_FOUND. Any other failure (connection, invalid id) is
|
|
26
|
-
* rethrown unchanged.
|
|
27
|
-
* @param {Object} integrationRepository
|
|
28
|
-
* @param {string} integrationId
|
|
29
|
-
* @returns {Promise<Object>} The integration record.
|
|
30
|
-
*/
|
|
31
|
-
async function loadIntegration(integrationRepository, integrationId) {
|
|
32
|
-
try {
|
|
33
|
-
return await integrationRepository.findIntegrationById(integrationId);
|
|
34
|
-
} catch (error) {
|
|
35
|
-
if (/^Integration with id .* not found$/.test(error?.message)) {
|
|
36
|
-
throw integrationNotFound(integrationId);
|
|
37
|
-
}
|
|
38
|
-
throw error;
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
module.exports = { assertEntityIdsInput, integrationNotFound, loadIntegration };
|