feat: fixed eslint and resolved all eslint issues

This commit is contained in:
Akhil Mohan
2024-01-30 22:30:42 +05:30
parent 7c4dd5000f
commit 5855cc660a
147 changed files with 1165 additions and 938 deletions
+20 -15
View File
@@ -1,27 +1,39 @@
/* eslint-env node */
module.exports = { module.exports = {
root: true,
env: { env: {
browser: true, es6: true,
es2021: true node: true
}, },
extends: ["airbnb-base", "airbnb-typescript/base", "prettier"], extends: [
plugins: ["prettier", "simple-import-sort", "import"], "eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-type-checked",
"airbnb-base",
"airbnb-typescript/base",
"plugin:prettier/recommended",
"prettier"
],
plugins: ["@typescript-eslint", "simple-import-sort", "import"],
parser: "@typescript-eslint/parser",
parserOptions: { parserOptions: {
ecmaVersion: "latest", project: true,
sourceType: "module", sourceType: "module",
project: "./tsconfig.json",
tsconfigRootDir: __dirname tsconfigRootDir: __dirname
}, },
root: true,
rules: { rules: {
"@typescript-eslint/no-empty-function": "off", "@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-unsafe-enum-comparison": "off",
"no-void": "off",
"consistent-return": "off", // my style "consistent-return": "off", // my style
"import/order": "off", // for simple-import-order "import/order": "off", // for simple-import-order
"import/prefer-default-export": "off", // why "import/prefer-default-export": "off", // why
"no-restricted-syntax": "off", "no-restricted-syntax": "off",
// importing rules
"simple-import-sort/exports": "error",
"import/first": "error", "import/first": "error",
"import/newline-after-import": "error", "import/newline-after-import": "error",
"import/no-duplicates": "error", "import/no-duplicates": "error",
"simple-import-sort/exports": "error",
"simple-import-sort/imports": [ "simple-import-sort/imports": [
"warn", "warn",
{ {
@@ -45,12 +57,5 @@ module.exports = {
] ]
} }
] ]
},
settings: {
"import/resolver": {
typescript: {
project: ["./tsconfig.json"]
}
}
} }
}; };
+69 -46
View File
@@ -25,6 +25,8 @@
"@octokit/webhooks-types": "^7.3.1", "@octokit/webhooks-types": "^7.3.1",
"@serdnam/pino-cloudwatch-transport": "^1.0.4", "@serdnam/pino-cloudwatch-transport": "^1.0.4",
"@sindresorhus/slugify": "^2.2.1", "@sindresorhus/slugify": "^2.2.1",
"@typescript-eslint/eslint-plugin": "^6.20.0",
"@typescript-eslint/parser": "^6.20.0",
"@ucast/mongo2js": "^1.3.4", "@ucast/mongo2js": "^1.3.4",
"ajv": "^8.12.0", "ajv": "^8.12.0",
"argon2": "^0.31.2", "argon2": "^0.31.2",
@@ -34,6 +36,8 @@
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"bullmq": "^5.1.1", "bullmq": "^5.1.1",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"eslint": "^8.56.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-airbnb-typescript": "^17.1.0", "eslint-config-airbnb-typescript": "^17.1.0",
"fastify": "^4.24.3", "fastify": "^4.24.3",
"fastify-plugin": "^4.5.1", "fastify-plugin": "^4.5.1",
@@ -80,10 +84,6 @@
"@types/picomatch": "^2.3.3", "@types/picomatch": "^2.3.3",
"@types/prompt-sync": "^4.2.3", "@types/prompt-sync": "^4.2.3",
"@types/uuid": "^9.0.7", "@types/uuid": "^9.0.7",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
"eslint": "^8.56.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"eslint-import-resolver-typescript": "^3.6.1", "eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1", "eslint-plugin-import": "^2.29.1",
@@ -4530,15 +4530,15 @@
} }
}, },
"node_modules/@typescript-eslint/eslint-plugin": { "node_modules/@typescript-eslint/eslint-plugin": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.20.0.tgz",
"integrity": "sha512-3+9OGAWHhk4O1LlcwLBONbdXsAhLjyCFogJY/cWy2lxdVJ2JrcTF2pTGMaLl2AE7U1l31n8Py4a8bx5DLf/0dQ==", "integrity": "sha512-fTwGQUnjhoYHeSF6m5pWNkzmDDdsKELYrOBxhjMrofPqCkoC2k3B2wvGHFxa1CTIqkEn88nlW1HVMztjo2K8Hg==",
"dependencies": { "dependencies": {
"@eslint-community/regexpp": "^4.5.1", "@eslint-community/regexpp": "^4.5.1",
"@typescript-eslint/scope-manager": "6.13.2", "@typescript-eslint/scope-manager": "6.20.0",
"@typescript-eslint/type-utils": "6.13.2", "@typescript-eslint/type-utils": "6.20.0",
"@typescript-eslint/utils": "6.13.2", "@typescript-eslint/utils": "6.20.0",
"@typescript-eslint/visitor-keys": "6.13.2", "@typescript-eslint/visitor-keys": "6.20.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"graphemer": "^1.4.0", "graphemer": "^1.4.0",
"ignore": "^5.2.4", "ignore": "^5.2.4",
@@ -4585,14 +4585,14 @@
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}, },
"node_modules/@typescript-eslint/parser": { "node_modules/@typescript-eslint/parser": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.20.0.tgz",
"integrity": "sha512-MUkcC+7Wt/QOGeVlM8aGGJZy1XV5YKjTpq9jK6r6/iLsGXhBVaGP5N0UYvFsu9BFlSpwY9kMretzdBH01rkRXg==", "integrity": "sha512-bYerPDF/H5v6V76MdMYhjwmwgMA+jlPVqjSDq2cRqMi8bP5sR3Z+RLOiOMad3nsnmDVmn2gAFCyNgh/dIrfP/w==",
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "6.13.2", "@typescript-eslint/scope-manager": "6.20.0",
"@typescript-eslint/types": "6.13.2", "@typescript-eslint/types": "6.20.0",
"@typescript-eslint/typescript-estree": "6.13.2", "@typescript-eslint/typescript-estree": "6.20.0",
"@typescript-eslint/visitor-keys": "6.13.2", "@typescript-eslint/visitor-keys": "6.20.0",
"debug": "^4.3.4" "debug": "^4.3.4"
}, },
"engines": { "engines": {
@@ -4633,12 +4633,12 @@
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}, },
"node_modules/@typescript-eslint/scope-manager": { "node_modules/@typescript-eslint/scope-manager": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.20.0.tgz",
"integrity": "sha512-CXQA0xo7z6x13FeDYCgBkjWzNqzBn8RXaE3QVQVIUm74fWJLkJkaHmHdKStrxQllGh6Q4eUGyNpMe0b1hMkXFA==", "integrity": "sha512-p4rvHQRDTI1tGGMDFQm+GtxP1ZHyAh64WANVoyEcNMpaTFn3ox/3CcgtIlELnRfKzSs/DwYlDccJEtr3O6qBvA==",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "6.13.2", "@typescript-eslint/types": "6.20.0",
"@typescript-eslint/visitor-keys": "6.13.2" "@typescript-eslint/visitor-keys": "6.20.0"
}, },
"engines": { "engines": {
"node": "^16.0.0 || >=18.0.0" "node": "^16.0.0 || >=18.0.0"
@@ -4649,12 +4649,12 @@
} }
}, },
"node_modules/@typescript-eslint/type-utils": { "node_modules/@typescript-eslint/type-utils": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.20.0.tgz",
"integrity": "sha512-Qr6ssS1GFongzH2qfnWKkAQmMUyZSyOr0W54nZNU1MDfo+U4Mv3XveeLZzadc/yq8iYhQZHYT+eoXJqnACM1tw==", "integrity": "sha512-qnSobiJQb1F5JjN0YDRPHruQTrX7ICsmltXhkV536mp4idGAYrIyr47zF/JmkJtEcAVnIz4gUYJ7gOZa6SmN4g==",
"dependencies": { "dependencies": {
"@typescript-eslint/typescript-estree": "6.13.2", "@typescript-eslint/typescript-estree": "6.20.0",
"@typescript-eslint/utils": "6.13.2", "@typescript-eslint/utils": "6.20.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"ts-api-utils": "^1.0.1" "ts-api-utils": "^1.0.1"
}, },
@@ -4696,9 +4696,9 @@
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}, },
"node_modules/@typescript-eslint/types": { "node_modules/@typescript-eslint/types": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.20.0.tgz",
"integrity": "sha512-7sxbQ+EMRubQc3wTfTsycgYpSujyVbI1xw+3UMRUcrhSy+pN09y/lWzeKDbvhoqcRbHdc+APLs/PWYi/cisLPg==", "integrity": "sha512-MM9mfZMAhiN4cOEcUOEx+0HmuaW3WBfukBZPCfwSqFnQy0grXYtngKCqpQN339X3RrwtzspWJrpbrupKYUSBXQ==",
"engines": { "engines": {
"node": "^16.0.0 || >=18.0.0" "node": "^16.0.0 || >=18.0.0"
}, },
@@ -4708,15 +4708,16 @@
} }
}, },
"node_modules/@typescript-eslint/typescript-estree": { "node_modules/@typescript-eslint/typescript-estree": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.20.0.tgz",
"integrity": "sha512-SuD8YLQv6WHnOEtKv8D6HZUzOub855cfPnPMKvdM/Bh1plv1f7Q/0iFUDLKKlxHcEstQnaUU4QZskgQq74t+3w==", "integrity": "sha512-RnRya9q5m6YYSpBN7IzKu9FmLcYtErkDkc8/dKv81I9QiLLtVBHrjz+Ev/crAqgMNW2FCsoZF4g2QUylMnJz+g==",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "6.13.2", "@typescript-eslint/types": "6.20.0",
"@typescript-eslint/visitor-keys": "6.13.2", "@typescript-eslint/visitor-keys": "6.20.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"globby": "^11.1.0", "globby": "^11.1.0",
"is-glob": "^4.0.3", "is-glob": "^4.0.3",
"minimatch": "9.0.3",
"semver": "^7.5.4", "semver": "^7.5.4",
"ts-api-utils": "^1.0.1" "ts-api-utils": "^1.0.1"
}, },
@@ -4733,6 +4734,14 @@
} }
} }
}, },
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz",
"integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
"dependencies": {
"balanced-match": "^1.0.0"
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/debug": { "node_modules/@typescript-eslint/typescript-estree/node_modules/debug": {
"version": "4.3.4", "version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
@@ -4749,22 +4758,36 @@
} }
} }
}, },
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
"version": "9.0.3",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz",
"integrity": "sha512-RHiac9mvaRw0x3AYRgDC1CxAP7HTcNrrECeA8YYJeWnpo+2Q5CegtZjaotWTWxDG3UeGA1coE05iH1mPjT/2mg==",
"dependencies": {
"brace-expansion": "^2.0.1"
},
"engines": {
"node": ">=16 || 14 >=14.17"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/ms": { "node_modules/@typescript-eslint/typescript-estree/node_modules/ms": {
"version": "2.1.2", "version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
}, },
"node_modules/@typescript-eslint/utils": { "node_modules/@typescript-eslint/utils": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.20.0.tgz",
"integrity": "sha512-b9Ptq4eAZUym4idijCRzl61oPCwwREcfDI8xGk751Vhzig5fFZR9CyzDz4Sp/nxSLBYxUPyh4QdIDqWykFhNmQ==", "integrity": "sha512-/EKuw+kRu2vAqCoDwDCBtDRU6CTKbUmwwI7SH7AashZ+W+7o8eiyy6V2cdOqN49KsTcASWsC5QeghYuRDTyOOg==",
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.4.0", "@eslint-community/eslint-utils": "^4.4.0",
"@types/json-schema": "^7.0.12", "@types/json-schema": "^7.0.12",
"@types/semver": "^7.5.0", "@types/semver": "^7.5.0",
"@typescript-eslint/scope-manager": "6.13.2", "@typescript-eslint/scope-manager": "6.20.0",
"@typescript-eslint/types": "6.13.2", "@typescript-eslint/types": "6.20.0",
"@typescript-eslint/typescript-estree": "6.13.2", "@typescript-eslint/typescript-estree": "6.20.0",
"semver": "^7.5.4" "semver": "^7.5.4"
}, },
"engines": { "engines": {
@@ -4779,11 +4802,11 @@
} }
}, },
"node_modules/@typescript-eslint/visitor-keys": { "node_modules/@typescript-eslint/visitor-keys": {
"version": "6.13.2", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.13.2.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.20.0.tgz",
"integrity": "sha512-OGznFs0eAQXJsp+xSd6k/O1UbFi/K/L7WjqeRoFE7vadjAF9y0uppXhYNQNEqygjou782maGClOoZwPqF0Drlw==", "integrity": "sha512-E8Cp98kRe4gKHjJD4NExXKz/zOJ1A2hhZc+IMVD6i7w4yjIvh6VyuRI0gRtxAsXtoC35uGMaQ9rjI2zJaXDEAw==",
"dependencies": { "dependencies": {
"@typescript-eslint/types": "6.13.2", "@typescript-eslint/types": "6.20.0",
"eslint-visitor-keys": "^3.4.1" "eslint-visitor-keys": "^3.4.1"
}, },
"engines": { "engines": {
+4 -4
View File
@@ -45,10 +45,6 @@
"@types/picomatch": "^2.3.3", "@types/picomatch": "^2.3.3",
"@types/prompt-sync": "^4.2.3", "@types/prompt-sync": "^4.2.3",
"@types/uuid": "^9.0.7", "@types/uuid": "^9.0.7",
"@typescript-eslint/eslint-plugin": "^6.13.2",
"@typescript-eslint/parser": "^6.13.2",
"eslint": "^8.56.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.1.0", "eslint-config-prettier": "^9.1.0",
"eslint-import-resolver-typescript": "^3.6.1", "eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.29.1", "eslint-plugin-import": "^2.29.1",
@@ -83,6 +79,8 @@
"@octokit/webhooks-types": "^7.3.1", "@octokit/webhooks-types": "^7.3.1",
"@serdnam/pino-cloudwatch-transport": "^1.0.4", "@serdnam/pino-cloudwatch-transport": "^1.0.4",
"@sindresorhus/slugify": "^2.2.1", "@sindresorhus/slugify": "^2.2.1",
"@typescript-eslint/eslint-plugin": "^6.20.0",
"@typescript-eslint/parser": "^6.20.0",
"@ucast/mongo2js": "^1.3.4", "@ucast/mongo2js": "^1.3.4",
"ajv": "^8.12.0", "ajv": "^8.12.0",
"argon2": "^0.31.2", "argon2": "^0.31.2",
@@ -92,6 +90,8 @@
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"bullmq": "^5.1.1", "bullmq": "^5.1.1",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"eslint": "^8.56.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-airbnb-typescript": "^17.1.0", "eslint-config-airbnb-typescript": "^17.1.0",
"fastify": "^4.24.3", "fastify": "^4.24.3",
"fastify-plugin": "^4.5.1", "fastify-plugin": "^4.5.1",
@@ -19,7 +19,7 @@ export async function up(knex: Knex): Promise<void> {
.references("id") .references("id")
.inTable(TableName.IdentityUaClientSecret) .inTable(TableName.IdentityUaClientSecret)
.onDelete("CASCADE"); .onDelete("CASCADE");
t.uuid("identityId").notNullable(); t.uuid("identityId").notNullable();
t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE"); t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE");
t.timestamps(true, true, true); t.timestamps(true, true, true);
}); });
@@ -15,7 +15,7 @@ export async function up(knex: Knex): Promise<void> {
t.timestamps(true, true, true); t.timestamps(true, true, true);
}); });
} }
createOnUpdateTrigger(knex, TableName.GitAppInstallSession); await createOnUpdateTrigger(knex, TableName.GitAppInstallSession);
if (!(await knex.schema.hasTable(TableName.GitAppOrg))) { if (!(await knex.schema.hasTable(TableName.GitAppOrg))) {
await knex.schema.createTable(TableName.GitAppOrg, (t) => { await knex.schema.createTable(TableName.GitAppOrg, (t) => {
@@ -28,7 +28,7 @@ export async function up(knex: Knex): Promise<void> {
t.timestamps(true, true, true); t.timestamps(true, true, true);
}); });
} }
createOnUpdateTrigger(knex, TableName.GitAppOrg); await createOnUpdateTrigger(knex, TableName.GitAppOrg);
if (!(await knex.schema.hasTable(TableName.SecretScanningGitRisk))) { if (!(await knex.schema.hasTable(TableName.SecretScanningGitRisk))) {
await knex.schema.createTable(TableName.SecretScanningGitRisk, (t) => { await knex.schema.createTable(TableName.SecretScanningGitRisk, (t) => {
@@ -66,7 +66,7 @@ export async function up(knex: Knex): Promise<void> {
t.timestamps(true, true, true); t.timestamps(true, true, true);
}); });
} }
createOnUpdateTrigger(knex, TableName.SecretScanningGitRisk); await createOnUpdateTrigger(knex, TableName.SecretScanningGitRisk);
} }
export async function down(knex: Knex): Promise<void> { export async function down(knex: Knex): Promise<void> {
+1 -1
View File
@@ -15,7 +15,7 @@ export const ApiKeysSchema = z.object({
secretHash: z.string(), secretHash: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
userId: z.string().uuid(), userId: z.string().uuid()
}); });
export type TApiKeys = z.infer<typeof ApiKeysSchema>; export type TApiKeys = z.infer<typeof ApiKeysSchema>;
+1 -1
View File
@@ -20,7 +20,7 @@ export const AuditLogsSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
orgId: z.string().uuid().nullable().optional(), orgId: z.string().uuid().nullable().optional(),
projectId: z.string().nullable().optional(), projectId: z.string().nullable().optional()
}); });
export type TAuditLogs = z.infer<typeof AuditLogsSchema>; export type TAuditLogs = z.infer<typeof AuditLogsSchema>;
@@ -16,7 +16,7 @@ export const AuthTokenSessionsSchema = z.object({
lastUsed: z.date(), lastUsed: z.date(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
userId: z.string().uuid(), userId: z.string().uuid()
}); });
export type TAuthTokenSessions = z.infer<typeof AuthTokenSessionsSchema>; export type TAuthTokenSessions = z.infer<typeof AuthTokenSessionsSchema>;
+1 -1
View File
@@ -17,7 +17,7 @@ export const AuthTokensSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
userId: z.string().uuid().nullable().optional(), userId: z.string().uuid().nullable().optional(),
orgId: z.string().uuid().nullable().optional(), orgId: z.string().uuid().nullable().optional()
}); });
export type TAuthTokens = z.infer<typeof AuthTokensSchema>; export type TAuthTokens = z.infer<typeof AuthTokensSchema>;
+1 -1
View File
@@ -18,7 +18,7 @@ export const BackupPrivateKeySchema = z.object({
verifier: z.string(), verifier: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
userId: z.string().uuid(), userId: z.string().uuid()
}); });
export type TBackupPrivateKey = z.infer<typeof BackupPrivateKeySchema>; export type TBackupPrivateKey = z.infer<typeof BackupPrivateKeySchema>;
@@ -13,7 +13,7 @@ export const GitAppInstallSessionsSchema = z.object({
userId: z.string().uuid().nullable().optional(), userId: z.string().uuid().nullable().optional(),
orgId: z.string().uuid(), orgId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TGitAppInstallSessions = z.infer<typeof GitAppInstallSessionsSchema>; export type TGitAppInstallSessions = z.infer<typeof GitAppInstallSessionsSchema>;
+1 -1
View File
@@ -13,7 +13,7 @@ export const GitAppOrgSchema = z.object({
userId: z.string().uuid(), userId: z.string().uuid(),
orgId: z.string().uuid(), orgId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TGitAppOrg = z.infer<typeof GitAppOrgSchema>; export type TGitAppOrg = z.infer<typeof GitAppOrgSchema>;
+1 -1
View File
@@ -12,7 +12,7 @@ export const IdentitiesSchema = z.object({
name: z.string(), name: z.string(),
authMethod: z.string().nullable().optional(), authMethod: z.string().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TIdentities = z.infer<typeof IdentitiesSchema>; export type TIdentities = z.infer<typeof IdentitiesSchema>;
@@ -19,7 +19,7 @@ export const IdentityAccessTokensSchema = z.object({
identityUAClientSecretId: z.string().nullable().optional(), identityUAClientSecretId: z.string().nullable().optional(),
identityId: z.string().uuid(), identityId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TIdentityAccessTokens = z.infer<typeof IdentityAccessTokensSchema>; export type TIdentityAccessTokens = z.infer<typeof IdentityAccessTokensSchema>;
@@ -14,9 +14,11 @@ export const IdentityOrgMembershipsSchema = z.object({
orgId: z.string().uuid(), orgId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
identityId: z.string().uuid(), identityId: z.string().uuid()
}); });
export type TIdentityOrgMemberships = z.infer<typeof IdentityOrgMembershipsSchema>; export type TIdentityOrgMemberships = z.infer<typeof IdentityOrgMembershipsSchema>;
export type TIdentityOrgMembershipsInsert = Omit<TIdentityOrgMemberships, TImmutableDBKeys>; export type TIdentityOrgMembershipsInsert = Omit<TIdentityOrgMemberships, TImmutableDBKeys>;
export type TIdentityOrgMembershipsUpdate = Partial<Omit<TIdentityOrgMemberships, TImmutableDBKeys>>; export type TIdentityOrgMembershipsUpdate = Partial<
Omit<TIdentityOrgMemberships, TImmutableDBKeys>
>;
@@ -14,9 +14,11 @@ export const IdentityProjectMembershipsSchema = z.object({
projectId: z.string(), projectId: z.string(),
identityId: z.string().uuid(), identityId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TIdentityProjectMemberships = z.infer<typeof IdentityProjectMembershipsSchema>; export type TIdentityProjectMemberships = z.infer<typeof IdentityProjectMembershipsSchema>;
export type TIdentityProjectMembershipsInsert = Omit<TIdentityProjectMemberships, TImmutableDBKeys>; export type TIdentityProjectMembershipsInsert = Omit<TIdentityProjectMemberships, TImmutableDBKeys>;
export type TIdentityProjectMembershipsUpdate = Partial<Omit<TIdentityProjectMemberships, TImmutableDBKeys>>; export type TIdentityProjectMembershipsUpdate = Partial<
Omit<TIdentityProjectMemberships, TImmutableDBKeys>
>;
@@ -19,9 +19,11 @@ export const IdentityUaClientSecretsSchema = z.object({
isClientSecretRevoked: z.boolean().default(false), isClientSecretRevoked: z.boolean().default(false),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
identityUAId: z.string().uuid(), identityUAId: z.string().uuid()
}); });
export type TIdentityUaClientSecrets = z.infer<typeof IdentityUaClientSecretsSchema>; export type TIdentityUaClientSecrets = z.infer<typeof IdentityUaClientSecretsSchema>;
export type TIdentityUaClientSecretsInsert = Omit<TIdentityUaClientSecrets, TImmutableDBKeys>; export type TIdentityUaClientSecretsInsert = Omit<TIdentityUaClientSecrets, TImmutableDBKeys>;
export type TIdentityUaClientSecretsUpdate = Partial<Omit<TIdentityUaClientSecrets, TImmutableDBKeys>>; export type TIdentityUaClientSecretsUpdate = Partial<
Omit<TIdentityUaClientSecrets, TImmutableDBKeys>
>;
@@ -17,9 +17,11 @@ export const IdentityUniversalAuthsSchema = z.object({
accessTokenTrustedIps: z.unknown(), accessTokenTrustedIps: z.unknown(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
identityId: z.string().uuid(), identityId: z.string().uuid()
}); });
export type TIdentityUniversalAuths = z.infer<typeof IdentityUniversalAuthsSchema>; export type TIdentityUniversalAuths = z.infer<typeof IdentityUniversalAuthsSchema>;
export type TIdentityUniversalAuthsInsert = Omit<TIdentityUniversalAuths, TImmutableDBKeys>; export type TIdentityUniversalAuthsInsert = Omit<TIdentityUniversalAuths, TImmutableDBKeys>;
export type TIdentityUniversalAuthsUpdate = Partial<Omit<TIdentityUniversalAuths, TImmutableDBKeys>>; export type TIdentityUniversalAuthsUpdate = Partial<
Omit<TIdentityUniversalAuths, TImmutableDBKeys>
>;
+1 -1
View File
@@ -12,7 +12,7 @@ export const IncidentContactsSchema = z.object({
email: z.string(), email: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
orgId: z.string().uuid(), orgId: z.string().uuid()
}); });
export type TIncidentContacts = z.infer<typeof IncidentContactsSchema>; export type TIncidentContacts = z.infer<typeof IncidentContactsSchema>;
+1 -1
View File
@@ -29,7 +29,7 @@ export const IntegrationAuthsSchema = z.object({
keyEncoding: z.string(), keyEncoding: z.string(),
projectId: z.string(), projectId: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TIntegrationAuths = z.infer<typeof IntegrationAuthsSchema>; export type TIntegrationAuths = z.infer<typeof IntegrationAuthsSchema>;
+2 -2
View File
@@ -25,9 +25,9 @@ export const IntegrationsSchema = z.object({
metadata: z.unknown().nullable().optional(), metadata: z.unknown().nullable().optional(),
integrationAuthId: z.string().uuid(), integrationAuthId: z.string().uuid(),
envId: z.string().uuid(), envId: z.string().uuid(),
secretPath: z.string().default('/'), secretPath: z.string().default("/"),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TIntegrations = z.infer<typeof IntegrationsSchema>; export type TIntegrations = z.infer<typeof IntegrationsSchema>;
+1 -1
View File
@@ -23,7 +23,7 @@ export const OrgBotsSchema = z.object({
privateKeyKeyEncoding: z.string(), privateKeyKeyEncoding: z.string(),
orgId: z.string().uuid(), orgId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TOrgBots = z.infer<typeof OrgBotsSchema>; export type TOrgBots = z.infer<typeof OrgBotsSchema>;
+2 -2
View File
@@ -10,13 +10,13 @@ import { TImmutableDBKeys } from "./models";
export const OrgMembershipsSchema = z.object({ export const OrgMembershipsSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
role: z.string(), role: z.string(),
status: z.string().default('invited'), status: z.string().default("invited"),
inviteEmail: z.string().nullable().optional(), inviteEmail: z.string().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
userId: z.string().uuid().nullable().optional(), userId: z.string().uuid().nullable().optional(),
orgId: z.string().uuid(), orgId: z.string().uuid(),
roleId: z.string().uuid().nullable().optional(), roleId: z.string().uuid().nullable().optional()
}); });
export type TOrgMemberships = z.infer<typeof OrgMembershipsSchema>; export type TOrgMemberships = z.infer<typeof OrgMembershipsSchema>;
+1 -1
View File
@@ -15,7 +15,7 @@ export const OrgRolesSchema = z.object({
permissions: z.unknown(), permissions: z.unknown(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
orgId: z.string().uuid(), orgId: z.string().uuid()
}); });
export type TOrgRoles = z.infer<typeof OrgRolesSchema>; export type TOrgRoles = z.infer<typeof OrgRolesSchema>;
+1 -1
View File
@@ -13,7 +13,7 @@ export const OrganizationsSchema = z.object({
customerId: z.string().nullable().optional(), customerId: z.string().nullable().optional(),
slug: z.string(), slug: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TOrganizations = z.infer<typeof OrganizationsSchema>; export type TOrganizations = z.infer<typeof OrganizationsSchema>;
+1 -1
View File
@@ -22,7 +22,7 @@ export const ProjectBotsSchema = z.object({
projectId: z.string(), projectId: z.string(),
senderId: z.string().uuid().nullable().optional(), senderId: z.string().uuid().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TProjectBots = z.infer<typeof ProjectBotsSchema>; export type TProjectBots = z.infer<typeof ProjectBotsSchema>;
@@ -14,7 +14,7 @@ export const ProjectEnvironmentsSchema = z.object({
position: z.number(), position: z.number(),
projectId: z.string(), projectId: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TProjectEnvironments = z.infer<typeof ProjectEnvironmentsSchema>; export type TProjectEnvironments = z.infer<typeof ProjectEnvironmentsSchema>;
+1 -1
View File
@@ -15,7 +15,7 @@ export const ProjectKeysSchema = z.object({
senderId: z.string().uuid().nullable().optional(), senderId: z.string().uuid().nullable().optional(),
projectId: z.string(), projectId: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TProjectKeys = z.infer<typeof ProjectKeysSchema>; export type TProjectKeys = z.infer<typeof ProjectKeysSchema>;
@@ -14,7 +14,7 @@ export const ProjectMembershipsSchema = z.object({
updatedAt: z.date(), updatedAt: z.date(),
userId: z.string().uuid(), userId: z.string().uuid(),
projectId: z.string(), projectId: z.string(),
roleId: z.string().uuid().nullable().optional(), roleId: z.string().uuid().nullable().optional()
}); });
export type TProjectMemberships = z.infer<typeof ProjectMembershipsSchema>; export type TProjectMemberships = z.infer<typeof ProjectMembershipsSchema>;
+1 -1
View File
@@ -15,7 +15,7 @@ export const ProjectRolesSchema = z.object({
permissions: z.unknown(), permissions: z.unknown(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
projectId: z.string(), projectId: z.string()
}); });
export type TProjectRoles = z.infer<typeof ProjectRolesSchema>; export type TProjectRoles = z.infer<typeof ProjectRolesSchema>;
+1 -1
View File
@@ -14,7 +14,7 @@ export const ProjectsSchema = z.object({
autoCapitalization: z.boolean().default(true).nullable().optional(), autoCapitalization: z.boolean().default(true).nullable().optional(),
orgId: z.string().uuid(), orgId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TProjects = z.infer<typeof ProjectsSchema>; export type TProjects = z.infer<typeof ProjectsSchema>;
+1 -1
View File
@@ -22,7 +22,7 @@ export const SamlConfigsSchema = z.object({
certTag: z.string().nullable().optional(), certTag: z.string().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
orgId: z.string().uuid(), orgId: z.string().uuid()
}); });
export type TSamlConfigs = z.infer<typeof SamlConfigsSchema>; export type TSamlConfigs = z.infer<typeof SamlConfigsSchema>;
@@ -12,9 +12,16 @@ export const SecretApprovalPoliciesApproversSchema = z.object({
approverId: z.string().uuid(), approverId: z.string().uuid(),
policyId: z.string().uuid(), policyId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretApprovalPoliciesApprovers = z.infer<typeof SecretApprovalPoliciesApproversSchema>; export type TSecretApprovalPoliciesApprovers = z.infer<
export type TSecretApprovalPoliciesApproversInsert = Omit<TSecretApprovalPoliciesApprovers, TImmutableDBKeys>; typeof SecretApprovalPoliciesApproversSchema
export type TSecretApprovalPoliciesApproversUpdate = Partial<Omit<TSecretApprovalPoliciesApprovers, TImmutableDBKeys>>; >;
export type TSecretApprovalPoliciesApproversInsert = Omit<
TSecretApprovalPoliciesApprovers,
TImmutableDBKeys
>;
export type TSecretApprovalPoliciesApproversUpdate = Partial<
Omit<TSecretApprovalPoliciesApprovers, TImmutableDBKeys>
>;
@@ -14,9 +14,11 @@ export const SecretApprovalPoliciesSchema = z.object({
approvals: z.number().default(1), approvals: z.number().default(1),
envId: z.string().uuid(), envId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretApprovalPolicies = z.infer<typeof SecretApprovalPoliciesSchema>; export type TSecretApprovalPolicies = z.infer<typeof SecretApprovalPoliciesSchema>;
export type TSecretApprovalPoliciesInsert = Omit<TSecretApprovalPolicies, TImmutableDBKeys>; export type TSecretApprovalPoliciesInsert = Omit<TSecretApprovalPolicies, TImmutableDBKeys>;
export type TSecretApprovalPoliciesUpdate = Partial<Omit<TSecretApprovalPolicies, TImmutableDBKeys>>; export type TSecretApprovalPoliciesUpdate = Partial<
Omit<TSecretApprovalPolicies, TImmutableDBKeys>
>;
@@ -12,9 +12,16 @@ export const SecretApprovalRequestSecretTagsSchema = z.object({
secretId: z.string().uuid(), secretId: z.string().uuid(),
tagId: z.string().uuid(), tagId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretApprovalRequestSecretTags = z.infer<typeof SecretApprovalRequestSecretTagsSchema>; export type TSecretApprovalRequestSecretTags = z.infer<
export type TSecretApprovalRequestSecretTagsInsert = Omit<TSecretApprovalRequestSecretTags, TImmutableDBKeys>; typeof SecretApprovalRequestSecretTagsSchema
export type TSecretApprovalRequestSecretTagsUpdate = Partial<Omit<TSecretApprovalRequestSecretTags, TImmutableDBKeys>>; >;
export type TSecretApprovalRequestSecretTagsInsert = Omit<
TSecretApprovalRequestSecretTags,
TImmutableDBKeys
>;
export type TSecretApprovalRequestSecretTagsUpdate = Partial<
Omit<TSecretApprovalRequestSecretTags, TImmutableDBKeys>
>;
@@ -13,9 +13,16 @@ export const SecretApprovalRequestsReviewersSchema = z.object({
status: z.string(), status: z.string(),
requestId: z.string().uuid(), requestId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretApprovalRequestsReviewers = z.infer<typeof SecretApprovalRequestsReviewersSchema>; export type TSecretApprovalRequestsReviewers = z.infer<
export type TSecretApprovalRequestsReviewersInsert = Omit<TSecretApprovalRequestsReviewers, TImmutableDBKeys>; typeof SecretApprovalRequestsReviewersSchema
export type TSecretApprovalRequestsReviewersUpdate = Partial<Omit<TSecretApprovalRequestsReviewers, TImmutableDBKeys>>; >;
export type TSecretApprovalRequestsReviewersInsert = Omit<
TSecretApprovalRequestsReviewers,
TImmutableDBKeys
>;
export type TSecretApprovalRequestsReviewersUpdate = Partial<
Omit<TSecretApprovalRequestsReviewers, TImmutableDBKeys>
>;
@@ -23,17 +23,22 @@ export const SecretApprovalRequestsSecretsSchema = z.object({
secretReminderNote: z.string().nullable().optional(), secretReminderNote: z.string().nullable().optional(),
secretReminderRepeatDays: z.number().nullable().optional(), secretReminderRepeatDays: z.number().nullable().optional(),
skipMultilineEncoding: z.boolean().default(false).nullable().optional(), skipMultilineEncoding: z.boolean().default(false).nullable().optional(),
algorithm: z.string().default('aes-256-gcm'), algorithm: z.string().default("aes-256-gcm"),
keyEncoding: z.string().default('utf8'), keyEncoding: z.string().default("utf8"),
metadata: z.unknown().nullable().optional(), metadata: z.unknown().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
requestId: z.string().uuid(), requestId: z.string().uuid(),
op: z.string(), op: z.string(),
secretId: z.string().uuid().nullable().optional(), secretId: z.string().uuid().nullable().optional(),
secretVersion: z.string().uuid().nullable().optional(), secretVersion: z.string().uuid().nullable().optional()
}); });
export type TSecretApprovalRequestsSecrets = z.infer<typeof SecretApprovalRequestsSecretsSchema>; export type TSecretApprovalRequestsSecrets = z.infer<typeof SecretApprovalRequestsSecretsSchema>;
export type TSecretApprovalRequestsSecretsInsert = Omit<TSecretApprovalRequestsSecrets, TImmutableDBKeys>; export type TSecretApprovalRequestsSecretsInsert = Omit<
export type TSecretApprovalRequestsSecretsUpdate = Partial<Omit<TSecretApprovalRequestsSecrets, TImmutableDBKeys>>; TSecretApprovalRequestsSecrets,
TImmutableDBKeys
>;
export type TSecretApprovalRequestsSecretsUpdate = Partial<
Omit<TSecretApprovalRequestsSecrets, TImmutableDBKeys>
>;
@@ -11,16 +11,18 @@ export const SecretApprovalRequestsSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
policyId: z.string().uuid(), policyId: z.string().uuid(),
hasMerged: z.boolean().default(false), hasMerged: z.boolean().default(false),
status: z.string().default('open'), status: z.string().default("open"),
conflicts: z.unknown().nullable().optional(), conflicts: z.unknown().nullable().optional(),
slug: z.string(), slug: z.string(),
folderId: z.string().uuid(), folderId: z.string().uuid(),
statusChangeBy: z.string().uuid().nullable().optional(), statusChangeBy: z.string().uuid().nullable().optional(),
committerId: z.string().uuid(), committerId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretApprovalRequests = z.infer<typeof SecretApprovalRequestsSchema>; export type TSecretApprovalRequests = z.infer<typeof SecretApprovalRequestsSchema>;
export type TSecretApprovalRequestsInsert = Omit<TSecretApprovalRequests, TImmutableDBKeys>; export type TSecretApprovalRequestsInsert = Omit<TSecretApprovalRequests, TImmutableDBKeys>;
export type TSecretApprovalRequestsUpdate = Partial<Omit<TSecretApprovalRequests, TImmutableDBKeys>>; export type TSecretApprovalRequestsUpdate = Partial<
Omit<TSecretApprovalRequests, TImmutableDBKeys>
>;
@@ -12,11 +12,11 @@ export const SecretBlindIndexesSchema = z.object({
encryptedSaltCipherText: z.string(), encryptedSaltCipherText: z.string(),
saltIV: z.string(), saltIV: z.string(),
saltTag: z.string(), saltTag: z.string(),
algorithm: z.string().default('aes-256-gcm'), algorithm: z.string().default("aes-256-gcm"),
keyEncoding: z.string().default('utf8'), keyEncoding: z.string().default("utf8"),
projectId: z.string(), projectId: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretBlindIndexes = z.infer<typeof SecretBlindIndexesSchema>; export type TSecretBlindIndexes = z.infer<typeof SecretBlindIndexesSchema>;
@@ -14,7 +14,7 @@ export const SecretFolderVersionsSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
envId: z.string().uuid(), envId: z.string().uuid(),
folderId: z.string().uuid(), folderId: z.string().uuid()
}); });
export type TSecretFolderVersions = z.infer<typeof SecretFolderVersionsSchema>; export type TSecretFolderVersions = z.infer<typeof SecretFolderVersionsSchema>;
+1 -1
View File
@@ -14,7 +14,7 @@ export const SecretFoldersSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
envId: z.string().uuid(), envId: z.string().uuid(),
parentId: z.string().uuid().nullable().optional(), parentId: z.string().uuid().nullable().optional()
}); });
export type TSecretFolders = z.infer<typeof SecretFoldersSchema>; export type TSecretFolders = z.infer<typeof SecretFoldersSchema>;
+1 -1
View File
@@ -15,7 +15,7 @@ export const SecretImportsSchema = z.object({
position: z.number(), position: z.number(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
folderId: z.string().uuid(), folderId: z.string().uuid()
}); });
export type TSecretImports = z.infer<typeof SecretImportsSchema>; export type TSecretImports = z.infer<typeof SecretImportsSchema>;
@@ -11,7 +11,7 @@ export const SecretRotationOutputsSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
key: z.string(), key: z.string(),
secretId: z.string().uuid(), secretId: z.string().uuid(),
rotationId: z.string().uuid(), rotationId: z.string().uuid()
}); });
export type TSecretRotationOutputs = z.infer<typeof SecretRotationOutputsSchema>; export type TSecretRotationOutputs = z.infer<typeof SecretRotationOutputsSchema>;
+1 -1
View File
@@ -22,7 +22,7 @@ export const SecretRotationsSchema = z.object({
keyEncoding: z.string().nullable().optional(), keyEncoding: z.string().nullable().optional(),
envId: z.string().uuid(), envId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretRotations = z.infer<typeof SecretRotationsSchema>; export type TSecretRotations = z.infer<typeof SecretRotationsSchema>;
@@ -38,9 +38,11 @@ export const SecretScanningGitRisksSchema = z.object({
status: z.string().nullable().optional(), status: z.string().nullable().optional(),
orgId: z.string().uuid(), orgId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretScanningGitRisks = z.infer<typeof SecretScanningGitRisksSchema>; export type TSecretScanningGitRisks = z.infer<typeof SecretScanningGitRisksSchema>;
export type TSecretScanningGitRisksInsert = Omit<TSecretScanningGitRisks, TImmutableDBKeys>; export type TSecretScanningGitRisksInsert = Omit<TSecretScanningGitRisks, TImmutableDBKeys>;
export type TSecretScanningGitRisksUpdate = Partial<Omit<TSecretScanningGitRisks, TImmutableDBKeys>>; export type TSecretScanningGitRisksUpdate = Partial<
Omit<TSecretScanningGitRisks, TImmutableDBKeys>
>;
@@ -13,7 +13,7 @@ export const SecretSnapshotFoldersSchema = z.object({
folderVersionId: z.string().uuid(), folderVersionId: z.string().uuid(),
snapshotId: z.string().uuid(), snapshotId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretSnapshotFolders = z.infer<typeof SecretSnapshotFoldersSchema>; export type TSecretSnapshotFolders = z.infer<typeof SecretSnapshotFoldersSchema>;
@@ -13,7 +13,7 @@ export const SecretSnapshotSecretsSchema = z.object({
secretVersionId: z.string().uuid(), secretVersionId: z.string().uuid(),
snapshotId: z.string().uuid(), snapshotId: z.string().uuid(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretSnapshotSecrets = z.infer<typeof SecretSnapshotSecretsSchema>; export type TSecretSnapshotSecrets = z.infer<typeof SecretSnapshotSecretsSchema>;
+1 -1
View File
@@ -13,7 +13,7 @@ export const SecretSnapshotsSchema = z.object({
folderId: z.string().uuid(), folderId: z.string().uuid(),
parentFolderId: z.string().uuid().nullable().optional(), parentFolderId: z.string().uuid().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSecretSnapshots = z.infer<typeof SecretSnapshotsSchema>; export type TSecretSnapshots = z.infer<typeof SecretSnapshotsSchema>;
@@ -10,7 +10,7 @@ import { TImmutableDBKeys } from "./models";
export const SecretTagJunctionSchema = z.object({ export const SecretTagJunctionSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
secretsId: z.string().uuid(), secretsId: z.string().uuid(),
secret_tagsId: z.string().uuid(), secret_tagsId: z.string().uuid()
}); });
export type TSecretTagJunction = z.infer<typeof SecretTagJunctionSchema>; export type TSecretTagJunction = z.infer<typeof SecretTagJunctionSchema>;
+1 -1
View File
@@ -15,7 +15,7 @@ export const SecretTagsSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
createdBy: z.string().uuid().nullable().optional(), createdBy: z.string().uuid().nullable().optional(),
projectId: z.string(), projectId: z.string()
}); });
export type TSecretTags = z.infer<typeof SecretTagsSchema>; export type TSecretTags = z.infer<typeof SecretTagsSchema>;
@@ -10,9 +10,11 @@ import { TImmutableDBKeys } from "./models";
export const SecretVersionTagJunctionSchema = z.object({ export const SecretVersionTagJunctionSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
secret_versionsId: z.string().uuid(), secret_versionsId: z.string().uuid(),
secret_tagsId: z.string().uuid(), secret_tagsId: z.string().uuid()
}); });
export type TSecretVersionTagJunction = z.infer<typeof SecretVersionTagJunctionSchema>; export type TSecretVersionTagJunction = z.infer<typeof SecretVersionTagJunctionSchema>;
export type TSecretVersionTagJunctionInsert = Omit<TSecretVersionTagJunction, TImmutableDBKeys>; export type TSecretVersionTagJunctionInsert = Omit<TSecretVersionTagJunction, TImmutableDBKeys>;
export type TSecretVersionTagJunctionUpdate = Partial<Omit<TSecretVersionTagJunction, TImmutableDBKeys>>; export type TSecretVersionTagJunctionUpdate = Partial<
Omit<TSecretVersionTagJunction, TImmutableDBKeys>
>;
+1 -1
View File
@@ -21,7 +21,7 @@ export const ServiceTokensSchema = z.object({
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
createdBy: z.string(), createdBy: z.string(),
projectId: z.string(), projectId: z.string()
}); });
export type TServiceTokens = z.infer<typeof ServiceTokensSchema>; export type TServiceTokens = z.infer<typeof ServiceTokensSchema>;
+1 -1
View File
@@ -12,7 +12,7 @@ export const SuperAdminSchema = z.object({
initialized: z.boolean().default(false).nullable().optional(), initialized: z.boolean().default(false).nullable().optional(),
allowSignUp: z.boolean().default(true).nullable().optional(), allowSignUp: z.boolean().default(true).nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TSuperAdmin = z.infer<typeof SuperAdminSchema>; export type TSuperAdmin = z.infer<typeof SuperAdminSchema>;
+1 -1
View File
@@ -16,7 +16,7 @@ export const TrustedIpsSchema = z.object({
comment: z.string().nullable().optional(), comment: z.string().nullable().optional(),
projectId: z.string(), projectId: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TTrustedIps = z.infer<typeof TrustedIpsSchema>; export type TTrustedIps = z.infer<typeof TrustedIpsSchema>;
+1 -1
View File
@@ -12,7 +12,7 @@ export const UserActionsSchema = z.object({
action: z.string(), action: z.string(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
userId: z.string().uuid(), userId: z.string().uuid()
}); });
export type TUserActions = z.infer<typeof UserActionsSchema>; export type TUserActions = z.infer<typeof UserActionsSchema>;
@@ -21,7 +21,7 @@ export const UserEncryptionKeysSchema = z.object({
tag: z.string(), tag: z.string(),
salt: z.string(), salt: z.string(),
verifier: z.string(), verifier: z.string(),
userId: z.string().uuid(), userId: z.string().uuid()
}); });
export type TUserEncryptionKeys = z.infer<typeof UserEncryptionKeysSchema>; export type TUserEncryptionKeys = z.infer<typeof UserEncryptionKeysSchema>;
+1 -1
View File
@@ -19,7 +19,7 @@ export const UsersSchema = z.object({
mfaMethods: z.string().array().nullable().optional(), mfaMethods: z.string().array().nullable().optional(),
devices: z.unknown().nullable().optional(), devices: z.unknown().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date()
}); });
export type TUsers = z.infer<typeof UsersSchema>; export type TUsers = z.infer<typeof UsersSchema>;
+2 -2
View File
@@ -9,7 +9,7 @@ import { TImmutableDBKeys } from "./models";
export const WebhooksSchema = z.object({ export const WebhooksSchema = z.object({
id: z.string().uuid(), id: z.string().uuid(),
secretPath: z.string().default('/'), secretPath: z.string().default("/"),
url: z.string(), url: z.string(),
lastStatus: z.string().nullable().optional(), lastStatus: z.string().nullable().optional(),
lastRunErrorMessage: z.string().nullable().optional(), lastRunErrorMessage: z.string().nullable().optional(),
@@ -21,7 +21,7 @@ export const WebhooksSchema = z.object({
keyEncoding: z.string().nullable().optional(), keyEncoding: z.string().nullable().optional(),
createdAt: z.date(), createdAt: z.date(),
updatedAt: z.date(), updatedAt: z.date(),
envId: z.string().uuid(), envId: z.string().uuid()
}); });
export type TWebhooks = z.infer<typeof WebhooksSchema>; export type TWebhooks = z.infer<typeof WebhooksSchema>;
+2 -2
View File
@@ -14,7 +14,7 @@ export async function seed(knex: Knex): Promise<void> {
const [user] = await knex(TableName.Users) const [user] = await knex(TableName.Users)
.insert([ .insert([
{ {
// @ts-ignore to calculate predefined // @ts-expect-error exluded type id needs to be inserted here to keep it testable
id: seedData1.id, id: seedData1.id,
email: seedData1.email, email: seedData1.email,
superAdmin: true, superAdmin: true,
@@ -48,7 +48,7 @@ export async function seed(knex: Knex): Promise<void> {
]); ]);
await knex(TableName.AuthTokenSession).insert({ await knex(TableName.AuthTokenSession).insert({
// @ts-ignore // @ts-expect-error exluded type id needs to be inserted here to keep it testable
id: seedData1.token.id, id: seedData1.token.id,
userId: seedData1.id, userId: seedData1.id,
ip: "151.196.220.213", ip: "151.196.220.213",
+1 -1
View File
@@ -14,7 +14,7 @@ export async function seed(knex: Knex): Promise<void> {
const [org] = await knex(TableName.Organization) const [org] = await knex(TableName.Organization)
.insert([ .insert([
{ {
// @ts-ignore because we need that id for api calls // @ts-expect-error exluded type id needs to be inserted here to keep it testable
id: seedData1.organization.id, id: seedData1.organization.id,
name: "infisical", name: "infisical",
slug: "infisical", slug: "infisical",
+1 -1
View File
@@ -20,7 +20,7 @@ export async function seed(knex: Knex): Promise<void> {
name: seedData1.project.name, name: seedData1.project.name,
orgId: seedData1.organization.id, orgId: seedData1.organization.id,
slug: "first-project", slug: "first-project",
// @ts-ignore pre calc id // @ts-expect-error exluded type id needs to be inserted here to keep it testable
id: seedData1.project.id id: seedData1.project.id
}) })
.returning("*"); .returning("*");
@@ -1,3 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
// TODO(akhilmhdh): Fix this when licence service gets it type
import { z } from "zod"; import { z } from "zod";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -26,7 +26,6 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
}, },
onRequest: verifyAuth([AuthMode.JWT]), onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => { handler: async (req) => {
const role = await server.services.orgRole.createRole( const role = await server.services.orgRole.createRole(
req.permission.id, req.permission.id,
req.params.organizationId, req.params.organizationId,
@@ -58,7 +57,6 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
}, },
onRequest: verifyAuth([AuthMode.JWT]), onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => { handler: async (req) => {
const role = await server.services.orgRole.updateRole( const role = await server.services.orgRole.updateRole(
req.permission.id, req.permission.id,
req.params.organizationId, req.params.organizationId,
@@ -85,7 +83,6 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
}, },
onRequest: verifyAuth([AuthMode.JWT]), onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => { handler: async (req) => {
const role = await server.services.orgRole.deleteRole( const role = await server.services.orgRole.deleteRole(
req.permission.id, req.permission.id,
req.params.organizationId, req.params.organizationId,
@@ -114,7 +111,6 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
}, },
onRequest: verifyAuth([AuthMode.JWT]), onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => { handler: async (req) => {
const roles = await server.services.orgRole.listRoles( const roles = await server.services.orgRole.listRoles(
req.permission.id, req.permission.id,
req.params.organizationId req.params.organizationId
@@ -139,7 +135,6 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
}, },
onRequest: verifyAuth([AuthMode.JWT]), onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => { handler: async (req) => {
const { permissions, membership } = await server.services.orgRole.getUserPermission( const { permissions, membership } = await server.services.orgRole.getUserPermission(
req.permission.id, req.permission.id,
req.params.organizationId req.params.organizationId
@@ -141,7 +141,6 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
}, },
onRequest: verifyAuth([AuthMode.JWT]), onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => { handler: async (req) => {
const { permissions, membership } = await server.services.projectRole.getUserPermission( const { permissions, membership } = await server.services.projectRole.getUserPermission(
req.permission.id, req.permission.id,
req.params.projectId req.params.projectId
+10
View File
@@ -1,3 +1,11 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
// All the any rules are disabled because passport typesense with fastify is really poor
import { Authenticator } from "@fastify/passport"; import { Authenticator } from "@fastify/passport";
import fastifySession from "@fastify/session"; import fastifySession from "@fastify/session";
import { MultiSamlStrategy } from "@node-saml/passport-saml"; import { MultiSamlStrategy } from "@node-saml/passport-saml";
@@ -33,6 +41,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
new MultiSamlStrategy( new MultiSamlStrategy(
{ {
passReqToCallback: true, passReqToCallback: true,
// eslint-disable-next-line
getSamlOptions: async (req, done) => { getSamlOptions: async (req, done) => {
try { try {
const { ssoIdentifier } = req.params; const { ssoIdentifier } = req.params;
@@ -67,6 +76,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
} }
} }
}, },
// eslint-disable-next-line
async (req, profile, cb) => { async (req, profile, cb) => {
try { try {
const serverCfg = getServerCfg(); const serverCfg = getServerCfg();
@@ -111,17 +111,18 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
}), }),
response: { response: {
200: z.object({ 200: z.object({
approvals: sapPubSchema.merge(z.object({approvers:z.string().array()})).array() approvals: sapPubSchema.merge(z.object({ approvers: z.string().array() })).array()
}) })
} }
}, },
onRequest: verifyAuth([AuthMode.JWT]), onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => { handler: async (req) => {
const approvals = await server.services.secretApprovalPolicy.getSecretApprovalPolicyByProjectId({ const approvals =
actor: req.permission.type, await server.services.secretApprovalPolicy.getSecretApprovalPolicyByProjectId({
actorId: req.permission.id, actor: req.permission.type,
projectId: req.query.workspaceId actorId: req.permission.id,
}); projectId: req.query.workspaceId
});
return { approvals }; return { approvals };
} }
}); });
@@ -137,7 +138,7 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
}), }),
response: { response: {
200: z.object({ 200: z.object({
policy: sapPubSchema.merge(z.object({approvers:z.string().array()})).optional() policy: sapPubSchema.merge(z.object({ approvers: z.string().array() })).optional()
}) })
} }
}, },
@@ -174,11 +174,13 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
...req.auditLogInfo, ...req.auditLogInfo,
event: { event: {
type: isClosing ? EventType.SECRET_APPROVAL_CLOSED : EventType.SECRET_APPROVAL_REOPENED, type: isClosing ? EventType.SECRET_APPROVAL_CLOSED : EventType.SECRET_APPROVAL_REOPENED,
// eslint-disable-next-line
metadata: { metadata: {
[isClosing ? ("closedBy" as const) : ("reopenedBy" as const)]: [isClosing ? ("closedBy" as const) : ("reopenedBy" as const)]:
approval.statusChangeBy as string, approval.statusChangeBy as string,
secretApprovalRequestId: approval.id, secretApprovalRequestId: approval.id,
secretApprovalRequestSlug: approval.slug secretApprovalRequestSlug: approval.slug
// eslint-disable-next-line
} as any } as any
// akhilmhdh: had to apply any to avoid ts issue with this // akhilmhdh: had to apply any to avoid ts issue with this
} }
@@ -48,10 +48,10 @@ export const auditLogDALFactory = (db: TDbClient) => {
.limit(limit) .limit(limit)
.offset(offset); .offset(offset);
if (startDate) { if (startDate) {
sqlQuery.where("createdAt", ">=", startDate); void sqlQuery.where("createdAt", ">=", startDate);
} }
if (endDate) { if (endDate) {
sqlQuery.where("createdAt", "<=", endDate); void sqlQuery.where("createdAt", "<=", endDate);
} }
const docs = await sqlQuery; const docs = await sqlQuery;
return docs; return docs;
@@ -39,7 +39,7 @@ export const setupLicenceRequestWithStore = (
let token: string; let token: string;
const licenceReq = axios.create({ const licenceReq = axios.create({
baseURL, baseURL,
timeout: 35 * 1000, timeout: 35 * 1000
// signal: AbortSignal.timeout(60 * 1000) // signal: AbortSignal.timeout(60 * 1000)
}); });
@@ -47,7 +47,7 @@ export const setupLicenceRequestWithStore = (
const appCfg = getConfig(); const appCfg = getConfig();
const { const {
data: { token: authToken } data: { token: authToken }
} = await request.post( } = await request.post<{ token: string }>(
refreshUrl, refreshUrl,
{}, {},
{ {
@@ -75,18 +75,18 @@ export const setupLicenceRequestWithStore = (
licenceReq.interceptors.response.use( licenceReq.interceptors.response.use(
(response) => response, (response) => response,
async (err) => { async (err) => {
const originalRequest = err.config; const originalRequest = (err as AxiosError).config;
// eslint-disable-next-line // eslint-disable-next-line
if ((err as AxiosError)?.response?.status === 401 && !originalRequest._retry) { if ((err as AxiosError)?.response?.status === 401 && !(originalRequest as any)._retry) {
// eslint-disable-next-line // eslint-disable-next-line
originalRequest._retry = true; (originalRequest as any)._retry = true; // injected
// refresh // refresh
await refreshLicence(); await refreshLicence();
licenceReq.defaults.headers.common.Authorization = `Bearer ${token}`; licenceReq.defaults.headers.common.Authorization = `Bearer ${token}`;
return licenceReq(originalRequest); return licenceReq(originalRequest!);
} }
return Promise.reject(err); return Promise.reject(err);
@@ -13,7 +13,7 @@ export const licenseDALFactory = (db: TDbClient) => {
.where({ status: OrgMembershipStatus.Accepted }) .where({ status: OrgMembershipStatus.Accepted })
.andWhere((bd) => { .andWhere((bd) => {
if (orgId) { if (orgId) {
bd.where({ orgId }); void bd.where({ orgId });
} }
}) })
.count(); .count();
@@ -1,3 +1,9 @@
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
// eslint-disable @typescript-eslint/no-unsafe-assignment
// TODO(akhilmhdh): With tony find out the api structure and fill it here
import { ForbiddenError } from "@casl/ability"; import { ForbiddenError } from "@casl/ability";
import NodeCache from "node-cache"; import NodeCache from "node-cache";
@@ -92,7 +98,7 @@ export const licenseServiceFactory = ({
// else it would reach catch statement // else it would reach catch statement
isValidLicense = true; isValidLicense = true;
} catch (error) { } catch (error) {
logger.error(`init-license: encountered an error when init license [error=${error}]`); logger.error(`init-license: encountered an error when init license [error]`, error);
} }
}; };
@@ -119,7 +125,10 @@ export const licenseServiceFactory = ({
return currentPlan; return currentPlan;
} }
} catch (error) { } catch (error) {
logger.error(`getPlan: encountered an error when fetching pan [orgId=${orgId}] [projectId=${projectId}] [error=${error}]`); logger.error(
`getPlan: encountered an error when fetching pan [orgId=${orgId}] [projectId=${projectId}] [error]`,
error
);
return onPremFeatures; return onPremFeatures;
} }
return onPremFeatures; return onPremFeatures;
@@ -136,7 +145,7 @@ export const licenseServiceFactory = ({
if (instanceType === InstanceType.Cloud) { if (instanceType === InstanceType.Cloud) {
const { const {
data: { customerId } data: { customerId }
} = await licenseServerCloudApi.request.post( } = await licenseServerCloudApi.request.post<{ customerId: string }>(
"/api/license-server/v1/customers", "/api/license-server/v1/customers",
{ {
email, email,
@@ -239,17 +239,29 @@ export const buildServiceTokenProjectPermission = (
const { can, build } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility); const { can, build } = new AbilityBuilder<MongoAbility<ProjectPermissionSet>>(createMongoAbility);
scopes.forEach(({ secretPath, environment }) => { scopes.forEach(({ secretPath, environment }) => {
if (canWrite) { if (canWrite) {
// TODO: @Akhi // TODO: @Akhi
// @ts-expect-error type // @ts-expect-error type
can(ProjectPermissionActions.Edit, ProjectPermissionSub.Secrets, { secretPath: { $glob: secretPath }, environment }); can(ProjectPermissionActions.Edit, ProjectPermissionSub.Secrets, {
// @ts-expect-error type secretPath: { $glob: secretPath },
can(ProjectPermissionActions.Create, ProjectPermissionSub.Secrets, { secretPath: { $glob: secretPath }, environment }); environment
// @ts-expect-error type });
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Secrets, {secretPath: { $glob: secretPath }, environment }); // @ts-expect-error type
can(ProjectPermissionActions.Create, ProjectPermissionSub.Secrets, {
secretPath: { $glob: secretPath },
environment
});
// @ts-expect-error type
can(ProjectPermissionActions.Delete, ProjectPermissionSub.Secrets, {
secretPath: { $glob: secretPath },
environment
});
} }
if (canRead) { if (canRead) {
// @ts-expect-error type // @ts-expect-error type
can(ProjectPermissionActions.Read, ProjectPermissionSub.Secrets, { secretPath: { $glob: secretPath }, environment }); can(ProjectPermissionActions.Read, ProjectPermissionSub.Secrets, {
secretPath: { $glob: secretPath },
environment
});
} }
}); });
@@ -258,6 +270,8 @@ export const buildServiceTokenProjectPermission = (
export const projectNoAccessPermissions = buildNoAccessProjectPermission(); export const projectNoAccessPermissions = buildNoAccessProjectPermission();
/* eslint-disable */
/** /**
* Extracts and formats permissions from a CASL Ability object or a raw permission set. * Extracts and formats permissions from a CASL Ability object or a raw permission set.
* @param ability * @param ability
@@ -287,3 +301,5 @@ export const isAtLeastAsPrivilegedWorkspace = (
return set1.size >= set2.size; return set1.size >= set2.size;
}; };
/* eslint-enable */
@@ -239,9 +239,9 @@ export const samlConfigServiceFactory = ({
"64f23239a5d4ed17f1e544c4": "9256337f-e3da-43d7-8266-39c9276e8426", "64f23239a5d4ed17f1e544c4": "9256337f-e3da-43d7-8266-39c9276e8426",
"65348e49db355e6e4782571f": "b8a227c7-843e-410e-8982-b4976a599b69", "65348e49db355e6e4782571f": "b8a227c7-843e-410e-8982-b4976a599b69",
"657a219fc8a80c2eff97eb38": "fcab1573-ae7f-4fcf-9645-646207acf035" "657a219fc8a80c2eff97eb38": "fcab1573-ae7f-4fcf-9645-646207acf035"
}; };
const id = UUIDToMongoId[dto.id] ?? dto.id const id = UUIDToMongoId[dto.id] ?? dto.id;
ssoConfig = await samlConfigDAL.findById(id); ssoConfig = await samlConfigDAL.findById(id);
} }
@@ -252,7 +252,7 @@ export const samlConfigServiceFactory = ({
const { permission } = await permissionService.getOrgPermission( const { permission } = await permissionService.getOrgPermission(
dto.actor, dto.actor,
dto.actorId, dto.actorId,
ssoConfig!.orgId ssoConfig.orgId
); );
ForbiddenError.from(permission).throwUnlessCan( ForbiddenError.from(permission).throwUnlessCan(
OrgPermissionActions.Read, OrgPermissionActions.Read,
@@ -400,7 +400,7 @@ export const samlConfigServiceFactory = ({
isUserCompleted, isUserCompleted,
...(relayState ...(relayState
? { ? {
callbackPort: JSON.parse(relayState).callbackPort as string callbackPort: (JSON.parse(relayState) as { callbackPort: string }).callbackPort
} }
: {}) : {})
}, },
@@ -18,6 +18,7 @@ export const secretApprovalPolicyDALFactory = (db: TDbClient) => {
const sapFindQuery = (tx: Knex, filter: TFindFilter<TSecretApprovalPolicies>) => const sapFindQuery = (tx: Knex, filter: TFindFilter<TSecretApprovalPolicies>) =>
tx(TableName.SecretApprovalPolicy) tx(TableName.SecretApprovalPolicy)
// eslint-disable-next-line
.where(buildFindFilter(filter)) .where(buildFindFilter(filter))
.join( .join(
TableName.Environment, TableName.Environment,
@@ -1,7 +1,12 @@
import { Knex } from "knex"; import { Knex } from "knex";
import { TDbClient } from "@app/db"; import { TDbClient } from "@app/db";
import { SecretApprovalRequestsSchema, TableName, TSecretApprovalRequests } from "@app/db/schemas"; import {
SecretApprovalRequestsSchema,
TableName,
TSecretApprovalRequests,
TSecretApprovalRequestsSecrets
} from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { import {
ormify, ormify,
@@ -125,10 +130,11 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
`${TableName.SecretApprovalPolicyApprover}.policyId` `${TableName.SecretApprovalPolicyApprover}.policyId`
) )
.where({ projectId }) .where({ projectId })
.andWhere((bd) => .andWhere(
bd (bd) =>
.where(`${TableName.SecretApprovalPolicyApprover}.approverId`, membershipId) void bd
.orWhere(`${TableName.SecretApprovalRequest}.committerId`, membershipId) .where(`${TableName.SecretApprovalPolicyApprover}.approverId`, membershipId)
.orWhere(`${TableName.SecretApprovalRequest}.committerId`, membershipId)
) )
.select("status", `${TableName.SecretApprovalRequest}.id`) .select("status", `${TableName.SecretApprovalRequest}.id`)
.groupBy(`${TableName.SecretApprovalRequest}.id`, "status") .groupBy(`${TableName.SecretApprovalRequest}.id`, "status")
@@ -141,11 +147,13 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
return { return {
open: parseInt( open: parseInt(
(docs.find(({ status }) => status === RequestState.Open)?.count as string) || "0", (docs.find(({ status }) => status === RequestState.Open) as { count: string })?.count ||
"0",
10 10
), ),
closed: parseInt( closed: parseInt(
(docs.find(({ status }) => status === RequestState.Closed)?.count as string) || "0", (docs.find(({ status }) => status === RequestState.Closed) as { count: string })?.count ||
"0",
10 10
) )
}; };
@@ -195,7 +203,7 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
`${TableName.SecretApprovalRequest}.id`, `${TableName.SecretApprovalRequest}.id`,
`${TableName.SecretApprovalRequestReviewer}.requestId` `${TableName.SecretApprovalRequestReviewer}.requestId`
) )
.leftJoin( .leftJoin<TSecretApprovalRequestsSecrets>(
TableName.SecretApprovalRequestSecret, TableName.SecretApprovalRequestSecret,
`${TableName.SecretApprovalRequestSecret}.requestId`, `${TableName.SecretApprovalRequestSecret}.requestId`,
`${TableName.SecretApprovalRequest}.id` `${TableName.SecretApprovalRequest}.id`
@@ -208,10 +216,11 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
committerId: committer committerId: committer
}) })
) )
.andWhere((bd) => .andWhere(
bd (bd) =>
.where(`${TableName.SecretApprovalPolicyApprover}.approverId`, membershipId) void bd
.orWhere(`${TableName.SecretApprovalRequest}.committerId`, membershipId) .where(`${TableName.SecretApprovalPolicyApprover}.approverId`, membershipId)
.orWhere(`${TableName.SecretApprovalRequest}.committerId`, membershipId)
) )
.select(selectAllTableCols(TableName.SecretApprovalRequest)) .select(selectAllTableCols(TableName.SecretApprovalRequest))
.select( .select(
@@ -1,7 +1,7 @@
import { Knex } from "knex"; import { Knex } from "knex";
import { TDbClient } from "@app/db"; import { TDbClient } from "@app/db";
import { SecretApprovalRequestsSecretsSchema, TableName } from "@app/db/schemas"; import { SecretApprovalRequestsSecretsSchema, TableName, TSecretTags } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex"; import { ormify, selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
@@ -45,7 +45,7 @@ export const secretApprovalRequestSecretDALFactory = (db: TDbClient) => {
`${TableName.SecretVersionTag}.${TableName.SecretVersion}Id`, `${TableName.SecretVersionTag}.${TableName.SecretVersion}Id`,
`${TableName.SecretVersion}.id` `${TableName.SecretVersion}.id`
) )
.leftJoin( .leftJoin<TSecretTags>(
db.ref(TableName.SecretTag).as("secVerTag"), db.ref(TableName.SecretTag).as("secVerTag"),
`${TableName.SecretVersionTag}.${TableName.SecretTag}Id`, `${TableName.SecretVersionTag}.${TableName.SecretTag}Id`,
db.ref("id").withSchema("secVerTag") db.ref("id").withSchema("secVerTag")
@@ -192,9 +192,13 @@ export const secretApprovalRequestSecretDALFactory = (db: TDbClient) => {
secVerTagSlug: slug, secVerTagSlug: slug,
secVerTagColor: color secVerTagColor: color
}) => ({ }) => ({
// eslint-disable-next-line
id, id,
// eslint-disable-next-line
name, name,
// eslint-disable-next-line
slug, slug,
// eslint-disable-next-line
color color
}) })
} }
@@ -1,3 +1,8 @@
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-return */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import axios from "axios"; import axios from "axios";
import jmespath from "jmespath"; import jmespath from "jmespath";
@@ -37,7 +42,7 @@ export const interpolate = (data: any, getValue: (key: string) => unknown) => {
if ((data as { ref: string })?.ref) return getValue((data as { ref: string }).ref); if ((data as { ref: string })?.ref) return getValue((data as { ref: string }).ref);
const temp = data as Record<string, unknown>; // for converting ts object to record type const temp = data as Record<string, unknown>; // for converting ts object to record type
Object.keys(temp).forEach((key) => { Object.keys(temp).forEach((key) => {
temp[key as keyof typeof temp] = interpolate(data[key as keyof typeof temp], getValue); temp[key] = interpolate(data[key], getValue);
}); });
} }
return data; return data;
@@ -6,6 +6,7 @@ import {
infisicalSymmetricEncypt infisicalSymmetricEncypt
} from "@app/lib/crypto/encryption"; } from "@app/lib/crypto/encryption";
import { daysToMillisecond, secondsToMillis } from "@app/lib/dates"; import { daysToMillisecond, secondsToMillis } from "@app/lib/dates";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger"; import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid"; import { alphaNumericNanoId } from "@app/lib/nanoid";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue"; import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
@@ -34,7 +35,6 @@ import {
TSecretRotationDbFn, TSecretRotationDbFn,
TSecretRotationEncData TSecretRotationEncData
} from "./secret-rotation-queue-types"; } from "./secret-rotation-queue-types";
import { BadRequestError } from "@app/lib/errors";
export type TSecretRotationQueueFactory = ReturnType<typeof secretRotationQueueFactory>; export type TSecretRotationQueueFactory = ReturnType<typeof secretRotationQueueFactory>;
@@ -70,7 +70,7 @@ export const secretRotationQueueFactory = ({
}: TSecretRotationQueueFactoryDep) => { }: TSecretRotationQueueFactoryDep) => {
const addToQueue = async (rotationId: string, interval: number) => { const addToQueue = async (rotationId: string, interval: number) => {
const appCfg = getConfig(); const appCfg = getConfig();
queue.queue( await queue.queue(
QueueName.SecretRotation, QueueName.SecretRotation,
QueueJobs.SecretRotation, QueueJobs.SecretRotation,
{ rotationId }, { rotationId },
@@ -265,7 +265,7 @@ export const secretRotationQueueFactory = ({
return { return {
...el, ...el,
secretId: id, secretId: id,
secretBlindIndex: el.secretBlindIndex as string secretBlindIndex: el.secretBlindIndex
}; };
}), }),
tx tx
@@ -288,7 +288,7 @@ export const secretRotationQueueFactory = ({
logger.error(error); logger.error(error);
if (error instanceof DisableRotationErrors) { if (error instanceof DisableRotationErrors) {
if (job.id) { if (job.id) {
queue.stopRepeatableJobByJobId(QueueName.SecretRotation, job.id); await queue.stopRepeatableJobByJobId(QueueName.SecretRotation, job.id);
} }
} }
@@ -1,7 +1,7 @@
import { Knex } from "knex"; import { Knex } from "knex";
import { TDbClient } from "@app/db"; import { TDbClient } from "@app/db";
import { TableName,TGitAppOrgInsert } from "@app/db/schemas"; import { TableName, TGitAppOrgInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
@@ -1,7 +1,7 @@
import { Knex } from "knex"; import { Knex } from "knex";
import { TDbClient } from "@app/db"; import { TDbClient } from "@app/db";
import { TableName,TGitAppInstallSessionsInsert } from "@app/db/schemas"; import { TableName, TGitAppInstallSessionsInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
@@ -1,7 +1,7 @@
import { Knex } from "knex"; import { Knex } from "knex";
import { TDbClient } from "@app/db"; import { TDbClient } from "@app/db";
import { TableName,TSecretScanningGitRisksInsert } from "@app/db/schemas"; import { TableName, TSecretScanningGitRisksInsert } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors"; import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex"; import { ormify } from "@app/lib/knex";
@@ -1,3 +1,4 @@
import { Octokit } from "@octokit/rest";
import { exec } from "child_process"; import { exec } from "child_process";
import { mkdir, readFile, rm, writeFile } from "fs"; import { mkdir, readFile, rm, writeFile } from "fs";
import { tmpdir } from "os"; import { tmpdir } from "os";
@@ -11,7 +12,7 @@ export function createTempFolder(): Promise<string> {
const tempFolderName = Math.random().toString(36).substring(2); const tempFolderName = Math.random().toString(36).substring(2);
const tempFolderPath = join(tempDir, tempFolderName); const tempFolderPath = join(tempDir, tempFolderName);
mkdir(tempFolderPath, (err: any) => { mkdir(tempFolderPath, (err) => {
if (err) { if (err) {
reject(err); reject(err);
} else { } else {
@@ -115,7 +116,7 @@ export function convertKeysToLowercase<T>(obj: T): T {
} }
export async function scanFullRepoContentAndGetFindings( export async function scanFullRepoContentAndGetFindings(
octokit: any, octokit: Octokit,
installationId: string, installationId: string,
repositoryFullName: string repositoryFullName: string
): Promise<SecretMatch[]> { ): Promise<SecretMatch[]> {
@@ -125,11 +126,13 @@ export async function scanFullRepoContentAndGetFindings(
try { try {
const { const {
data: { token } data: { token }
} = await octokit.apps.createInstallationAccessToken({ installation_id: installationId }); } = await octokit.apps.createInstallationAccessToken({
installation_id: Number(installationId)
});
await cloneRepo(token, repositoryFullName, repoPath); await cloneRepo(token, repositoryFullName, repoPath);
await runInfisicalScanOnRepo(repoPath, findingsPath); await runInfisicalScanOnRepo(repoPath, findingsPath);
const findingsData = await readFindingsFile(findingsPath); const findingsData = await readFindingsFile(findingsPath);
return JSON.parse(findingsData); return JSON.parse(findingsData) as SecretMatch[];
} finally { } finally {
await deleteTempFolder(tempFolder); await deleteTempFolder(tempFolder);
} }
@@ -144,7 +147,7 @@ export async function scanContentAndGetFindings(textContent: string): Promise<Se
await writeTextToFile(filePath, textContent); await writeTextToFile(filePath, textContent);
await runInfisicalScan(filePath, findingsPath); await runInfisicalScan(filePath, findingsPath);
const findingsData = await readFindingsFile(findingsPath); const findingsData = await readFindingsFile(findingsPath);
return JSON.parse(findingsData); return JSON.parse(findingsData) as SecretMatch[];
} finally { } finally {
await deleteTempFolder(tempFolder); await deleteTempFolder(tempFolder);
} }
@@ -96,8 +96,8 @@ export const secretScanningQueueFactory = ({
path: filepath path: filepath
}); });
const { data }: any = fileContentsResponse; const { data } = fileContentsResponse;
const fileContent = Buffer.from(data.content, "base64").toString(); const fileContent = Buffer.from((data as { content: string }).content, "base64").toString();
// eslint-disable-next-line // eslint-disable-next-line
const findings = await scanContentAndGetFindings(`\n${fileContent}`); // extra line to count lines correctly const findings = await scanContentAndGetFindings(`\n${fileContent}`); // extra line to count lines correctly
@@ -118,7 +118,7 @@ export const secretScanningQueueFactory = ({
} }
await secretScanningDAL.transaction(async (tx) => { await secretScanningDAL.transaction(async (tx) => {
if (!Object.keys(allFindingsByFingerprint).length) return; if (!Object.keys(allFindingsByFingerprint).length) return;
secretScanningDAL.upsert( await secretScanningDAL.upsert(
Object.keys(allFindingsByFingerprint).map((key) => ({ Object.keys(allFindingsByFingerprint).map((key) => ({
installationId, installationId,
email: allFindingsByFingerprint[key].Email, email: allFindingsByFingerprint[key].Email,
@@ -186,7 +186,9 @@ export const secretScanningQueueFactory = ({
}); });
const findings = await scanFullRepoContentAndGetFindings( const findings = await scanFullRepoContentAndGetFindings(
octokit, // this is because of collision of octokit in probot and github
// eslint-disable-next-line
octokit as any,
installationId, installationId,
repository.fullName repository.fullName
); );
@@ -170,9 +170,7 @@ export const secretScanningServiceFactory = ({
await secretScanningDAL.transaction(async (tx) => { await secretScanningDAL.transaction(async (tx) => {
if (repositoryIds.length) { if (repositoryIds.length) {
await Promise.all( await Promise.all(
repositoryIds.map((repoId) => repositoryIds.map((repoId) => secretScanningDAL.delete({ repositoryId: repoId }, tx))
secretScanningDAL.delete({ repositoryId: repoId }, tx)
)
); );
} }
await gitAppOrgDAL.delete({ installationId }, tx); await gitAppOrgDAL.delete({ installationId }, tx);
@@ -162,7 +162,8 @@ export const snapshotDALFactory = (db: TDbClient) => {
try { try {
const data = await (tx || db) const data = await (tx || db)
.withRecursive("parent", (qb) => { .withRecursive("parent", (qb) => {
qb.from(TableName.Snapshot) void qb
.from(TableName.Snapshot)
.leftJoin<TSecretSnapshotFolders>( .leftJoin<TSecretSnapshotFolders>(
TableName.SnapshotFolder, TableName.SnapshotFolder,
`${TableName.SnapshotFolder}.snapshotId`, `${TableName.SnapshotFolder}.snapshotId`,
@@ -180,35 +181,36 @@ export const snapshotDALFactory = (db: TDbClient) => {
db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId") db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId")
) )
.where(`${TableName.Snapshot}.id`, snapshotId) .where(`${TableName.Snapshot}.id`, snapshotId)
.union((cb) => .union(
cb (cb) =>
.select(selectAllTableCols(TableName.Snapshot)) void cb
.select({ depth: db.raw("parent.depth + 1") }) .select(selectAllTableCols(TableName.Snapshot))
.select( .select({ depth: db.raw("parent.depth + 1") })
db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"), .select(
db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId") db.ref("name").withSchema(TableName.SecretFolderVersion).as("folderVerName"),
) db.ref("folderId").withSchema(TableName.SecretFolderVersion).as("folderVerId")
.from(TableName.Snapshot) )
.join<TSecretSnapshots, TSecretSnapshots & { secretId: string; max: number }>( .from(TableName.Snapshot)
db(TableName.Snapshot) .join<TSecretSnapshots, TSecretSnapshots & { secretId: string; max: number }>(
.groupBy("folderId") db(TableName.Snapshot)
.max("createdAt") .groupBy("folderId")
.select("folderId") .max("createdAt")
.as("latestVersion"), .select("folderId")
`${TableName.Snapshot}.createdAt`, .as("latestVersion"),
"latestVersion.max" `${TableName.Snapshot}.createdAt`,
) "latestVersion.max"
.leftJoin<TSecretSnapshotFolders>( )
TableName.SnapshotFolder, .leftJoin<TSecretSnapshotFolders>(
`${TableName.SnapshotFolder}.snapshotId`, TableName.SnapshotFolder,
`${TableName.Snapshot}.id` `${TableName.SnapshotFolder}.snapshotId`,
) `${TableName.Snapshot}.id`
.leftJoin<TSecretFolderVersions>( )
TableName.SecretFolderVersion, .leftJoin<TSecretFolderVersions>(
`${TableName.SnapshotFolder}.folderVersionId`, TableName.SecretFolderVersion,
`${TableName.SecretFolderVersion}.id` `${TableName.SnapshotFolder}.folderVersionId`,
) `${TableName.SecretFolderVersion}.id`
.join("parent", "parent.folderVerId", `${TableName.Snapshot}.folderId`) )
.join("parent", "parent.folderVerId", `${TableName.Snapshot}.folderId`)
); );
}) })
.orderBy("depth", "asc") .orderBy("depth", "asc")
@@ -285,7 +287,7 @@ export const snapshotDALFactory = (db: TDbClient) => {
label: "secretVersions" as const, label: "secretVersions" as const,
mapper: (el) => ({ mapper: (el) => ({
...SecretVersionsSchema.parse(el), ...SecretVersionsSchema.parse(el),
latestSecretVersion: el.latestSecretVersion latestSecretVersion: el.latestSecretVersion as number
}), }),
childrenMapper: [ childrenMapper: [
{ {
@@ -307,7 +309,7 @@ export const snapshotDALFactory = (db: TDbClient) => {
mapper: ({ folderVerId: id, folderVerName: name, latestFolderVersion }) => ({ mapper: ({ folderVerId: id, folderVerName: name, latestFolderVersion }) => ({
id, id,
name, name,
latestFolderVersion latestFolderVersion: latestFolderVersion as number
}) })
} }
] ]
+5 -2
View File
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { buildMongoQueryMatcher, MongoAbility } from "@casl/ability"; import { buildMongoQueryMatcher, MongoAbility } from "@casl/ability";
import { FieldCondition, FieldInstruction, JsInterpreter } from "@ucast/mongo2js"; import { FieldCondition, FieldInstruction, JsInterpreter } from "@ucast/mongo2js";
import picomatch from "picomatch"; import picomatch from "picomatch";
@@ -12,7 +13,7 @@ const $glob: FieldInstruction<string> = {
}; };
const glob: JsInterpreter<FieldCondition<string>> = (node, object, context) => { const glob: JsInterpreter<FieldCondition<string>> = (node, object, context) => {
const secretPath = context.get(object, node.field); const secretPath = context.get(object, node.field) as string;
const permissionSecretGlobPath = node.value; const permissionSecretGlobPath = node.value;
return picomatch.isMatch(secretPath, permissionSecretGlobPath, { strictSlashes: false }); return picomatch.isMatch(secretPath, permissionSecretGlobPath, { strictSlashes: false });
}; };
@@ -23,7 +24,9 @@ export const conditionsMatcher = buildMongoQueryMatcher({ $glob }, { glob });
* Extracts and formats permissions from a CASL Ability object or a raw permission set. * Extracts and formats permissions from a CASL Ability object or a raw permission set.
*/ */
const extractPermissions = (ability: MongoAbility) => const extractPermissions = (ability: MongoAbility) =>
ability.rules.map((permission) => `${permission.action}_${permission.subject}`); ability.rules.map(
(permission) => `${permission.action as string}_${permission.subject as string}`
);
/** /**
* Compares two sets of permissions to determine if the first set is at least as privileged as the second set. * Compares two sets of permissions to determine if the first set is at least as privileged as the second set.
+7 -2
View File
@@ -56,7 +56,12 @@ const envSchema = z
CLIENT_SECRET_GITHUB_LOGIN: zpStr(z.string().optional()), CLIENT_SECRET_GITHUB_LOGIN: zpStr(z.string().optional()),
CLIENT_ID_GITLAB_LOGIN: zpStr(z.string().optional()), CLIENT_ID_GITLAB_LOGIN: zpStr(z.string().optional()),
CLIENT_SECRET_GITLAB_LOGIN: zpStr(z.string().optional()), CLIENT_SECRET_GITLAB_LOGIN: zpStr(z.string().optional()),
CLIENT_GITLAB_LOGIN_URL: zpStr(z.string().optional().default(process.env.URL_GITLAB_LOGIN ?? GITLAB_URL)), // fallback since URL_GITLAB_LOGIN has been renamed CLIENT_GITLAB_LOGIN_URL: zpStr(
z
.string()
.optional()
.default(process.env.URL_GITLAB_LOGIN ?? GITLAB_URL)
), // fallback since URL_GITLAB_LOGIN has been renamed
// integration client secrets // integration client secrets
// heroku // heroku
CLIENT_ID_HEROKU: zpStr(z.string().optional()), CLIENT_ID_HEROKU: zpStr(z.string().optional()),
@@ -121,7 +126,7 @@ export const initEnvConfig = (logger: Logger) => {
logger.error(parsedEnv.error.issues); logger.error(parsedEnv.error.issues);
process.exit(-1); process.exit(-1);
} }
envCfg = Object.freeze(parsedEnv.data); envCfg = Object.freeze(parsedEnv.data);
return envCfg; return envCfg;
}; };
+1
View File
@@ -5,6 +5,7 @@ export const request = axios.create();
axiosRetry(request, { axiosRetry(request, {
retries: 3, retries: 3,
// eslint-disable-next-line
retryDelay: axiosRetry.exponentialDelay, retryDelay: axiosRetry.exponentialDelay,
retryCondition: (err) => axiosRetry.isNetworkError(err) || axiosRetry.isRetryableError(err) retryCondition: (err) => axiosRetry.isNetworkError(err) || axiosRetry.isRetryableError(err)
}); });
+1 -1
View File
@@ -223,7 +223,7 @@ export const infisicalSymmetricEncypt = (data: string) => {
throw new Error("Missing both encryption keys"); throw new Error("Missing both encryption keys");
}; };
export const infisicalSymmetricDecrypt = <T extends any = string>({ export const infisicalSymmetricDecrypt = <T = string>({
keyEncoding, keyEncoding,
ciphertext, ciphertext,
tag, tag,
+1 -1
View File
@@ -29,7 +29,7 @@ export const unique = <T, K extends string | number | symbol>(
): T[] => { ): T[] => {
const valueMap = array.reduce( const valueMap = array.reduce(
(acc, item) => { (acc, item) => {
const key = toKey ? toKey(item) : (item as any as string | number | symbol); const key = toKey ? toKey(item) : (item as unknown as string | number | symbol);
if (acc[key]) return acc; if (acc[key]) return acc;
acc[key] = item; acc[key] = item;
return acc; return acc;
+2 -2
View File
@@ -21,9 +21,9 @@ export const pick = <T extends object, TKeys extends keyof T>(
* object. Optional second argument shakes out values * object. Optional second argument shakes out values
* by custom evaluation. * by custom evaluation.
*/ */
export const shake = <RemovedKeys extends string, T = {}>( export const shake = <RemovedKeys extends string, T = object>(
obj: T, obj: T,
filter: (value: any) => boolean = (x) => x === undefined || x === null filter: (value: unknown) => boolean = (x) => x === undefined || x === null
): Omit<T, RemovedKeys> => { ): Omit<T, RemovedKeys> => {
if (!obj) return {} as T; if (!obj) return {} as T;
const keys = Object.keys(obj) as (keyof T)[]; const keys = Object.keys(obj) as (keyof T)[];
+16 -15
View File
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-misused-promises */
import { Knex } from "knex"; import { Knex } from "knex";
import { Tables } from "knex/types/tables"; import { Tables } from "knex/types/tables";
@@ -15,22 +16,22 @@ export const withTransaction = <K extends object>(db: Knex, dal: K) => ({
...dal ...dal
}); });
export type TFindFilter<R extends {} = any> = Partial<R> & { export type TFindFilter<R extends object = object> = Partial<R> & {
$in?: Partial<{ [k in keyof R]: R[k][] }>; $in?: Partial<{ [k in keyof R]: R[k][] }>;
}; };
export const buildFindFilter = export const buildFindFilter =
<R extends {} = any>({ $in, ...filter }: TFindFilter<R>) => <R extends object = object>({ $in, ...filter }: TFindFilter<R>) =>
(bd: Knex.QueryBuilder<R, R>) => { (bd: Knex.QueryBuilder<R, R>) => {
bd.where(filter); void bd.where(filter);
if ($in) { if ($in) {
Object.entries($in).forEach(([key, val]) => { Object.entries($in).forEach(([key, val]) => {
bd.whereIn(key as any, val as any); void bd.whereIn(key as never, val as never);
}); });
} }
return bd; return bd;
}; };
export type TFindOpt<R extends {} = any> = { export type TFindOpt<R extends object = object> = {
limit?: number; limit?: number;
offset?: number; offset?: number;
sort?: Array<[keyof R, "asc" | "desc"] | [keyof R, "asc" | "desc", "first" | "last"]>; sort?: Array<[keyof R, "asc" | "desc"] | [keyof R, "asc" | "desc", "first" | "last"]>;
@@ -53,7 +54,7 @@ export const ormify = <DbOps extends object, Tname extends keyof Tables>(
findById: async (id: string, tx?: Knex) => { findById: async (id: string, tx?: Knex) => {
try { try {
const result = await (tx || db)(tableName) const result = await (tx || db)(tableName)
.where({ id } as any) .where({ id } as never)
.first("*"); .first("*");
return result; return result;
} catch (error) { } catch (error) {
@@ -74,10 +75,10 @@ export const ormify = <DbOps extends object, Tname extends keyof Tables>(
) => { ) => {
try { try {
const query = (tx || db)(tableName).where(buildFindFilter(filter)); const query = (tx || db)(tableName).where(buildFindFilter(filter));
if (limit) query.limit(limit); if (limit) void query.limit(limit);
if (offset) query.offset(offset); if (offset) void query.offset(offset);
if (sort) { if (sort) {
query.orderBy( void query.orderBy(
sort.map(([column, order, nulls]) => ({ column: column as string, order, nulls })) sort.map(([column, order, nulls]) => ({ column: column as string, order, nulls }))
); );
} }
@@ -90,7 +91,7 @@ export const ormify = <DbOps extends object, Tname extends keyof Tables>(
create: async (data: Tables[Tname]["insert"], tx?: Knex) => { create: async (data: Tables[Tname]["insert"], tx?: Knex) => {
try { try {
const [res] = await (tx || db)(tableName) const [res] = await (tx || db)(tableName)
.insert(data as any) .insert(data as never)
.returning("*"); .returning("*");
return res; return res;
} catch (error) { } catch (error) {
@@ -101,7 +102,7 @@ export const ormify = <DbOps extends object, Tname extends keyof Tables>(
try { try {
if (!data.length) return []; if (!data.length) return [];
const res = await (tx || db)(tableName) const res = await (tx || db)(tableName)
.insert(data as any) .insert(data as never)
.returning("*"); .returning("*");
return res; return res;
} catch (error) { } catch (error) {
@@ -111,8 +112,8 @@ export const ormify = <DbOps extends object, Tname extends keyof Tables>(
updateById: async (id: string, data: Tables[Tname]["update"], tx?: Knex) => { updateById: async (id: string, data: Tables[Tname]["update"], tx?: Knex) => {
try { try {
const [res] = await (tx || db)(tableName) const [res] = await (tx || db)(tableName)
.where({ id } as any) .where({ id } as never)
.update(data as any) .update(data as never)
.returning("*"); .returning("*");
return res; return res;
} catch (error) { } catch (error) {
@@ -127,7 +128,7 @@ export const ormify = <DbOps extends object, Tname extends keyof Tables>(
try { try {
const res = await (tx || db)(tableName) const res = await (tx || db)(tableName)
.where(buildFindFilter(filter)) .where(buildFindFilter(filter))
.update(data as any) .update(data as never)
.returning("*"); .returning("*");
return res; return res;
} catch (error) { } catch (error) {
@@ -137,7 +138,7 @@ export const ormify = <DbOps extends object, Tname extends keyof Tables>(
deleteById: async (id: string, tx?: Knex) => { deleteById: async (id: string, tx?: Knex) => {
try { try {
const [res] = await (tx || db)(tableName) const [res] = await (tx || db)(tableName)
.where({ id } as any) .where({ id } as never)
.delete() .delete()
.returning("*"); .returning("*");
return res; return res;
+14 -4
View File
@@ -1,7 +1,16 @@
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
// TODO(akhilmhdh): make this better later
export const mergeOneToManyRelation = < export const mergeOneToManyRelation = <
T extends Record<string, any>, T extends Record<string, unknown>,
Pk extends keyof T, Pk extends keyof T,
P extends Record<string, any>, P extends Record<string, unknown>,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint
C extends any, C extends any,
Ck extends string = "child" Ck extends string = "child"
>( >(
@@ -22,7 +31,7 @@ export const mergeOneToManyRelation = <
const parent = parentMapper(row) as any; const parent = parentMapper(row) as any;
parent[childKey] = []; parent[childKey] = [];
groupedRecord.push(parent); groupedRecord.push(parent);
prevPkId = pk; prevPkId = pk as string;
prevPkIndex += 1; prevPkIndex += 1;
} }
groupedRecord[prevPkIndex][childKey].push(childMapper(row)); groupedRecord[prevPkIndex][childKey].push(childMapper(row));
@@ -41,6 +50,7 @@ export type TSqlPackRelationships<
childrenMapper: C; childrenMapper: C;
}; };
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint
export type TChildMapper<T extends {}, U extends string = string, R extends unknown = unknown> = { export type TChildMapper<T extends {}, U extends string = string, R extends unknown = unknown> = {
key: keyof T; key: keyof T;
label: U; label: U;
@@ -82,7 +92,7 @@ const sqlChildMapper = <
const ck = `${prefix}-${label}-${doc[childPk]}`; const ck = `${prefix}-${label}-${doc[childPk]}`;
const val = mapper(doc); const val = mapper(doc);
if (!lookupTable.has(ck)) { if (!lookupTable.has(ck)) {
if (typeof val !== "undefined" && val !== null) docsByPk[pk as keyof P][label].push(val); if (typeof val !== "undefined" && val !== null) docsByPk[pk][label].push(val);
lookupTable.add(ck); lookupTable.add(ck);
} }
if (nestedMappers && val) { if (nestedMappers && val) {
+1 -1
View File
@@ -1 +1 @@
export { initLogger,logger } from "./logger"; export { initLogger, logger } from "./logger";
+6 -4
View File
@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
// logger follows a singleton pattern // logger follows a singleton pattern
// easier to use it that's all. // easier to use it that's all.
import pino, { Logger } from "pino"; import pino, { Logger } from "pino";
@@ -14,10 +15,10 @@ const logLevelToSeverityLookup: Record<string, string> = {
// eslint-disable-next-line import/no-mutable-exports // eslint-disable-next-line import/no-mutable-exports
export let logger: Readonly<Logger>; export let logger: Readonly<Logger>;
// akhilmhdh: // akhilmhdh:
// The logger is not placed in the main app config to avoid a circular dependency. // The logger is not placed in the main app config to avoid a circular dependency.
// The config requires the logger to display errors when an invalid environment is supplied. // The config requires the logger to display errors when an invalid environment is supplied.
// On the other hand, the logger needs the config to obtain credentials for AWS or other transports. // On the other hand, the logger needs the config to obtain credentials for AWS or other transports.
// By keeping the logger separate, it becomes an independent package. // By keeping the logger separate, it becomes an independent package.
const loggerConfig = z.object({ const loggerConfig = z.object({
@@ -66,6 +67,7 @@ export const initLogger = async () => {
}) })
} }
}, },
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
transport transport
); );
return logger; return logger;
+1 -1
View File
@@ -1,4 +1,4 @@
import { z,ZodTypeAny } from "zod"; import { z, ZodTypeAny } from "zod";
// this is a patched zod string to remove empty string to undefined // this is a patched zod string to remove empty string to undefined
export const zpStr = <T extends ZodTypeAny>( export const zpStr = <T extends ZodTypeAny>(
+4 -2
View File
@@ -18,19 +18,21 @@ const run = async () => {
const server = await main({ db, smtp, logger, queue }); const server = await main({ db, smtp, logger, queue });
const bootstrap = await bootstrapCheck({ db }); const bootstrap = await bootstrapCheck({ db });
// eslint-disable-next-line
process.on("SIGINT", async () => { process.on("SIGINT", async () => {
await server.close(); await server.close();
await db.destroy(); await db.destroy();
process.exit(0); process.exit(0);
}); });
// eslint-disable-next-line
process.on("SIGTERM", async () => { process.on("SIGTERM", async () => {
await server.close(); await server.close();
await db.destroy(); await db.destroy();
process.exit(0); process.exit(0);
}); });
server.listen({ await server.listen({
port: appCfg.PORT, port: appCfg.PORT,
host: appCfg.HOST, host: appCfg.HOST,
listenTextResolver: (address) => { listenTextResolver: (address) => {
@@ -40,4 +42,4 @@ const run = async () => {
}); });
}; };
run(); void run();
+5 -5
View File
@@ -63,14 +63,14 @@ export type TQueueJobTypes = {
export type TQueueServiceFactory = ReturnType<typeof queueServiceFactory>; export type TQueueServiceFactory = ReturnType<typeof queueServiceFactory>;
export const queueServiceFactory = (redisUrl: string) => { export const queueServiceFactory = (redisUrl: string) => {
const connection = new Redis(redisUrl, { maxRetriesPerRequest: null }); const connection = new Redis(redisUrl, { maxRetriesPerRequest: null });
const queueContainer: Record< const queueContainer = {} as Record<
QueueName, QueueName,
Queue<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]> Queue<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]>
> = {} as any; >;
const workerContainer: Record< const workerContainer = {} as Record<
QueueName, QueueName,
Worker<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]> Worker<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]>
> = {} as any; >;
const start = <T extends QueueName>( const start = <T extends QueueName>(
name: T, name: T,
@@ -93,7 +93,7 @@ export const queueServiceFactory = (redisUrl: string) => {
>(name, jobFn, { connection }); >(name, jobFn, { connection });
}; };
const listen = async < const listen = <
T extends QueueName, T extends QueueName,
U extends keyof WorkerListener<TQueueJobTypes[T]["payload"], void, TQueueJobTypes[T]["name"]> U extends keyof WorkerListener<TQueueJobTypes[T]["payload"], void, TQueueJobTypes[T]["name"]>
>( >(
+1 -1
View File
@@ -6,7 +6,7 @@ import { getConfig } from "@app/lib/config/env";
export const globalRateLimiterCfg = (): RateLimitPluginOptions => { export const globalRateLimiterCfg = (): RateLimitPluginOptions => {
const appCfg = getConfig(); const appCfg = getConfig();
const redis = appCfg.isRedisConfigured const redis = appCfg.isRedisConfigured
? new Redis(appCfg.REDIS_URL as string, { connectTimeout: 500, maxRetriesPerRequest: 1 }) ? new Redis(appCfg.REDIS_URL, { connectTimeout: 500, maxRetriesPerRequest: 1 })
: null; : null;
return { return {
@@ -106,9 +106,7 @@ export const injectIdentity = fp(async (server: FastifyZodProvider) => {
break; break;
} }
case AuthMode.SERVICE_TOKEN: { case AuthMode.SERVICE_TOKEN: {
const serviceToken = await server.services.serviceToken.fnValidateServiceToken( const serviceToken = await server.services.serviceToken.fnValidateServiceToken(token);
token as string
);
req.auth = { req.auth = {
authMode: AuthMode.SERVICE_TOKEN as const, authMode: AuthMode.SERVICE_TOKEN as const,
serviceToken, serviceToken,

Some files were not shown because too many files have changed in this diff Show More