repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
keyshade
github_2023
keyshade-xyz
typescript
AuthorityCheckerService.checkAuthorityOverProject
public async checkAuthorityOverProject( input: AuthorityInput ): Promise<ProjectWithSecrets> { const { userId, entity, authorities, prisma } = input let project: ProjectWithSecrets try { if (entity.slug) { project = await prisma.project.findUnique({ where: { slug: entity.slug }, include: { secrets: true } }) } else { project = await prisma.project.findFirst({ where: { name: entity.name, workspace: { members: { some: { userId: userId } } } }, include: { secrets: true } }) } } catch (error) { this.customLoggerService.error(error) throw new InternalServerErrorException(error) } if (!project) { throw new NotFoundException(`Project ${entity.slug} not found`) } const permittedAuthoritiesForProject: Set<Authority> = await getCollectiveProjectAuthorities(userId, project, prisma) const permittedAuthoritiesForWorkspace: Set<Authority> = await getCollectiveWorkspaceAuthorities( project.workspaceId, userId, prisma ) const projectAccessLevel = project.accessLevel switch (projectAccessLevel) { case ProjectAccessLevel.GLOBAL: // In the global case, we check if the authorities being passed in // contains just the READ_PROJECT authority. If not, we need to // check if the user has access to the other authorities mentioned as well. if ( authorities.length !== 1 || !authorities.includes(Authority.READ_PROJECT) ) { this.checkHasPermissionOverEntity( permittedAuthoritiesForWorkspace, authorities, userId ) } break case ProjectAccessLevel.INTERNAL: this.checkHasPermissionOverEntity( permittedAuthoritiesForWorkspace, authorities, userId ) break case ProjectAccessLevel.PRIVATE: this.checkHasPermissionOverEntity( permittedAuthoritiesForProject, authorities, userId ) break } return project }
/** * Checks if the user has the required authorities to access the given project. * * @param input The input object containing the userId, entity, authorities, and prisma client * @returns The project if the user has the required authorities * @throws InternalServerErrorException if there's an error when communicating with the database * @throws NotFoundException if the project is not found * @throws UnauthorizedException if the user does not have the required authorities */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L96-L177
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthorityCheckerService.checkAuthorityOverEnvironment
public async checkAuthorityOverEnvironment( input: AuthorityInput ): Promise<EnvironmentWithProject> { const { userId, entity, authorities, prisma } = input let environment: EnvironmentWithProject try { if (entity.slug) { environment = await prisma.environment.findUnique({ where: { slug: entity.slug }, include: { project: true } }) } else { environment = await prisma.environment.findFirst({ where: { name: entity.name, project: { workspace: { members: { some: { userId: userId } } } } }, include: { project: true } }) } } catch (error) { this.customLoggerService.error(error) throw new InternalServerErrorException(error) } if (!environment) { throw new NotFoundException(`Environment ${entity.slug} not found`) } const permittedAuthorities = await getCollectiveEnvironmentAuthorities( userId, environment, prisma ) this.checkHasPermissionOverEntity(permittedAuthorities, authorities, userId) return environment }
/** * Checks if the user has the required authorities to access the given environment. * * @param input The input object containing the userId, entity, authorities, and prisma client * @returns The environment if the user has the required authorities * @throws InternalServerErrorException if there's an error when communicating with the database * @throws NotFoundException if the environment is not found * @throws UnauthorizedException if the user does not have the required authorities */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L188-L234
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthorityCheckerService.checkAuthorityOverVariable
public async checkAuthorityOverVariable( input: AuthorityInput ): Promise<VariableWithProjectAndVersion> { const { userId, entity, authorities, prisma } = input let variable: VariableWithProjectAndVersion try { if (entity.slug) { variable = await prisma.variable.findUnique({ where: { slug: entity.slug }, include: { versions: true, project: true } }) } else { variable = await prisma.variable.findFirst({ where: { name: entity.name, project: { workspace: { members: { some: { userId: userId } } } } }, include: { versions: true, project: true } }) } } catch (error) { this.customLoggerService.error(error) throw new InternalServerErrorException(error) } if (!variable) { throw new NotFoundException(`Variable ${entity.slug} not found`) } const permittedAuthorities = await getCollectiveProjectAuthorities( userId, variable.project, prisma ) this.checkHasPermissionOverEntity(permittedAuthorities, authorities, userId) return variable }
/** * Checks if the user has the required authorities to access the given variable. * * @param input The input object containing the userId, entity, authorities, and prisma client * @returns The variable if the user has the required authorities * @throws InternalServerErrorException if there's an error when communicating with the database * @throws NotFoundException if the variable is not found * @throws UnauthorizedException if the user does not have the required authorities */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L245-L293
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthorityCheckerService.checkAuthorityOverSecret
public async checkAuthorityOverSecret( input: AuthorityInput ): Promise<SecretWithProjectAndVersion> { const { userId, entity, authorities, prisma } = input let secret: SecretWithProjectAndVersion try { if (entity.slug) { secret = await prisma.secret.findUnique({ where: { slug: entity.slug }, include: { versions: true, project: true } }) } else { secret = await prisma.secret.findFirst({ where: { name: entity.name, project: { workspace: { members: { some: { userId: userId } } } } }, include: { versions: true, project: true } }) } } catch (error) { this.customLoggerService.error(error) throw new InternalServerErrorException(error) } if (!secret) { throw new NotFoundException(`Secret ${entity.slug} not found`) } const permittedAuthorities = await getCollectiveProjectAuthorities( userId, secret.project, prisma ) this.checkHasPermissionOverEntity(permittedAuthorities, authorities, userId) return secret }
/** * Checks if the user has the required authorities to access the given secret. * * @param input The input object containing the userId, entity, authorities, and prisma client * @returns The secret if the user has the required authorities * @throws InternalServerErrorException if there's an error when communicating with the database * @throws NotFoundException if the secret is not found * @throws UnauthorizedException if the user does not have the required authorities */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L304-L352
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthorityCheckerService.checkAuthorityOverIntegration
public async checkAuthorityOverIntegration( input: AuthorityInput ): Promise<IntegrationWithWorkspace> { const { userId, entity, authorities, prisma } = input let integration: IntegrationWithWorkspace | null try { if (entity.slug) { integration = await prisma.integration.findUnique({ where: { slug: entity.slug }, include: { workspace: true } }) } else { integration = await prisma.integration.findFirst({ where: { name: entity.name, workspace: { members: { some: { userId: userId } } } }, include: { workspace: true } }) } } catch (error) { this.customLoggerService.error(error) throw new InternalServerErrorException(error) } if (!integration) { throw new NotFoundException(`Integration ${entity.slug} not found`) } const permittedAuthorities = await getCollectiveWorkspaceAuthorities( integration.workspaceId, userId, prisma ) this.checkHasPermissionOverEntity(permittedAuthorities, authorities, userId) if (integration.projectId) { const project = await prisma.project.findUnique({ where: { id: integration.projectId } }) if (!project) { throw new NotFoundException( `Project with ID ${integration.projectId} not found` ) } const projectAuthorities = await getCollectiveProjectAuthorities( userId, project, prisma ) this.checkHasPermissionOverEntity(projectAuthorities, authorities, userId) } return integration }
/** * Checks if the user has the required authorities to access the given integration. * * @param input The input object containing the userId, entity, authorities, and prisma client * @returns The integration if the user has the required authorities * @throws InternalServerErrorException if there's an error when communicating with the database * @throws NotFoundException if the integration is not found * @throws UnauthorizedException if the user does not have the required authorities */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L363-L431
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthorityCheckerService.checkHasPermissionOverEntity
private checkHasPermissionOverEntity( permittedAuthorities: Set<Authority>, authorities: Authority[], userId: string ): void { // We commence the check if WORKSPACE_ADMIN isn't in the list of permitted authorities if (!permittedAuthorities.has(Authority.WORKSPACE_ADMIN)) { // Check if the authority object passed is completely contained within the permitted authorities const hasRequiredAuthority = authorities.every((auth) => permittedAuthorities.has(auth) ) if (!hasRequiredAuthority) { throw new UnauthorizedException( `User ${userId} does not have any of the required authorities to perform the action` ) } } }
/** * Checks if the user has all the required authorities to perform an action. * Throws UnauthorizedException if the user does not have all the required authorities. * * @param permittedAuthorities The set of authorities that the user has * @param authorities The set of authorities required to perform the action * @param userId The slug of the user * @returns void * @throws UnauthorizedException if the user does not have all the required authorities */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L443-L461
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
getQueryString
const getQueryString = (query: QueryOptions) => { return Object.keys(query) .map((key) => `${key}=${query[key]}`) .join('&') }
//convert query object to query string to use in links
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/paginate.ts#L24-L28
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
sampleRateSchema
const sampleRateSchema = (name: string) => z .string() .optional() .transform((val) => (val === undefined ? undefined : parseFloat(val))) .pipe(z.number().min(0).max(1).optional()) .refine((val) => val === undefined || !isNaN(val), { message: `${name} must be a number between 0 and 1` })
/* Apparently zod validates empty strings. https://github.com/colinhacks/zod/issues/2466 So if you have your variable in the .env set to empty, zod turns a blind eye to it since it parses to VARIABLE = '' To over come this you need to set a min length (.min()) if you want zod to throw an error Zod only throws errors if a variable is missing completely from .env Use the .optional() property if you are okay with a variable being omitted from .env file */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/env/env.schema.ts#L21-L29
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
QueryTransformPipe.transform
transform(value: any, metadata: ArgumentMetadata) { if (metadata.type === 'query') { if (metadata.data === 'limit') return isNaN(value) || value === 0 ? 10 : parseInt(value) if (metadata.data === 'page') return isNaN(value) ? 0 : Number(value) } return value }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/pipes/query.transform.pipe.ts#L10-L17
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.createEnvironment
async createEnvironment( user: User, dto: CreateEnvironment, projectSlug: Project['slug'] ) { // Check if the user has the required role to create an environment const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [ Authority.CREATE_ENVIRONMENT, Authority.READ_ENVIRONMENT, Authority.READ_PROJECT ], prisma: this.prisma }) const projectId = project.id // Check if an environment with the same name already exists await this.environmentExists(dto.name, project) // Create the environment const environment = await this.prisma.environment.create({ data: { name: dto.name, slug: await generateEntitySlug(dto.name, 'ENVIRONMENT', this.prisma), description: dto.description, project: { connect: { id: projectId } }, lastUpdatedBy: { connect: { id: user.id } } }, include: { lastUpdatedBy: { select: { id: true, name: true, profilePictureUrl: true, email: true } } } }) await createEvent( { triggeredBy: user, entity: environment, type: EventType.ENVIRONMENT_ADDED, source: EventSource.ENVIRONMENT, title: `Environment created`, metadata: { environmentId: environment.id, name: environment.name, projectId, projectName: project.name }, workspaceId: project.workspaceId }, this.prisma ) this.logger.log( `Environment ${environment.name} created in project ${project.name} (${project.id})` ) return environment }
/** * Creates a new environment in the given project. * * This endpoint requires the following authorities: * - `CREATE_ENVIRONMENT` on the project * - `READ_ENVIRONMENT` on the project * - `READ_PROJECT` on the project * * If the user does not have the required authorities, a `ForbiddenException` is thrown. * * If an environment with the same name already exists in the project, a `ConflictException` is thrown. * * The created environment is returned, with the slug generated using the `name` and `ENVIRONMENT` as the entity type. * * An event of type `ENVIRONMENT_ADDED` is created, with the following metadata: * - `environmentId`: The ID of the created environment * - `name`: The name of the created environment * - `projectId`: The ID of the project in which the environment was created * - `projectName`: The name of the project in which the environment was created * * @param user The user that is creating the environment * @param dto The data for the new environment * @param projectSlug The slug of the project in which to create the environment * @returns The created environment */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L58-L132
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.updateEnvironment
async updateEnvironment( user: User, dto: UpdateEnvironment, environmentSlug: Environment['slug'] ) { const environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: environmentSlug }, authorities: [ Authority.UPDATE_ENVIRONMENT, Authority.READ_ENVIRONMENT, Authority.READ_PROJECT ], prisma: this.prisma }) // Check if an environment with the same name already exists dto.name && (await this.environmentExists(dto.name, environment.project)) // Update the environment const updatedEnvironment = await this.prisma.environment.update({ where: { id: environment.id }, data: { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'ENVIRONMENT', this.prisma) : environment.slug, description: dto.description, lastUpdatedById: user.id } }) const project = environment.project await createEvent( { triggeredBy: user, entity: updatedEnvironment, type: EventType.ENVIRONMENT_UPDATED, source: EventSource.ENVIRONMENT, title: `Environment updated`, metadata: { environmentId: updatedEnvironment.id, name: updatedEnvironment.name, projectId: updatedEnvironment.projectId }, workspaceId: project.workspaceId }, this.prisma ) this.logger.log( `Environment ${updatedEnvironment.name} updated in project ${project.name} (${project.id})` ) return updatedEnvironment }
/** * Updates an environment in the given project. * * This endpoint requires the following authorities: * - `UPDATE_ENVIRONMENT` on the environment * - `READ_ENVIRONMENT` on the environment * - `READ_PROJECT` on the project * * If the user does not have the required authorities, a `ForbiddenException` is thrown. * * If an environment with the same name already exists in the project, a `ConflictException` is thrown. * * The updated environment is returned, with the slug generated using the `name` and `ENVIRONMENT` as the entity type. * * An event of type `ENVIRONMENT_UPDATED` is created, with the following metadata: * - `environmentId`: The ID of the updated environment * - `name`: The name of the updated environment * - `projectId`: The ID of the project in which the environment was updated * - `projectName`: The name of the project in which the environment was updated * * @param user The user that is updating the environment * @param dto The data for the updated environment * @param environmentSlug The slug of the environment to update * @returns The updated environment */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L159-L218
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.getEnvironment
async getEnvironment(user: User, environmentSlug: Environment['slug']) { const environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma }) delete environment.project return environment }
/** * Gets an environment by its slug. * * This endpoint requires the `READ_ENVIRONMENT` authority on the environment. * * If the user does not have the required authority, a `ForbiddenException` is thrown. * * The returned environment object does not include the project property. * * @param user The user that is requesting the environment * @param environmentSlug The slug of the environment to get * @returns The environment */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L233-L245
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.getEnvironmentsOfProject
async getEnvironmentsOfProject( user: User, projectSlug: Project['slug'], page: number, limit: number, sort: string, order: string, search: string ) { const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma }) const projectId = project.id // Get the environments for the required page const items = await this.prisma.environment.findMany({ where: { projectId, name: { contains: search } }, select: { id: true, name: true, slug: true, description: true, createdAt: true, updatedAt: true, lastUpdatedBy: { select: { id: true, email: true, profilePictureUrl: true, name: true } } }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { [sort]: order } }) // Parse the secret and variable counts for each environment for (const environment of items) { const secretCount = await this.getSecretCount(environment.id) const variableCount = await this.getVariableCount(environment.id) environment['secrets'] = secretCount environment['variables'] = variableCount } // Calculate metadata for pagination const totalCount = await this.prisma.environment.count({ where: { projectId, name: { contains: search } } }) const metadata = paginate(totalCount, `/environment/all/${projectSlug}`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search }) return { items, metadata } }
/** * Gets a list of all environments in the given project. * * This endpoint requires the `READ_ENVIRONMENT` authority on the project. * * If the user does not have the required authority, a `ForbiddenException` is thrown. * * The returned list of environments is paginated and sorted according to the provided parameters. * * The metadata object contains the following properties: * - `href`: The URL to the current page * - `next`: The URL to the next page (if it exists) * - `prev`: The URL to the previous page (if it exists) * - `totalPages`: The total number of pages * - `totalItems`: The total number of items * - `limit`: The maximum number of items per page * - `page`: The current page number * - `sort`: The sort field * - `order`: The sort order * - `search`: The search query * * @param user The user that is requesting the environments * @param projectSlug The slug of the project in which to get the environments * @param page The page number * @param limit The maximum number of items per page * @param sort The sort field * @param order The sort order * @param search The search query * @returns An object with a list of environments and metadata */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L277-L352
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.deleteEnvironment
async deleteEnvironment(user: User, environmentSlug: Environment['slug']) { const environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.DELETE_ENVIRONMENT], prisma: this.prisma }) // Check if this is the only existing environment const count = await this.prisma.environment.count({ where: { projectId: environment.projectId } }) if (count === 1) { throw new BadRequestException( 'Cannot delete the last environment in the project' ) } // Delete the environment await this.prisma.environment.delete({ where: { id: environment.id } }) await createEvent( { triggeredBy: user, type: EventType.ENVIRONMENT_DELETED, source: EventSource.ENVIRONMENT, entity: environment, title: `Environment deleted`, metadata: { environmentId: environment.id, name: environment.name, projectId: environment.projectId }, workspaceId: environment.project.workspaceId }, this.prisma ) this.logger.log( `Environment ${environment.name} deleted in project ${environment.project.name} (${environment.project.id})` ) }
/** * Deletes an environment in a project. * * This endpoint requires the `DELETE_ENVIRONMENT` authority on the environment. * * If the user does not have the required authority, a `ForbiddenException` is thrown. * * If this is the only existing environment in the project, a `BadRequestException` is thrown. * * An event of type `ENVIRONMENT_DELETED` is created, with the following metadata: * - `environmentId`: The ID of the deleted environment * - `name`: The name of the deleted environment * - `projectId`: The ID of the project in which the environment was deleted * * @param user The user that is deleting the environment * @param environmentSlug The slug of the environment to delete */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L371-L419
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.environmentExists
private async environmentExists(name: Environment['name'], project: Project) { const { id: projectId, slug } = project if ( (await this.prisma.environment.findUnique({ where: { projectId_name: { projectId, name } } })) !== null ) { throw new ConflictException( `Environment with name ${name} already exists in project ${slug}` ) } }
/** * Checks if an environment with the given name already exists in the given project. * @throws ConflictException if an environment with the given name already exists * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L426-L443
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.getSecretCount
private async getSecretCount( environmentId: Environment['id'] ): Promise<number> { const secrets = await this.prisma.secretVersion.findMany({ distinct: ['secretId'], where: { environmentId } }) return secrets.length }
/** * Counts the number of unique secrets in an environment. * @param environmentId The ID of the environment to count secrets for. * @returns The number of unique secrets in the environment. * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L451-L462
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
EnvironmentService.getVariableCount
private async getVariableCount( environmentId: Environment['id'] ): Promise<number> { const variables = await this.prisma.variableVersion.findMany({ distinct: ['variableId'], where: { environmentId } }) return variables.length }
/** * Counts the number of unique variables in an environment. * @param environmentId The ID of the environment to count variables for. * @returns The number of unique variables in the environment. * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/environment/service/environment.service.ts#L470-L481
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
FeedbackService.registerFeedback
async registerFeedback(feedback: string): Promise<void> { if (!feedback || feedback.trim().length === 0) { throw new BadRequestException('Feedback cannot be null or empty') } const adminEmail = process.env.FEEDBACK_FORWARD_EMAIL await this.mailService.feedbackEmail(adminEmail, feedback.trim()) }
/** * Registers a feedback to be sent to the admin's email. * @param feedback The feedback to be sent. * @throws {BadRequestException} If the feedback is null or empty. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/feedback/service/feedback.service.ts#L15-L22
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
IntegrationFactory.createIntegration
public static createIntegration( integrationType: IntegrationType ): BaseIntegration { switch (integrationType) { case IntegrationType.DISCORD: return new DiscordIntegration() case IntegrationType.SLACK: return new SlackIntegration() default: throw new InternalServerErrorException('Integration type not found') } }
/** * Create an integration based on the integration type. * @param integrationType The type of integration to create. * @returns The integration object. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/integration/plugins/factory/integration.factory.ts#L17-L28
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
IntegrationService.createIntegration
async createIntegration( user: User, dto: CreateIntegration, workspaceSlug: Workspace['slug'] ) { // Check if the user is permitted to create integrations in the workspace const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.CREATE_INTEGRATION, Authority.READ_WORKSPACE], prisma: this.prisma }) const workspaceId = workspace.id // Check if integration with the same name already exists await this.existsByNameAndWorkspaceId(dto.name, workspace) let project: Project | null = null let environment: Environment | null = null // Check if the user has READ authority over the project if (dto.projectSlug) { project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: dto.projectSlug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma }) } // Check if only environmentId is provided if (dto.environmentSlug && !dto.projectSlug) { throw new BadRequestException( 'Environment can only be provided if project is also provided' ) } // Check if the user has READ authority over the environment if (dto.environmentSlug) { environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: dto.environmentSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma }) } // Create the integration object const integrationObject = IntegrationFactory.createIntegration(dto.type) // Check for permitted events integrationObject.validatePermittedEvents(dto.notifyOn) // Check for authentication parameters integrationObject.validateMetadataParameters(dto.metadata) // Create the integration const integration = await this.prisma.integration.create({ data: { name: dto.name, slug: await generateEntitySlug(dto.name, 'INTEGRATION', this.prisma), type: dto.type, metadata: dto.metadata, notifyOn: dto.notifyOn, environmentId: environment?.id, projectId: project?.id, workspaceId } }) this.logger.log( `Integration ${integration.id} created by user ${user.id} in workspace ${workspaceId}` ) await createEvent( { triggeredBy: user, entity: integration, type: EventType.INTEGRATION_ADDED, source: EventSource.INTEGRATION, title: `Integration ${integration.name} created`, metadata: { integrationId: integration.id }, workspaceId: workspaceId }, this.prisma ) return integration }
/** * Creates a new integration in the given workspace. The user needs to have * `CREATE_INTEGRATION` and `READ_WORKSPACE` authority in the workspace. * * If the integration is of type `PROJECT`, the user needs to have `READ_PROJECT` * authority in the project specified by `projectSlug`. * * If the integration is of type `ENVIRONMENT`, the user needs to have `READ_ENVIRONMENT` * authority in the environment specified by `environmentSlug`. * * If the integration is of type `PROJECT` and `environmentSlug` is provided, * the user needs to have `READ_ENVIRONMENT` authority in the environment specified * by `environmentSlug`. * * The integration is created with the given name, slug, type, metadata and * notifyOn events. The slug is generated using the `name` and a unique * identifier. * * @param user The user creating the integration * @param dto The integration data * @param workspaceSlug The slug of the workspace the integration is being * created in * @returns The created integration */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/integration/service/integration.service.ts#L60-L152
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
IntegrationService.updateIntegration
async updateIntegration( user: User, dto: UpdateIntegration, integrationSlug: Integration['slug'] ) { const integration = await this.authorityCheckerService.checkAuthorityOverIntegration({ userId: user.id, entity: { slug: integrationSlug }, authorities: [Authority.UPDATE_INTEGRATION], prisma: this.prisma }) const integrationId = integration.id // Check if the name of the integration is being changed, and if so, check if the new name is unique if (dto.name) { await this.existsByNameAndWorkspaceId(dto.name, integration.workspace) } let project: Project | null = null let environment: Environment | null = null // If the project is being changed, check if the user has READ authority over the new project if (dto.projectSlug) { project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: dto.projectSlug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma }) } // Check if only environmentId is provided, or if the integration has no project associated from prior if (dto.environmentSlug && !integration.projectId && !dto.projectSlug) { throw new BadRequestException( 'Environment can only be provided if project is also provided' ) } // If the environment is being changed, check if the user has READ authority over the new environment if (dto.environmentSlug) { environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: dto.environmentSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma }) } // Create the integration object const integrationObject = IntegrationFactory.createIntegration( integration.type ) // Check for permitted events dto.notifyOn && integrationObject.validatePermittedEvents(dto.notifyOn) // Check for authentication parameters dto.metadata && integrationObject.validateMetadataParameters(dto.metadata) // Update the integration const updatedIntegration = await this.prisma.integration.update({ where: { id: integrationId }, data: { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'INTEGRATION', this.prisma) : integration.slug, metadata: dto.metadata, notifyOn: dto.notifyOn, environmentId: environment?.id, projectId: project?.id } }) this.logger.log( `Integration ${integrationId} updated by user ${user.id} in workspace ${integration.workspaceId}` ) await createEvent( { triggeredBy: user, entity: updatedIntegration, type: EventType.INTEGRATION_UPDATED, source: EventSource.INTEGRATION, title: `Integration ${updatedIntegration.name} updated`, metadata: { integrationId: updatedIntegration.id }, workspaceId: integration.workspaceId }, this.prisma ) return updatedIntegration }
/** * Updates an integration. The user needs to have `UPDATE_INTEGRATION` authority * over the integration. * * If the integration is of type `PROJECT`, the user needs to have `READ_PROJECT` * authority in the project specified by `projectSlug`. * * If the integration is of type `ENVIRONMENT`, the user needs to have `READ_ENVIRONMENT` * authority in the environment specified by `environmentSlug`. * * If the integration is of type `PROJECT` and `environmentSlug` is provided, * the user needs to have `READ_ENVIRONMENT` authority in the environment specified * by `environmentSlug`. * * The integration is updated with the given name, slug, metadata and * notifyOn events. * * @param user The user updating the integration * @param dto The integration data * @param integrationSlug The slug of the integration to update * @returns The updated integration */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/integration/service/integration.service.ts#L176-L272
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
IntegrationService.getIntegration
async getIntegration(user: User, integrationSlug: Integration['slug']) { return this.authorityCheckerService.checkAuthorityOverIntegration({ userId: user.id, entity: { slug: integrationSlug }, authorities: [Authority.READ_INTEGRATION], prisma: this.prisma }) }
/** * Retrieves an integration by its slug. The user needs to have `READ_INTEGRATION` * authority over the integration. * * @param user The user retrieving the integration * @param integrationSlug The slug of the integration to retrieve * @returns The integration with the given slug */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/integration/service/integration.service.ts#L282-L289
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
IntegrationService.getAllIntegrationsOfWorkspace
async getAllIntegrationsOfWorkspace( user: User, workspaceSlug: Workspace['slug'], page: number, limit: number, sort: string, order: string, search: string ) { // Check if the user has READ authority over the workspace const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_INTEGRATION], prisma: this.prisma }) const workspaceId = workspace.id // We need to return only those integrations that have the following properties: // - belong to the workspace // - does not belong to any project // - does not belong to any project where the user does not have READ authority // Get the projects the user has READ authority over const membership = await this.prisma.workspaceMember.findUnique({ where: { workspaceId_userId: { userId: user.id, workspaceId } } }) const workspaceRoles = await this.prisma.workspaceRole.findMany({ where: { workspaceId, workspaceMembers: { some: { workspaceMemberId: membership.id } } }, include: { projects: { include: { project: true } } } }) const projectIds = workspaceRoles .map((role) => role.projects.map((p) => p.projectId)) .flat() || [] // Get all integrations in the workspace const integrations = await this.prisma.integration.findMany({ where: { name: { contains: search }, workspaceId, OR: [ { projectId: null }, { projectId: { in: projectIds } } ] }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { [sort]: order } }) // Calculate metadata for pagination const totalCount = await this.prisma.integration.count({ where: { name: { contains: search }, workspaceId, OR: [ { projectId: null }, { projectId: { in: projectIds } } ] } }) const metadata = paginate(totalCount, `/integration/all/${workspaceSlug}`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search }) return { items: integrations, metadata } }
/** * Retrieves all integrations in a workspace that the user has READ authority over. * * The user needs to have `READ_INTEGRATION` authority over the workspace. * * The results are paginated and can be sorted by name ascending or descending. * * @param user The user retrieving the integrations * @param workspaceSlug The slug of the workspace to retrieve integrations from * @param page The page number of the results * @param limit The number of items per page * @param sort The property to sort the results by (default: name) * @param order The order to sort the results by (default: ascending) * @param search The string to search for in the integration names * @returns A paginated list of integrations in the workspace */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/integration/service/integration.service.ts#L309-L418
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
IntegrationService.deleteIntegration
async deleteIntegration(user: User, integrationSlug: Integration['slug']) { const integration = await this.authorityCheckerService.checkAuthorityOverIntegration({ userId: user.id, entity: { slug: integrationSlug }, authorities: [Authority.DELETE_INTEGRATION], prisma: this.prisma }) const integrationId = integration.id await this.prisma.integration.delete({ where: { id: integrationId } }) this.logger.log( `Integration ${integrationId} deleted by user ${user.id} in workspace ${integration.workspaceId}` ) await createEvent( { triggeredBy: user, entity: integration, type: EventType.INTEGRATION_DELETED, source: EventSource.INTEGRATION, title: `Integration ${integration.name} deleted`, metadata: { integrationId: integration.id }, workspaceId: integration.workspaceId }, this.prisma ) }
/** * Deletes an integration by its slug. The user needs to have `DELETE_INTEGRATION` * authority over the integration. * * @param user The user deleting the integration * @param integrationSlug The slug of the integration to delete * @returns Nothing */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/integration/service/integration.service.ts#L428-L460
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
IntegrationService.existsByNameAndWorkspaceId
private async existsByNameAndWorkspaceId( name: Integration['name'], workspace: Workspace ) { const workspaceId = workspace.id if ( (await this.prisma.integration.findUnique({ where: { workspaceId_name: { workspaceId, name } } })) !== null ) throw new ConflictException( 'Integration with the same name already exists in the workspace' ) }
/** * Checks if an integration with the same name already exists in the workspace. * Throws a ConflictException if the integration already exists. * * @param name The name of the integration to check * @param workspace The workspace to check in */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/integration/service/integration.service.ts#L469-L488
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.findUserByEmail
async findUserByEmail(email: string): Promise<User | null> { return await this.prisma.user.findUnique({ where: { email } }) }
/** * Find a user by email * @param email the email to search for * @returns the user if found, null otherwise */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L14-L20
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.findUserById
async findUserById(id: string): Promise<User | null> { return await this.prisma.user.findUnique({ where: { id } }) }
/** * Find a user by the user id * @param id The id of the user to find * @returns the user if found, null otherwise */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L27-L33
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.findUsers
async findUsers( page: number, limit: number, sort: string, order: string, search: string ): Promise<User[]> { return await this.prisma.user.findMany({ skip: (page - 1) * limit, take: limit, orderBy: { [sort]: order }, where: { OR: [ { name: { contains: search } }, { email: { contains: search } } ] } }) }
/** * Find all users * @param page The page number * @param limit The number of items per page * @param sort The field to sort by * @param order The order to sort by * @param search The search string * @returns The list of users */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L44-L72
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.createUser
async createUser(email: string): Promise<User> { return await this.prisma.user.create({ data: { email } }) }
/** * Create a user with the given email. The onboarding process * will aim at updating the user further. * @param email The email of the user to create * @returns */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L80-L86
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.updateUser
async updateUser(id: string, data: Partial<User>): Promise<User> { return await this.prisma.user.update({ where: { id }, data }) }
/** * Update an existing user * @param id ID of the user to update * @param data The data to update * @returns The updated user */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L94-L101
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.deleteUser
async deleteUser(id: string): Promise<User> { return await this.prisma.user.delete({ where: { id } }) }
/** * Delete a user by id * @param id The id of the user to delete * @returns The deleted user */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L108-L114
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.isOtpValid
async isOtpValid(email: string, otp: string): Promise<boolean> { const timeNow = new Date() return ( (await this.prisma.otp.count({ where: { code: otp, user: { email }, expiresAt: { gt: timeNow } } })) > 0 ) }
/** * An OTP is valid if it exists, is not expired, and is associated with the given email * @param email the email against which to check the OTP * @param otp the OTP code to check * @returns returns true if the OTP is valid, false otherwise */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L122-L137
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
PrismaRepository.invalidateOldOtps
private async invalidateOldOtps(email: string): Promise<void> { const user = await this.prisma.user.findUnique({ where: { email } }) if (user) { await this.prisma.otp.deleteMany({ where: { userId: user.id, expiresAt: { gte: new Date() } } }) } }
/** * Invalidate Old OTPs for a User * * This method invalidates old OTPs (One-Time Passwords) associated with a user. * It finds and deletes OTPs that belong to the user and have not expired yet. * * @param email - The email address of the user for whom old OTPs should be invalidated. * * @example * ```typescript * await invalidateOldOtps('[email protected]'); * ``` */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/prisma/prisma.repository.ts#L172-L189
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.createProject
async createProject( user: User, workspaceSlug: Workspace['slug'], dto: CreateProject ) { // Check if the workspace exists or not const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.CREATE_PROJECT], prisma: this.prisma }) const workspaceId = workspace.id // Check if project with this name already exists for the user if (await this.projectExists(dto.name, workspaceId)) throw new ConflictException( `Project with this name **${dto.name}** already exists` ) // Create the public and private key pair const { publicKey, privateKey } = createKeyPair() const data: any = { name: dto.name, slug: await generateEntitySlug(dto.name, 'PROJECT', this.prisma), description: dto.description, storePrivateKey: dto.accessLevel === ProjectAccessLevel.GLOBAL ? true : dto.storePrivateKey, // If the project is global, the private key must be stored publicKey, accessLevel: dto.accessLevel } // Check if the private key should be stored // PLEASE DON'T STORE YOUR PRIVATE KEYS WITH US!! if (dto.storePrivateKey) { data.privateKey = privateKey } const userId = user.id const newProjectId = v4() const adminRole = await this.prisma.workspaceRole.findFirst({ where: { workspaceId: workspaceId, hasAdminAuthority: true } }) // Create and return the project const createNewProject = this.prisma.project.create({ data: { id: newProjectId, ...data, workspace: { connect: { id: workspaceId } }, lastUpdatedBy: { connect: { id: userId } } } }) const addProjectToAdminRoleOfItsWorkspace = this.prisma.workspaceRole.update({ where: { id: adminRole.id }, data: { projects: { create: { project: { connect: { id: newProjectId } } } } } }) const createEnvironmentOps = [] // Create and assign the environments provided in the request, if any // or create a default environment if (dto.environments && dto.environments.length > 0) { for (const environment of dto.environments) { createEnvironmentOps.push( this.prisma.environment.create({ data: { name: environment.name, slug: await generateEntitySlug( environment.name, 'ENVIRONMENT', this.prisma ), description: environment.description, projectId: newProjectId, lastUpdatedById: user.id } }) ) } } else { createEnvironmentOps.push( this.prisma.environment.create({ data: { name: 'default', slug: await generateEntitySlug( 'default', 'ENVIRONMENT', this.prisma ), description: 'Default environment for the project', projectId: newProjectId, lastUpdatedById: user.id } }) ) } const [newProject] = await this.prisma.$transaction([ createNewProject, addProjectToAdminRoleOfItsWorkspace, ...createEnvironmentOps ]) await createEvent( { triggeredBy: user, entity: newProject, type: EventType.PROJECT_CREATED, source: EventSource.PROJECT, title: `Project created`, metadata: { projectId: newProject.id, name: newProject.name, workspaceId, workspaceName: workspace.name }, workspaceId }, this.prisma ) this.log.debug(`Created project ${newProject}`) // It is important that we log before the private key is set // in order to not log the private key newProject.privateKey = privateKey return newProject }
/** * Creates a new project in a workspace * * @param user The user who is creating the project * @param workspaceSlug The slug of the workspace where the project will be created * @param dto The data for the new project * @returns The newly created project */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L50-L210
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.updateProject
async updateProject( user: User, projectSlug: Project['slug'], dto: UpdateProject ) { // Check if the user has the authority to update the project let authority: Authority = Authority.UPDATE_PROJECT // Only admins can change the visibility of the project if (dto.accessLevel) authority = Authority.WORKSPACE_ADMIN const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [authority], prisma: this.prisma }) // Check if project with this name already exists for the user if ( (dto.name && (await this.projectExists(dto.name, user.id))) || project.name === dto.name ) throw new ConflictException( `Project with this name **${dto.name}** already exists` ) if (dto.accessLevel) { const currentAccessLevel = project.accessLevel if ( currentAccessLevel !== ProjectAccessLevel.GLOBAL && dto.accessLevel === ProjectAccessLevel.GLOBAL ) { // If the project is being made global, the private key must be stored // This is because we want anyone to see the secrets in the project dto.storePrivateKey = true dto.privateKey = dto.privateKey || project.privateKey // We can't make the project global if a private key isn't supplied, // because we need to decrypt the secrets if (!dto.privateKey) { throw new BadRequestException( 'Private key is required to make the project GLOBAL' ) } } else if ( currentAccessLevel === ProjectAccessLevel.GLOBAL && dto.accessLevel !== ProjectAccessLevel.GLOBAL ) { dto.storePrivateKey = false dto.regenerateKeyPair = true // At this point, we already will have the private key since the project is global dto.privateKey = project.privateKey } } const data: Partial<Project> = { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'PROJECT', this.prisma) : project.slug, description: dto.description, storePrivateKey: dto.storePrivateKey, privateKey: dto.storePrivateKey ? dto.privateKey : null, accessLevel: dto.accessLevel } // If the access level is changed to PRIVATE or internal, we would // also need to unlink all the forks if ( dto.accessLevel !== ProjectAccessLevel.GLOBAL && project.accessLevel === ProjectAccessLevel.GLOBAL ) { data.isForked = false data.forkedFromId = null } const versionUpdateOps = [] let privateKey = dto.privateKey let publicKey = project.publicKey if (dto.regenerateKeyPair) { if (dto.privateKey || project.privateKey) { const { txs, newPrivateKey, newPublicKey } = await this.updateProjectKeyPair( project, dto.privateKey || project.privateKey, dto.storePrivateKey ) privateKey = newPrivateKey publicKey = newPublicKey versionUpdateOps.push(...txs) } else { throw new BadRequestException( 'Private key is required to regenerate the key pair' ) } } // Update and return the project const updateProjectOp = this.prisma.project.update({ where: { id: project.id }, data: { ...data, lastUpdatedById: user.id } }) const [updatedProject] = await this.prisma.$transaction([ updateProjectOp, ...versionUpdateOps ]) await createEvent( { triggeredBy: user, entity: updatedProject, type: EventType.PROJECT_UPDATED, source: EventSource.PROJECT, title: `Project updated`, metadata: { projectId: updatedProject.id, name: updatedProject.name }, workspaceId: updatedProject.workspaceId }, this.prisma ) this.log.debug(`Updated project ${updatedProject.id}`) return { ...updatedProject, privateKey, publicKey } }
/** * Updates a project. * * @param user The user who is updating the project * @param projectSlug The slug of the project to update * @param dto The data to update the project with * @returns The updated project * * @throws ConflictException If a project with the same name already exists for the user * @throws BadRequestException If the private key is required but not supplied */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L223-L365
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.forkProject
async forkProject( user: User, projectSlug: Project['slug'], forkMetadata: ForkProject ) { const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma }) let workspaceId = null if (forkMetadata.workspaceSlug) { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: forkMetadata.workspaceSlug }, authorities: [Authority.CREATE_PROJECT], prisma: this.prisma }) workspaceId = workspace.id } else { const defaultWorkspace = await this.prisma.workspaceMember.findFirst({ where: { userId: user.id, workspace: { isDefault: true } } }) workspaceId = defaultWorkspace.workspaceId } const newProjectName = forkMetadata.name || project.name // Check if project with this name already exists for the user if (await this.projectExists(newProjectName, workspaceId)) throw new ConflictException( `Project with this name **${newProjectName}** already exists in the selected workspace` ) const { privateKey, publicKey } = createKeyPair() const userId = user.id const newProjectId = v4() const adminRole = await this.prisma.workspaceRole.findFirst({ where: { workspaceId, hasAdminAuthority: true } }) // Create and return the project const createNewProject = this.prisma.project.create({ data: { id: newProjectId, name: newProjectName, slug: await generateEntitySlug(newProjectName, 'PROJECT', this.prisma), description: project.description, storePrivateKey: forkMetadata.storePrivateKey || project.storePrivateKey, publicKey: publicKey, privateKey: forkMetadata.storePrivateKey || project.storePrivateKey ? privateKey : null, accessLevel: project.accessLevel, isForked: true, forkedFromId: project.id, workspaceId: workspaceId, lastUpdatedById: userId } }) const addProjectToAdminRoleOfItsWorkspace = this.prisma.workspaceRole.update({ where: { id: adminRole.id }, data: { projects: { create: { project: { connect: { id: newProjectId } } } } } }) const copyProjectOp = await this.copyProjectData( user, { id: project.id, privateKey: project.privateKey }, { id: newProjectId, publicKey }, true ) const [newProject] = await this.prisma.$transaction([ createNewProject, addProjectToAdminRoleOfItsWorkspace, ...copyProjectOp ]) await createEvent( { triggeredBy: user, entity: newProject, type: EventType.PROJECT_CREATED, source: EventSource.PROJECT, title: `Project created`, metadata: { projectId: newProject.id, name: newProject.name, workspaceId, workspaceName: workspaceId }, workspaceId }, this.prisma ) this.log.debug(`Created project ${newProject}`) return newProject }
/** * Forks a project. * * @param user The user who is creating the new project * @param projectSlug The slug of the project to fork * @param forkMetadata The metadata for the new project * @returns The newly forked project * * @throws ConflictException If a project with the same name already exists for the user * @throws BadRequestException If the private key is required but not supplied */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L378-L512
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.unlinkParentOfFork
async unlinkParentOfFork(user: User, projectSlug: Project['slug']) { const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.UPDATE_PROJECT], prisma: this.prisma }) const projectId = project.id await this.prisma.project.update({ where: { id: projectId }, data: { isForked: false, forkedFromId: null } }) }
/** * Unlinks a forked project from its parent project. * * @param user The user who is unlinking the project * @param projectSlug The slug of the project to unlink * @returns The updated project * * @throws BadRequestException If the project is not a forked project * @throws UnauthorizedException If the user does not have the authority to update the project */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L524-L543
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.syncFork
async syncFork(user: User, projectSlug: Project['slug'], hardSync: boolean) { const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.UPDATE_PROJECT], prisma: this.prisma }) const projectId = project.id if (!project.isForked || project.forkedFromId == null) { throw new BadRequestException( `Project ${projectSlug} is not a forked project` ) } const forkedFromProject = await this.prisma.project.findUnique({ where: { id: project.forkedFromId } }) const parentProject = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: forkedFromProject.slug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma }) const copyProjectOp = await this.copyProjectData( user, { id: parentProject.id, privateKey: parentProject.privateKey }, { id: projectId, publicKey: project.publicKey }, hardSync ) await this.prisma.$transaction(copyProjectOp) }
/** * Syncs a forked project with its parent project. * * @param user The user who is syncing the project * @param projectSlug The slug of the project to sync * @param hardSync Whether to do a hard sync or not. If true, all items in the * forked project will be replaced with the items from the parent project. If * false, only items that are not present in the forked project will be added * from the parent project. * * @throws BadRequestException If the project is not a forked project * @throws UnauthorizedException If the user does not have the authority to update the project */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L558-L602
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.deleteProject
async deleteProject(user: User, projectSlug: Project['slug']) { const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.DELETE_PROJECT], prisma: this.prisma }) const op = [] // Remove the fork relationships op.push( this.prisma.project.updateMany({ where: { forkedFromId: project.id }, data: { isForked: false, forkedFromId: null } }) ) // Delete the project op.push( this.prisma.project.delete({ where: { id: project.id } }) ) await this.prisma.$transaction(op) await createEvent( { triggeredBy: user, type: EventType.PROJECT_DELETED, source: EventSource.PROJECT, entity: project, title: `Project deleted`, metadata: { projectId: project.id, name: project.name }, workspaceId: project.workspaceId }, this.prisma ) this.log.debug(`Deleted project ${project}`) }
/** * Deletes a project. * @param user The user who is deleting the project * @param projectSlug The slug of the project to delete * * @throws UnauthorizedException If the user does not have the authority to delete the project */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L611-L663
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.getAllProjectForks
async getAllProjectForks( user: User, projectSlug: Project['slug'], page: number, limit: number ) { const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma }) const projectId = project.id const forks = await this.prisma.project.findMany({ where: { forkedFromId: projectId } }) const forksAllowed = forks.filter(async (fork) => { const allowed = (await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: fork.slug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma })) != null return allowed }) const items = forksAllowed.slice(page * limit, (page + 1) * limit) // Calculate metadata const metadata = paginate( forksAllowed.length, `/project/${projectSlug}/forks`, { page, limit: limitMaxItemsPerPage(limit) } ) return { items, metadata } }
/** * Gets all the forks of a project. * * @param user The user who is requesting the forks * @param projectSlug The slug of the project to get forks for * @param page The page number to get the forks for * @param limit The number of forks to get per page * @returns An object with two properties: `items` and `metadata`. * `items` is an array of project objects that are forks of the given project, * and `metadata` is the pagination metadata for the forks. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L676-L722
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.getProject
async getProject(user: User, projectSlug: Project['slug']) { const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma }) delete project.secrets return await this.countEnvironmentsVariablesAndSecretsInProject( project, user ) }
/** * Gets a project by slug. * * @param user The user who is requesting the project * @param projectSlug The slug of the project to get * @returns The project with secrets removed * * @throws UnauthorizedException If the user does not have the authority to read the project */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L733-L748
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.getProjectsOfWorkspace
async getProjectsOfWorkspace( user: User, workspaceSlug: Workspace['slug'], page: number, limit: number, sort: string, order: string, search: string ) { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_PROJECT], prisma: this.prisma }) const workspaceId = workspace.id //fetch projects with required properties const projects = ( await this.prisma.project.findMany({ skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { [sort]: order }, where: { workspaceId, OR: [ { name: { contains: search } }, { description: { contains: search } } ], workspace: { members: { some: { userId: user.id, roles: { some: { role: { authorities: { hasSome: [ Authority.WORKSPACE_ADMIN, Authority.READ_PROJECT ] } } } } } } } } }) ).map((project) => excludeFields(project, 'privateKey', 'publicKey')) const items = await Promise.all( projects.map(async (project) => this.countEnvironmentsVariablesAndSecretsInProject(project, user) ) ) //calculate metadata const totalCount = await this.prisma.project.count({ where: { workspaceId, OR: [ { name: { contains: search } }, { description: { contains: search } } ], workspace: { members: { some: { userId: user.id } } } } }) const metadata = paginate(totalCount, `/project/all/${workspaceSlug}`, { page, limit, sort, order, search }) return { items, metadata } }
/** * Gets all the projects in a workspace that the user has access to. * * @param user The user who is requesting the projects * @param workspaceSlug The slug of the workspace to get the projects from * @param page The page number to get the projects for * @param limit The number of projects to get per page * @param sort The field to sort the projects by * @param order The order to sort the projects in * @param search The search string to filter the projects by * @returns An object with two properties: `items` and `metadata`. * `items` is an array of project objects that match the given criteria, * and `metadata` is an object with pagination metadata. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L764-L868
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.projectExists
private async projectExists( projectName: string, workspaceId: Workspace['id'] ): Promise<boolean> { return ( (await this.prisma.workspaceMember.count({ where: { workspaceId, workspace: { projects: { some: { name: projectName } } } } })) > 0 ) }
/** * Checks if a project with a given name exists in a workspace. * * @param projectName The name of the project to check * @param workspaceId The ID of the workspace to check in * @returns true if the project exists, false otherwise */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L877-L895
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.copyProjectData
private async copyProjectData( user: User, fromProject: { id: Project['id'] privateKey: string // Need the private key to decrypt the secrets }, toProject: { id: Project['id'] publicKey: string // Need the public key to encrypt the secrets }, // hardCopy = true: Replace everything in the toProject with the fromProject // hardCopy = false: Only add those items in the toProject that are not already present in it hardCopy: boolean = false ) { // This field will be populated if hardCopy is true // When we are doing a hard copy, we need to delete all the // items in the toProject that are already present in it const deleteOps = [] // Get all the environments that belongs to the parent project // and replicate them for the new project const createEnvironmentOps = [] const envNameToIdMap = {} // These fields will be populated if hardCopy is false // When we are doing a soft copy, we would only like to add those // items in the toProject that are not already present in it with // comparison to the fromProject const toProjectEnvironments: Set<Environment['name']> = new Set() const toProjectSecrets: Set<Secret['name']> = new Set() const toProjectVariables: Set<Variable['name']> = new Set() if (!hardCopy) { const [environments, secrets, variables] = await this.prisma.$transaction( [ this.prisma.environment.findMany({ where: { projectId: toProject.id } }), this.prisma.secret.findMany({ where: { projectId: toProject.id } }), this.prisma.variable.findMany({ where: { projectId: toProject.id } }) ] ) environments.forEach((env) => { envNameToIdMap[env.name] = env.id toProjectEnvironments.add(env.name) }) secrets.forEach((secret) => { toProjectSecrets.add(secret.name) }) variables.forEach((variable) => { toProjectVariables.add(variable.name) }) } else { deleteOps.push( this.prisma.environment.deleteMany({ where: { projectId: toProject.id } }) ) deleteOps.push( this.prisma.secret.deleteMany({ where: { projectId: toProject.id } }) ) deleteOps.push( this.prisma.variable.deleteMany({ where: { projectId: toProject.id } }) ) } // We want to find all such environments in the fromProject that // is not present in the toProject. You can think of this as a set // difference operation. // In case of a hard copy, we would just copy all the environments // since toProjectEnvironments will be empty. const missingEnvironments = await this.prisma.environment.findMany({ where: { projectId: fromProject.id, name: { notIn: Array.from(toProjectEnvironments) } } }) // For all the new environments that we are creating, we want to map // the name of the environment to the id of the newly created environment for (const environment of missingEnvironments) { const newEnvironmentId = v4() envNameToIdMap[environment.name] = newEnvironmentId createEnvironmentOps.push( this.prisma.environment.create({ data: { id: newEnvironmentId, name: environment.name, slug: await generateEntitySlug( environment.name, 'ENVIRONMENT', this.prisma ), description: environment.description, projectId: toProject.id, lastUpdatedById: user.id } }) ) } const createSecretOps = [] // Get all the secrets that belongs to the parent project and // replicate them for the new project. This too is a set difference // operation. const secrets = await this.prisma.secret.findMany({ where: { projectId: fromProject.id, name: { notIn: Array.from(toProjectSecrets) } }, include: { versions: { include: { environment: { select: { name: true } } } } } }) for (const secret of secrets) { const secretVersions = secret.versions.map(async (version) => ({ value: await encrypt( toProject.publicKey, await decrypt(fromProject.privateKey, version.value) ), version: version.version, environmentName: version.environment.name })) createSecretOps.push( this.prisma.secret.create({ data: { name: secret.name, slug: await generateEntitySlug(secret.name, 'SECRET', this.prisma), projectId: toProject.id, lastUpdatedById: user.id, note: secret.note, rotateAt: secret.rotateAt, versions: { create: await Promise.all( secretVersions.map(async (secretVersion) => { const awaitedSecretVersion = await secretVersion return { value: awaitedSecretVersion.value, version: awaitedSecretVersion.version, environmentId: envNameToIdMap[awaitedSecretVersion.environmentName], createdById: user.id } }) ) } } }) ) } // Get all the variables that belongs to the parent project and // replicate them for the new project const createVariableOps = [] const variables = await this.prisma.variable.findMany({ where: { projectId: fromProject.id, name: { notIn: Array.from(toProjectVariables) } }, include: { versions: { include: { environment: { select: { name: true } } } } } }) for (const variable of variables) { createVariableOps.push( this.prisma.variable.create({ data: { name: variable.name, slug: await generateEntitySlug( variable.name, 'VARIABLE', this.prisma ), projectId: toProject.id, lastUpdatedById: user.id, note: variable.note, versions: { create: variable.versions.map((version) => ({ value: version.value, version: version.version, createdById: user.id, environmentId: envNameToIdMap[version.environment.name] })) } } }) ) } return [ ...deleteOps, ...createEnvironmentOps, ...createSecretOps, ...createVariableOps ] }
/** * Copies the project data from one project to another project. * * @param user The user who is performing the copy operation * @param fromProject The project from which the data is being copied * @param toProject The project to which the data is being copied * @param hardCopy If true, replace all the data in the toProject with the fromProject, * otherwise, only add the items in the fromProject that are not already present in the toProject. * @returns An array of database operations that need to be performed to copy the data. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L907-L1155
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ProjectService.updateProjectKeyPair
private async updateProjectKeyPair( project: ProjectWithSecrets, oldPrivateKey: string, storePrivateKey: boolean ) { // A new key pair can be generated only if: // - The existing private key is provided // - Or, the private key was stored const { privateKey: newPrivateKey, publicKey: newPublicKey } = createKeyPair() const txs = [] // Re-hash all secrets for (const secret of project.secrets) { const versions = await this.prisma.secretVersion.findMany({ where: { secretId: secret.id } }) const updatedVersions: Partial<SecretVersion>[] = [] // First, encrypt the values with the new key and store // them in a temporary array for (const version of versions) { updatedVersions.push({ id: version.id, value: await encrypt( await decrypt(oldPrivateKey, version.value), newPrivateKey ) }) } // Apply the changes to the database for (const version of updatedVersions) { txs.push( this.prisma.secretVersion.update({ where: { id: version.id }, data: { value: version.value } }) ) } } // Update the project with the new key pair txs.push( this.prisma.project.update({ where: { id: project.id }, data: { publicKey: newPublicKey, privateKey: storePrivateKey ? newPrivateKey : null } }) ) return { txs, newPrivateKey, newPublicKey } }
/** * Updates the key pair of a project. * * @param project The project to update * @param oldPrivateKey The old private key of the project * @param storePrivateKey Whether to store the new private key in the database * * @returns An object with three properties: * - `txs`: an array of database operations that need to be performed to update the project * - `newPrivateKey`: the new private key of the project * - `newPublicKey`: the new public key of the project */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/project/service/project.service.ts#L1169-L1233
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
uploadFile
async function uploadFile(file) { if (!isServiceLoaded) { throw new InternalServerErrorException('Minio Client has not loaded') } const fileName = `${Date.now()}-${file.originalname}` try { await minioClient.putObject( bucketName, fileName, file.buffer, file.size ) } catch (error) { logger.error('Error uploading file to Minio', error) throw new InternalServerErrorException('Error uploading file to Minio') } return fileName }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/provider/minio.provider.ts#L74-L93
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
getFileUrl
async function getFileUrl(fileName: string) { if (!isServiceLoaded) { throw new InternalServerErrorException('Minio Client has not loaded') } try { return await minioClient.presignedUrl('GET', bucketName, fileName) } catch (error) { logger.error('Error generating file URL from Minio', error) throw new InternalServerErrorException( 'Error generating file URL from Minio' ) } }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/provider/minio.provider.ts#L96-L109
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
deleteFile
async function deleteFile(fileName: string) { if (!isServiceLoaded) { throw new InternalServerErrorException('Minio Client has not loaded') } try { await minioClient.removeObject(bucketName, fileName) return true } catch (error) { logger.error('Error deleting file from Minio', error) throw new InternalServerErrorException('Error deleting file from Minio') } }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/provider/minio.provider.ts#L112-L124
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.createSecret
async createSecret( user: User, dto: CreateSecret, projectSlug: Project['slug'] ): Promise<SecretWithValues> { // Fetch the project const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.CREATE_SECRET], prisma: this.prisma }) const projectId = project.id // Check if the secret with the same name already exists in the project await this.secretExists(dto.name, project) const shouldCreateRevisions = dto.entries && dto.entries.length > 0 // Check if the user has access to the environments const environmentSlugToIdMap = shouldCreateRevisions ? await getEnvironmentIdToSlugMap( dto, user, project, this.prisma, this.authorityCheckerService ) : new Map<string, string>() // Create the secret const secretData = await this.prisma.secret.create({ data: { name: dto.name, slug: await generateEntitySlug(dto.name, 'SECRET', this.prisma), note: dto.note, rotateAt: addHoursToDate(dto.rotateAfter), rotateAfter: +dto.rotateAfter, versions: shouldCreateRevisions && { createMany: { data: await Promise.all( dto.entries.map(async (entry) => ({ value: await encrypt(project.publicKey, entry.value), version: 1, createdById: user.id, environmentId: environmentSlugToIdMap.get(entry.environmentSlug) })) ) } }, project: { connect: { id: projectId } }, lastUpdatedBy: { connect: { id: user.id } } }, include: { lastUpdatedBy: { select: { id: true, name: true } }, versions: { select: { environment: { select: { id: true, name: true, slug: true } }, value: true, version: true, createdBy: { select: { id: true, name: true, profilePictureUrl: true } }, createdOn: true } } } }) const secret = getSecretWithValues(secretData) await createEvent( { triggeredBy: user, entity: secret.secret, type: EventType.SECRET_ADDED, source: EventSource.SECRET, title: `Secret created`, metadata: { secretId: secret.secret.id, name: secret.secret.name, projectId, projectName: project.name }, workspaceId: project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} created secret ${secret.secret.id}`) return secret }
/** * Creates a new secret in a project * @param user the user creating the secret * @param dto the secret data * @param projectSlug the slug of the project * @returns the created secret */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L65-L181
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.updateSecret
async updateSecret( user: User, secretSlug: Secret['slug'], dto: UpdateSecret ) { const secret = await this.authorityCheckerService.checkAuthorityOverSecret({ userId: user.id, entity: { slug: secretSlug }, authorities: [Authority.UPDATE_SECRET], prisma: this.prisma }) const shouldCreateRevisions = dto.entries && dto.entries.length > 0 // Check if the secret with the same name already exists in the project dto.name && (await this.secretExists(dto.name, secret.project)) // Check if the user has access to the environments const environmentSlugToIdMap = shouldCreateRevisions ? await getEnvironmentIdToSlugMap( dto, user, secret.project, this.prisma, this.authorityCheckerService ) : new Map<string, string>() const op = [] // Update the secret // Update the other fields op.push( this.prisma.secret.update({ where: { id: secret.id }, data: { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'SECRET', this.prisma) : undefined, note: dto.note, ...(dto.rotateAfter ? { rotateAt: addHoursToDate(dto.rotateAfter), rotateAfter: +dto.rotateAfter } : {}), lastUpdatedById: user.id }, select: { id: true, name: true, note: true, slug: true } }) ) // If new values for various environments are proposed, // we want to create new versions for those environments if (shouldCreateRevisions) { for (const entry of dto.entries) { // Fetch the latest version of the secret for the environment const latestVersion = await this.prisma.secretVersion.findFirst({ where: { secretId: secret.id, environmentId: environmentSlugToIdMap.get(entry.environmentSlug) }, select: { version: true }, orderBy: { version: 'desc' }, take: 1 }) // Create the new version op.push( this.prisma.secretVersion.create({ data: { value: await encrypt(secret.project.publicKey, entry.value), version: latestVersion ? latestVersion.version + 1 : 1, createdById: user.id, environmentId: environmentSlugToIdMap.get(entry.environmentSlug), secretId: secret.id }, select: { id: true, environment: { select: { id: true, slug: true } }, value: true, version: true } }) ) } } // Make the transaction const tx = await this.prisma.$transaction(op) const updatedSecret = tx[0] const updatedVersions = tx.slice(1) const result = { secret: updatedSecret, updatedVersions: updatedVersions } // Notify the new secret version through Redis if (dto.entries && dto.entries.length > 0) { for (const entry of dto.entries) { try { await this.redis.publish( CHANGE_NOTIFIER_RSC, JSON.stringify({ environmentId: environmentSlugToIdMap.get(entry.environmentSlug), name: updatedSecret.name, value: entry.value, isPlaintext: true } as ChangeNotificationEvent) ) } catch (error) { this.logger.error(`Error publishing secret update to Redis: ${error}`) } } } await createEvent( { triggeredBy: user, entity: secret, type: EventType.SECRET_UPDATED, source: EventSource.SECRET, title: `Secret updated`, metadata: { secretId: secret.id, name: secret.name, projectId: secret.projectId, projectName: secret.project.name }, workspaceId: secret.project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} updated secret ${secret.id}`) return result }
/** * Updates a secret in a project * @param user the user performing the action * @param secretSlug the slug of the secret to update * @param dto the new secret data * @returns the updated secret and the updated versions */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L190-L346
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.rollbackSecret
async rollbackSecret( user: User, secretSlug: Secret['slug'], environmentSlug: Environment['slug'], rollbackVersion: SecretVersion['version'] ) { // Fetch the secret const secret = await this.authorityCheckerService.checkAuthorityOverSecret({ userId: user.id, entity: { slug: secretSlug }, authorities: [Authority.UPDATE_SECRET], prisma: this.prisma }) // Fetch the environment const environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.UPDATE_SECRET], prisma: this.prisma }) const environmentId = environment.id const project = secret.project // Filter the secret versions by the environment secret.versions = secret.versions.filter( (version) => version.environmentId === environmentId ) if (secret.versions.length === 0) { throw new NotFoundException( `No versions found for environment: ${environmentSlug} for secret: ${secretSlug}` ) } // Sorting is in ascending order of dates. So the last element is the latest version const maxVersion = secret.versions[secret.versions.length - 1].version // Check if the rollback version is valid if (rollbackVersion < 1 || rollbackVersion >= maxVersion) { throw new NotFoundException( `Invalid rollback version: ${rollbackVersion} for secret: ${secretSlug}` ) } // Rollback the secret const result = await this.prisma.secretVersion.deleteMany({ where: { secretId: secret.id, version: { gt: Number(rollbackVersion) } } }) try { await this.redis.publish( CHANGE_NOTIFIER_RSC, JSON.stringify({ environmentId, name: secret.name, value: project.storePrivateKey ? await decrypt(project.privateKey, secret.versions[0].value) : secret.versions[0].value, isPlaintext: project.storePrivateKey } as ChangeNotificationEvent) ) } catch (error) { this.logger.error(`Error publishing secret update to Redis: ${error}`) } await createEvent( { triggeredBy: user, entity: secret, type: EventType.SECRET_UPDATED, source: EventSource.SECRET, title: `Secret rolled back`, metadata: { secretId: secret.id, name: secret.name, projectId: secret.projectId, projectName: secret.project.name }, workspaceId: secret.project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} rolled back secret ${secret.id}`) return result }
/** * Rollback a secret to a specific version * @param user the user performing the action * @param secretSlug the slug of the secret to rollback * @param environmentSlug the slug of the environment to rollback * @param rollbackVersion the version to rollback to * @returns the deleted secret versions */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L356-L450
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.deleteSecret
async deleteSecret(user: User, secretSlug: Secret['slug']) { // Check if the user has the required role const secret = await this.authorityCheckerService.checkAuthorityOverSecret({ userId: user.id, entity: { slug: secretSlug }, authorities: [Authority.DELETE_SECRET], prisma: this.prisma }) // Delete the secret await this.prisma.secret.delete({ where: { id: secret.id } }) await createEvent( { triggeredBy: user, type: EventType.SECRET_DELETED, source: EventSource.SECRET, entity: secret, title: `Secret deleted`, metadata: { secretId: secret.id }, workspaceId: secret.project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} deleted secret ${secret.id}`) }
/** * Deletes a secret from a project * @param user the user performing the action * @param secretSlug the slug of the secret to delete * @returns void */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L458-L490
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.getRevisionsOfSecret
async getRevisionsOfSecret( user: User, secretSlug: Secret['slug'], environmentSlug: Environment['slug'], decryptValue: boolean, page: number, limit: number, order: 'asc' | 'desc' = 'desc' ) { // Fetch the secret const secret = await this.authorityCheckerService.checkAuthorityOverSecret({ userId: user.id, entity: { slug: secretSlug }, authorities: [Authority.READ_SECRET], prisma: this.prisma }) const secretId = secret.id // Fetch the environment const environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma }) const environmentId = environment.id // Check if the secret can be decrypted await this.checkAutoDecrypt(decryptValue, secret.project) // Get the revisions const items = await this.prisma.secretVersion.findMany({ where: { secretId: secretId, environmentId: environmentId }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { version: order }, include: { createdBy: { select: { id: true, name: true, profilePictureUrl: true } } } }) // Decrypt the values if (decryptValue) { for (const item of items) { item.value = await decrypt(secret.project.privateKey, item.value) } } const totalCount = await this.prisma.secretVersion.count({ where: { secretId: secretId, environmentId: environmentId } }) const metadata = paginate(totalCount, `/secret/${secretSlug}`, { page, limit: limitMaxItemsPerPage(limit), order }) return { items, metadata } }
/** * Gets all revisions of a secret in an environment * @param user the user performing the action * @param secretSlug the slug of the secret * @param environmentSlug the slug of the environment * @param decryptValue whether to decrypt the secret values or not * @param page the page of items to return * @param limit the number of items to return per page * @param order the order of the items. Default is 'desc' * @returns an object with the items and the pagination metadata */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L503-L577
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.getAllSecretsOfProject
async getAllSecretsOfProject( user: User, projectSlug: Project['slug'], decryptValue: boolean, page: number, limit: number, sort: string, order: string, search: string ) { // Fetch the project const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.READ_SECRET], prisma: this.prisma }) const projectId = project.id // Check if the secret values can be decrypted await this.checkAutoDecrypt(decryptValue, project) const secrets = await this.prisma.secret.findMany({ where: { projectId, name: { contains: search } }, include: { lastUpdatedBy: { select: { id: true, name: true, profilePictureUrl: true } }, versions: { select: { value: true, version: true, environment: { select: { name: true, id: true, slug: true } }, createdBy: { select: { id: true, name: true, profilePictureUrl: true } }, createdOn: true } } }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { [sort]: order } }) const secretsWithEnvironmentalValues = new Set<{ secret: Partial<Secret> values: { environment: { name: Environment['name'] id: Environment['id'] slug: Environment['slug'] } value: SecretVersion['value'] version: SecretVersion['version'] createdBy: { id: User['id'] name: User['name'] profilePictureUrl: User['profilePictureUrl'] } createdOn: SecretVersion['createdOn'] }[] }>() for (const secret of secrets) { // Logic to update the map: // 1. If the environment ID is not present in the key, insert the environment ID and the secret version // 2. If the environment ID is already present, check if the existing secret version is lesser than the new secret version. // If it is, update the secret version const envIdToSecretVersionMap = new Map< Environment['id'], Partial<SecretVersion> & { environment: { id: Environment['id'] slug: Environment['slug'] name: Environment['name'] } createdBy: { id: User['id'] name: User['name'] profilePictureUrl: User['profilePictureUrl'] } } >() for (const secretVersion of secret.versions) { const environmentId = secretVersion.environment.id const existingSecretVersion = envIdToSecretVersionMap.get(environmentId) if (!existingSecretVersion) { envIdToSecretVersionMap.set(environmentId, secretVersion) } else { if (existingSecretVersion.version < secretVersion.version) { envIdToSecretVersionMap.set(environmentId, secretVersion) } } } delete secret.versions // Add the secret to the map secretsWithEnvironmentalValues.add({ secret, values: await Promise.all( Array.from(envIdToSecretVersionMap.values()).map( async (secretVersion) => ({ environment: { id: secretVersion.environment.id, name: secretVersion.environment.name, slug: secretVersion.environment.slug }, value: decryptValue ? await decrypt(project.privateKey, secretVersion.value) : secretVersion.value, version: secretVersion.version, createdBy: { id: secretVersion.createdBy.id, name: secretVersion.createdBy.name, profilePictureUrl: secretVersion.createdBy.profilePictureUrl }, createdOn: secretVersion.createdOn }) ) ) }) } // console.log(secretsWithEnvironmentalValues) const items = Array.from(secretsWithEnvironmentalValues.values()) // Calculate pagination metadata const totalCount = await this.prisma.secret.count({ where: { projectId, name: { contains: search } } }) const metadata = paginate( totalCount, `/secret/${projectSlug}`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search }, { decryptValue } ) return { items, metadata } }
/** * Gets all secrets of a project * @param user the user performing the action * @param projectSlug the slug of the project * @param decryptValue whether to decrypt the secret values or not * @param page the page of items to return * @param limit the number of items to return per page * @param sort the field to sort the results by * @param order the order of the results * @param search the search query * @returns an object with the items and the pagination metadata */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L591-L768
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.secretExists
private async secretExists(secretName: Secret['name'], project: Project) { if ( (await this.prisma.secret.findFirst({ where: { name: secretName, projectId: project.id } })) !== null ) { throw new ConflictException( `Secret already exists: ${secretName} in project ${project.slug}` ) } }
/** * Checks if a secret with a given name already exists in the project * @throws {ConflictException} if the secret already exists * @param secretName the name of the secret to check * @param project the project to check the secret in */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L901-L914
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
SecretService.checkAutoDecrypt
private async checkAutoDecrypt(decryptValue: boolean, project: Project) { // Check if the project is allowed to store the private key if (decryptValue && !project.storePrivateKey) { throw new BadRequestException( `Cannot decrypt secret values as the project does not store the private key` ) } // Check if the project has a private key. This is just to ensure that we don't run into any // problems while decrypting the secret if (decryptValue && !project.privateKey) { throw new NotFoundException( `Cannot decrypt secret values as the project does not have a private key` ) } }
/** * Checks if the project is allowed to decrypt secret values * @param decryptValue whether to decrypt the secret values or not * @param project the project to check * @throws {BadRequestException} if the project does not store the private key and decryptValue is true * @throws {NotFoundException} if the project does not have a private key and decryptValue is true */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/secret/service/secret.service.ts#L923-L938
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ChangeNotifier.afterInit
async afterInit() { this.logger.log('Initialized change notifier socket gateway') await this.redisSubscriber.subscribe( CHANGE_NOTIFIER_RSC, this.notifyConfigurationUpdate.bind(this) ) }
/** * We want the socket gateway to subscribe to the Redis channel. * This approach allows us to handle distributed computing where * multiple clients can connect to different instances of the API. * Any server that will get an update, will publish it to the Redis * channel, and all connected clients will receive the update. Out * of them, the ones that have sockets registered for the particular * environmentId will receive the update. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/socket/change-notifier.socket.ts#L69-L75
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
VariableService.createVariable
async createVariable( user: User, dto: CreateVariable, projectSlug: Project['slug'] ): Promise<VariableWithValues> { // Fetch the project const project = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.CREATE_VARIABLE], prisma: this.prisma }) const projectId = project.id // Check if a variable with the same name already exists in the project await this.variableExists(dto.name, project) const shouldCreateRevisions = dto.entries && dto.entries.length > 0 // Check if the user has access to the environments const environmentSlugToIdMap = shouldCreateRevisions ? await getEnvironmentIdToSlugMap( dto, user, project, this.prisma, this.authorityCheckerService ) : new Map<string, string>() // Create the variable const variableData = await this.prisma.variable.create({ data: { name: dto.name, slug: await generateEntitySlug(dto.name, 'VARIABLE', this.prisma), note: dto.note, versions: shouldCreateRevisions && { createMany: { data: dto.entries.map((entry) => ({ value: entry.value, createdById: user.id, environmentId: environmentSlugToIdMap.get(entry.environmentSlug) })) } }, project: { connect: { id: projectId } }, lastUpdatedBy: { connect: { id: user.id } } }, include: { lastUpdatedBy: { select: { id: true, name: true } }, versions: { select: { environment: { select: { id: true, name: true, slug: true } }, version: true, value: true, createdBy: { select: { id: true, name: true, profilePictureUrl: true } } } } } }) const variable = getVariableWithValues(variableData) await createEvent( { triggeredBy: user, entity: variable.variable, type: EventType.VARIABLE_ADDED, source: EventSource.VARIABLE, title: `Variable created`, metadata: { variableId: variable.variable.id, name: variable.variable.name, projectId, projectName: project.name }, workspaceId: project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} created variable ${variable.variable.id}`) return variable }
/** * Creates a new variable in a project * @param user the user performing the action * @param dto the variable to create * @param projectSlug the slug of the project to create the variable in * @returns the newly created variable */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/variable/service/variable.service.ts#L56-L166
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
VariableService.updateVariable
async updateVariable( user: User, variableSlug: Variable['slug'], dto: UpdateVariable ) { const variable = await this.authorityCheckerService.checkAuthorityOverVariable({ userId: user.id, entity: { slug: variableSlug }, authorities: [Authority.UPDATE_VARIABLE], prisma: this.prisma }) // Check if the variable already exists in the project dto.name && (await this.variableExists(dto.name, variable.project)) const shouldCreateRevisions = dto.entries && dto.entries.length > 0 // Check if the user has access to the environments const environmentSlugToIdMap = shouldCreateRevisions ? await getEnvironmentIdToSlugMap( dto, user, variable.project, this.prisma, this.authorityCheckerService ) : new Map<string, string>() const op = [] // Update the variable // Update the fields op.push( this.prisma.variable.update({ where: { id: variable.id }, data: { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'VARIABLE', this.prisma) : undefined, note: dto.note, lastUpdatedById: user.id }, select: { id: true, name: true, note: true, slug: true } }) ) // If new values for various environments are proposed, // we want to create new versions for those environments if (shouldCreateRevisions) { for (const entry of dto.entries) { // Fetch the latest version of the variable for the environment const latestVersion = await this.prisma.variableVersion.findFirst({ where: { variableId: variable.id, environmentId: environmentSlugToIdMap.get(entry.environmentSlug) }, select: { version: true }, orderBy: { version: 'desc' }, take: 1 }) // Create the new version op.push( this.prisma.variableVersion.create({ data: { value: entry.value, version: latestVersion ? latestVersion.version + 1 : 1, createdById: user.id, environmentId: environmentSlugToIdMap.get(entry.environmentSlug), variableId: variable.id }, select: { id: true, environment: { select: { id: true, slug: true } }, value: true, version: true } }) ) } } // Make the transaction const tx = await this.prisma.$transaction(op) const updatedVariable = tx[0] const updatedVersions = tx.slice(1) const result = { variable: updatedVariable, updatedVersions: updatedVersions } // Notify the new variable version through Redis if (dto.entries && dto.entries.length > 0) { for (const entry of dto.entries) { try { await this.redis.publish( CHANGE_NOTIFIER_RSC, JSON.stringify({ environmentId: environmentSlugToIdMap.get(entry.environmentSlug), name: updatedVariable.name, value: entry.value, isPlaintext: true } as ChangeNotificationEvent) ) } catch (error) { this.logger.error( `Error publishing variable update to Redis: ${error}` ) } } } await createEvent( { triggeredBy: user, entity: variable, type: EventType.VARIABLE_UPDATED, source: EventSource.VARIABLE, title: `Variable updated`, metadata: { variableId: variable.id, name: variable.name, projectId: variable.projectId, projectName: variable.project.name }, workspaceId: variable.project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} updated variable ${variable.id}`) return result }
/** * Updates a variable in a project * @param user the user performing the action * @param variableSlug the slug of the variable to update * @param dto the data to update the variable with * @returns the updated variable and its new versions */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/variable/service/variable.service.ts#L175-L327
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
VariableService.rollbackVariable
async rollbackVariable( user: User, variableSlug: Variable['slug'], environmentSlug: Environment['slug'], rollbackVersion: VariableVersion['version'] ) { const environment = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.UPDATE_VARIABLE], prisma: this.prisma }) const environmentId = environment.id const variable = await this.authorityCheckerService.checkAuthorityOverVariable({ userId: user.id, entity: { slug: variableSlug }, authorities: [Authority.UPDATE_VARIABLE], prisma: this.prisma }) // Filter the variable versions by the environment variable.versions = variable.versions.filter( (version) => version.environmentId === environmentId ) if (variable.versions.length === 0) { throw new NotFoundException( `No versions found for environment: ${environmentSlug} for variable: ${variableSlug}` ) } // Sorting is in ascending order of dates. So the last element is the latest version const maxVersion = variable.versions[variable.versions.length - 1].version // Check if the rollback version is valid if (rollbackVersion < 1 || rollbackVersion >= maxVersion) { throw new NotFoundException( `Invalid rollback version: ${rollbackVersion} for variable: ${variableSlug}` ) } // Rollback the variable const result = await this.prisma.variableVersion.deleteMany({ where: { variableId: variable.id, version: { gt: Number(rollbackVersion) } } }) try { // Notify the new variable version through Redis await this.redis.publish( CHANGE_NOTIFIER_RSC, JSON.stringify({ environmentId, name: variable.name, value: variable.versions[rollbackVersion - 1].value, isPlaintext: true } as ChangeNotificationEvent) ) } catch (error) { this.logger.error(`Error publishing variable update to Redis: ${error}`) } await createEvent( { triggeredBy: user, entity: variable, type: EventType.VARIABLE_UPDATED, source: EventSource.VARIABLE, title: `Variable rolled back`, metadata: { variableId: variable.id, name: variable.name, projectId: variable.projectId, projectName: variable.project.name, rollbackVersion }, workspaceId: variable.project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} rolled back variable ${variable.id}`) return result }
/** * Rollback a variable to a specific version in a given environment. * * Throws a NotFoundException if the variable does not exist or if the version is invalid. * @param user the user performing the action * @param variableSlug the slug of the variable to rollback * @param environmentSlug the slug of the environment to rollback in * @param rollbackVersion the version to rollback to * @returns the deleted variable versions */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/variable/service/variable.service.ts#L339-L430
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
VariableService.deleteVariable
async deleteVariable(user: User, variableSlug: Variable['slug']) { const variable = await this.authorityCheckerService.checkAuthorityOverVariable({ userId: user.id, entity: { slug: variableSlug }, authorities: [Authority.DELETE_VARIABLE], prisma: this.prisma }) // Delete the variable await this.prisma.variable.delete({ where: { id: variable.id } }) await createEvent( { triggeredBy: user, type: EventType.VARIABLE_DELETED, source: EventSource.VARIABLE, title: `Variable deleted`, entity: variable, metadata: { variableId: variable.id, name: variable.name, projectId: variable.projectId, projectName: variable.project.name }, workspaceId: variable.project.workspaceId }, this.prisma ) this.logger.log(`User ${user.id} deleted variable ${variable.id}`) }
/** * Deletes a variable from a project. * @param user the user performing the action * @param variableSlug the slug of the variable to delete * @returns nothing * @throws `NotFoundException` if the variable does not exist * @throws `ForbiddenException` if the user does not have the required authority */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/variable/service/variable.service.ts#L440-L475
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
VariableService.getAllVariablesOfProject
async getAllVariablesOfProject( user: User, projectSlug: Project['slug'], page: number, limit: number, sort: string, order: string, search: string ) { // Check if the user has the required authorities in the project const { id: projectId } = await this.authorityCheckerService.checkAuthorityOverProject({ userId: user.id, entity: { slug: projectSlug }, authorities: [Authority.READ_VARIABLE], prisma: this.prisma }) const variables = await this.prisma.variable.findMany({ where: { projectId, name: { contains: search } }, include: { lastUpdatedBy: { select: { id: true, name: true, profilePictureUrl: true } }, versions: { select: { value: true, version: true, environment: { select: { name: true, id: true, slug: true } }, createdBy: { select: { id: true, name: true, profilePictureUrl: true } }, createdOn: true } } }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { [sort]: order } }) const variablesWithEnvironmentalValues = new Set<{ variable: Partial<Variable> values: { environment: { name: Environment['name'] id: Environment['id'] slug: Environment['slug'] } value: VariableVersion['value'] version: VariableVersion['version'] createdBy: { id: User['id'] name: User['name'] profilePictureUrl: User['profilePictureUrl'] } createdOn: VariableVersion['createdOn'] }[] }>() for (const variable of variables) { // Logic to update the map: // 1. If the environment ID is not present in the key, insert the environment ID and the variable version // 2. If the environment ID is already present, check if the existing variable version is lesser than the new variable version. // If it is, update the variable version const envIdToVariableVersionMap = new Map< Environment['id'], Partial<VariableVersion> & { environment: { id: Environment['id'] slug: Environment['slug'] name: Environment['name'] } createdBy: { id: User['id'] name: User['name'] profilePictureUrl: User['profilePictureUrl'] } } >() for (const variableVersion of variable.versions) { const environmentId = variableVersion.environment.id const existingVariableVersion = envIdToVariableVersionMap.get(environmentId) if (!existingVariableVersion) { envIdToVariableVersionMap.set(environmentId, variableVersion) } else { if (existingVariableVersion.version < variableVersion.version) { envIdToVariableVersionMap.set(environmentId, variableVersion) } } } delete variable.versions // Add the variable to the map variablesWithEnvironmentalValues.add({ variable, values: await Promise.all( Array.from(envIdToVariableVersionMap.values()).map( async (variableVersion) => ({ environment: { id: variableVersion.environment.id, name: variableVersion.environment.name, slug: variableVersion.environment.slug }, value: variableVersion.value, version: variableVersion.version, createdBy: { id: variableVersion.createdBy.id, name: variableVersion.createdBy.name, profilePictureUrl: variableVersion.createdBy.profilePictureUrl }, createdOn: variableVersion.createdOn }) ) ) }) } const items = Array.from(variablesWithEnvironmentalValues.values()) //calculate metadata const totalCount = await this.prisma.variable.count({ where: { projectId, name: { contains: search } } }) const metadata = paginate(totalCount, `/variable/${projectSlug}`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search }) return { items, metadata } }
/** * Gets all variables of a project, paginated, sorted and filtered by search query. * @param user the user performing the action * @param projectSlug the slug of the project to get the variables from * @param page the page number to fetch * @param limit the number of items per page * @param sort the field to sort by * @param order the order to sort in * @param search the search query to filter by * @returns a paginated list of variables with their latest versions for each environment * @throws `NotFoundException` if the project does not exist * @throws `ForbiddenException` if the user does not have the required authority */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/variable/service/variable.service.ts#L490-L654
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
VariableService.getRevisionsOfVariable
async getRevisionsOfVariable( user: User, variableSlug: Variable['slug'], environmentSlug: Environment['slug'], page: number, limit: number, order: 'asc' | 'desc' = 'desc' ) { const { id: variableId } = await this.authorityCheckerService.checkAuthorityOverVariable({ userId: user.id, entity: { slug: variableSlug }, authorities: [Authority.READ_VARIABLE], prisma: this.prisma }) const { id: environmentId } = await this.authorityCheckerService.checkAuthorityOverEnvironment({ userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma }) const items = await this.prisma.variableVersion.findMany({ where: { variableId: variableId, environmentId: environmentId }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { version: order }, include: { createdBy: { select: { id: true, name: true, profilePictureUrl: true } } } }) const total = await this.prisma.variableVersion.count({ where: { variableId: variableId, environmentId: environmentId } }) const metadata = paginate(total, `/variable/${variableSlug}`, { page, limit: limitMaxItemsPerPage(limit), order }) return { items, metadata } }
/** * Gets all revisions of a variable in a given environment. * * The response is paginated and sorted by the version in the given order. * @param user the user performing the action * @param variableSlug the slug of the variable * @param environmentSlug the slug of the environment * @param page the page number to fetch * @param limit the number of items per page * @param order the order to sort in * @returns a paginated list of variable versions with metadata * @throws `NotFoundException` if the variable or environment does not exist * @throws `ForbiddenException` if the user does not have the required authority */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/variable/service/variable.service.ts#L670-L729
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
VariableService.variableExists
private async variableExists( variableName: Variable['name'], project: Project ) { if ( (await this.prisma.variable.findFirst({ where: { name: variableName, projectId: project.id } })) !== null ) { throw new ConflictException( `Variable already exists: ${variableName} in project ${project.slug}` ) } }
/** * Checks if a variable with a given name already exists in a project. * Throws a ConflictException if the variable already exists. * @param variableName the name of the variable to check for * @param project the project to check in * @returns nothing * @throws `ConflictException` if the variable already exists */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/variable/service/variable.service.ts#L739-L755
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.transferOwnership
async transferOwnership( user: User, workspaceSlug: Workspace['slug'], otherUserEmail: User['email'] ): Promise<void> { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.WORKSPACE_ADMIN], prisma: this.prisma }) const otherUser = await getUserByEmailOrId(otherUserEmail, this.prisma) if (otherUser.id === user.id) { throw new BadRequestException( `You are already the owner of the workspace ${workspace.name} (${workspace.slug})` ) } // We don't want the users to be able to transfer // ownership if the workspace is the default workspace if (workspace.isDefault) { throw new BadRequestException( `You cannot transfer ownership of default workspace ${workspace.name} (${workspace.slug})` ) } const workspaceMembership = await this.getWorkspaceMembership( workspace.id, otherUser.id ) // Check if the user is a member of the workspace if (!workspaceMembership) { throw new NotFoundException( `${otherUser.email} is not a member of workspace ${workspace.name} (${workspace.slug})` ) } // Check if the user has accepted the invitation if (!workspaceMembership.invitationAccepted) { throw new BadRequestException( `${otherUser.email} has not accepted the invitation to workspace ${workspace.name} (${workspace.slug})` ) } const currentUserMembership = await this.getWorkspaceMembership( workspace.id, user.id ) // Get the admin ownership role const adminOwnershipRole = await this.prisma.workspaceRole.findFirst({ where: { workspaceId: workspace.id, hasAdminAuthority: true } }) // Remove this role from the current owner const removeRole = this.prisma.workspaceMemberRoleAssociation.delete({ where: { roleId_workspaceMemberId: { roleId: adminOwnershipRole.id, workspaceMemberId: currentUserMembership.id } } }) // Assign this role to the new owner const assignRole = this.prisma.workspaceMemberRoleAssociation.create({ data: { role: { connect: { id: adminOwnershipRole.id } }, workspaceMember: { connect: { id: workspaceMembership.id } } } }) // Update the owner of the workspace const updateWorkspace = this.prisma.workspace.update({ where: { id: workspace.id }, data: { ownerId: otherUser.id, lastUpdatedBy: { connect: { id: user.id } } } }) try { await this.prisma.$transaction([removeRole, assignRole, updateWorkspace]) } catch (e) { this.log.error('Error in transaction', e) throw new InternalServerErrorException('Error in transaction') } await createEvent( { triggeredBy: user, entity: workspace, type: EventType.WORKSPACE_UPDATED, source: EventSource.WORKSPACE, title: `Workspace transferred`, metadata: { workspaceId: workspace.id, name: workspace.name, newOwnerId: otherUser.id }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `Transferred ownership of workspace ${workspace.name} (${workspace.id}) to user ${otherUser.email} (${otherUser.id})` ) }
/** * Transfers ownership of a workspace to another user. * @param user The user transferring the ownership * @param workspaceSlug The slug of the workspace to transfer * @param otherUserEmail The email of the user to transfer the ownership to * @throws BadRequestException if the user is already the owner of the workspace, * or if the workspace is the default workspace * @throws NotFoundException if the other user is not a member of the workspace * @throws InternalServerErrorException if there is an error in the transaction */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L53-L183
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.inviteUsersToWorkspace
async inviteUsersToWorkspace( user: User, workspaceSlug: Workspace['slug'], members: CreateWorkspaceMember[] ): Promise<void> { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.ADD_USER], prisma: this.prisma }) // Add users to the workspace if any if (members && members.length > 0) { await this.addMembersToWorkspace(workspace, user, members) await createEvent( { triggeredBy: user, entity: workspace, type: EventType.INVITED_TO_WORKSPACE, source: EventSource.WORKSPACE, title: `Invited users to workspace`, metadata: { workspaceId: workspace.id, name: workspace.name, members: members.map((m) => m.email) }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `Added users to workspace ${workspace.name} (${workspace.id})` ) return } this.log.warn( `No users to add to workspace ${workspace.name} (${workspace.id})` ) }
/** * Invites users to a workspace. * @param user The user to invite the users for * @param workspaceSlug The slug of the workspace to invite users to * @param members The members to invite * @throws BadRequestException if the user does not have the authority to add users to the workspace * @throws NotFoundException if the workspace or any of the users to invite do not exist * @throws InternalServerErrorException if there is an error in the transaction */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L194-L238
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.removeUsersFromWorkspace
async removeUsersFromWorkspace( user: User, workspaceSlug: Workspace['slug'], userEmails: User['email'][] ): Promise<void> { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.REMOVE_USER], prisma: this.prisma }) const userIds = await this.prisma.user .findMany({ where: { email: { in: userEmails.map((email) => email.toLowerCase()) } }, select: { id: true } }) .then((users) => users.map((u) => u.id)) // Remove users from the workspace if any if (userIds && userIds.length > 0) { if (userIds.find((id) => id === user.id)) { throw new BadRequestException( `You cannot remove yourself from the workspace. Please transfer the ownership to another member before leaving the workspace.` ) } // Delete the membership await this.prisma.workspaceMember.deleteMany({ where: { workspaceId: workspace.id, userId: { in: userIds } } }) // Send an email to the removed users const removedOn = new Date() const emailPromises = userEmails.map((userEmail) => this.mailService.removedFromWorkspace( userEmail, workspace.name, removedOn ) ) await Promise.all(emailPromises) } await createEvent( { triggeredBy: user, entity: workspace, type: EventType.REMOVED_FROM_WORKSPACE, source: EventSource.WORKSPACE, title: `Removed users from workspace`, metadata: { workspaceId: workspace.id, name: workspace.name, members: userIds }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `Removed users from workspace ${workspace.name} (${workspace.id})` ) }
/** * Removes users from a workspace. * @param user The user to remove users from the workspace for * @param workspaceSlug The slug of the workspace to remove users from * @param userEmails The emails of the users to remove from the workspace * @throws BadRequestException if the user is trying to remove themselves from the workspace, * or if the user is not a member of the workspace * @throws NotFoundException if the workspace or any of the users to remove do not exist * @throws InternalServerErrorException if there is an error in the transaction */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L250-L327
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.updateMemberRoles
async updateMemberRoles( user: User, workspaceSlug: Workspace['slug'], otherUserEmail: User['email'], roleSlugs: WorkspaceRole['slug'][] ): Promise<void> { const otherUser = await getUserByEmailOrId(otherUserEmail, this.prisma) const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.UPDATE_USER_ROLE], prisma: this.prisma }) if (!roleSlugs || roleSlugs.length === 0) { this.log.warn( `No roles to update for user ${otherUserEmail} in workspace ${workspace.name} (${workspace.id})` ) } // Check if the member in concern is a part of the workspace or not if (!(await this.memberExistsInWorkspace(workspace.id, otherUser.id))) throw new NotFoundException( `${otherUser.email} is not a member of workspace ${workspace.name} (${workspace.slug})` ) const workspaceAdminRole = await this.getWorkspaceAdminRole(workspace.id) // Check if the admin role is tried to be assigned to the user if (roleSlugs.includes(workspaceAdminRole.slug)) { throw new BadRequestException(`Admin role cannot be assigned to the user`) } // Update the role of the user const membership = await this.prisma.workspaceMember.findUnique({ where: { workspaceId_userId: { workspaceId: workspace.id, userId: otherUser.id } } }) // Clear out the existing roles const deleteExistingAssociations = this.prisma.workspaceMemberRoleAssociation.deleteMany({ where: { workspaceMemberId: membership.id } }) const roleSet = new Set<WorkspaceRole>() for (const slug of roleSlugs) { const role = await this.prisma.workspaceRole.findUnique({ where: { slug } }) if (!role) { throw new NotFoundException(`Role ${slug} not found`) } roleSet.add(role) } // Create new associations const createNewAssociations = this.prisma.workspaceMemberRoleAssociation.createMany({ data: Array.from(roleSet).map((role) => ({ roleId: role.id, workspaceMemberId: membership.id })) }) await this.prisma.$transaction([ deleteExistingAssociations, createNewAssociations ]) await createEvent( { triggeredBy: user, entity: workspace, type: EventType.WORKSPACE_MEMBERSHIP_UPDATED, source: EventSource.WORKSPACE, title: `Updated role of user in workspace`, metadata: { workspaceId: workspace.id, name: workspace.name, userId: otherUser.id, roleIds: roleSlugs }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `Updated role of user ${otherUser.id} in workspace ${workspace.name} (${workspace.id})` ) }
/** * Updates the roles of a user in a workspace. * * @throws NotFoundException if the user is not a member of the workspace * @throws BadRequestException if the admin role is tried to be assigned to the user * @param user The user to update the roles for * @param workspaceSlug The slug of the workspace to update the roles in * @param otherUserEmail The email of the user to update the roles for * @param roleSlugs The slugs of the roles to assign to the user */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L339-L443
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.getAllMembersOfWorkspace
async getAllMembersOfWorkspace( user: User, workspaceSlug: Workspace['slug'], page: number, limit: number, sort: string, order: string, search: string ) { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_USERS], prisma: this.prisma }) //get all members of workspace for page with limit const items = await this.prisma.workspaceMember.findMany({ skip: page * limit, take: limit, orderBy: { workspace: { [sort]: order } }, where: { workspaceId: workspace.id, user: { OR: [ { name: { contains: search } }, { email: { contains: search.toLowerCase() } } ] } }, select: { id: true, user: true, roles: { select: { id: true, role: { select: { id: true, name: true, description: true, colorCode: true, authorities: true, projects: { select: { id: true } } } } } }, invitationAccepted: true } }) //calculate metadata for pagination const totalCount = await this.prisma.workspaceMember.count({ where: { workspaceId: workspace.id, user: { OR: [ { name: { contains: search } }, { email: { contains: search.toLowerCase() } } ] } } }) const metadata = paginate( totalCount, `/workspace-membership/${workspace.slug}/members`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search } ) return { items, metadata } }
/** * Gets all members of a workspace, paginated. * @param user The user to get the members for * @param workspaceSlug The slug of the workspace to get the members from * @param page The page number to get * @param limit The number of items per page to get * @param sort The field to sort by * @param order The order to sort in * @param search The search string to filter by * @returns The members of the workspace, paginated, with metadata */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L456-L558
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.acceptInvitation
async acceptInvitation( user: User, workspaceSlug: Workspace['slug'] ): Promise<void> { // Check if the user has a pending invitation to the workspace await this.checkInvitationPending(workspaceSlug, user) const workspace = await this.prisma.workspace.findUnique({ where: { slug: workspaceSlug } }) // Update the membership await this.prisma.workspaceMember.update({ where: { workspaceId_userId: { workspaceId: workspace.id, userId: user.id } }, data: { invitationAccepted: true } }) await createEvent( { triggeredBy: user, entity: workspace, type: EventType.ACCEPTED_INVITATION, source: EventSource.WORKSPACE, title: `${user.name} accepted invitation to workspace ${workspace.name}`, metadata: { workspaceId: workspace.id }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `User ${user.name} (${user.id}) accepted invitation to workspace ${workspace.id}` ) }
/** * Accepts an invitation to a workspace. * @param user The user to accept the invitation for * @param workspaceSlug The slug of the workspace to accept the invitation for * @throws BadRequestException if the user does not have a pending invitation to the workspace * @throws NotFoundException if the workspace does not exist * @throws InternalServerErrorException if there is an error in the transaction */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L568-L612
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.cancelInvitation
async cancelInvitation( user: User, workspaceSlug: Workspace['slug'], inviteeEmail: User['email'] ): Promise<void> { const inviteeUser = await getUserByEmailOrId(inviteeEmail, this.prisma) const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.REMOVE_USER], prisma: this.prisma }) // Check if the user has a pending invitation to the workspace await this.checkInvitationPending(workspaceSlug, inviteeUser) // Delete the membership await this.deleteMembership(workspace.id, inviteeUser.id) await createEvent( { triggeredBy: user, entity: workspace, type: EventType.CANCELLED_INVITATION, source: EventSource.WORKSPACE, title: `Cancelled invitation to workspace`, metadata: { workspaceId: workspace.id, inviteeId: inviteeUser.id }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `User ${user.name} (${user.id}) cancelled invitation to workspace ${workspace.id}` ) }
/** * Cancels an invitation to a workspace. * @param user The user cancelling the invitation * @param workspaceSlug The slug of the workspace to cancel the invitation for * @param inviteeEmail The email of the user to cancel the invitation for * @throws BadRequestException if the user does not have a pending invitation to the workspace * @throws NotFoundException if the workspace or the user to cancel the invitation for do not exist * @throws InternalServerErrorException if there is an error in the transaction */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L623-L663
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.declineInvitation
async declineInvitation( user: User, workspaceSlug: Workspace['slug'] ): Promise<void> { // Check if the user has a pending invitation to the workspace await this.checkInvitationPending(workspaceSlug, user) const workspace = await this.prisma.workspace.findUnique({ where: { slug: workspaceSlug } }) // Delete the membership await this.deleteMembership(workspace.id, user.id) await createEvent( { triggeredBy: user, entity: workspace, type: EventType.DECLINED_INVITATION, source: EventSource.WORKSPACE, title: `${user.name} declined invitation to workspace ${workspace.name}`, metadata: { workspaceId: workspace.id }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `User ${user.name} (${user.id}) declined invitation to workspace ${workspace.id}` ) }
/** * Declines an invitation to a workspace. * @param user The user declining the invitation * @param workspaceSlug The slug of the workspace to decline the invitation for * @throws BadRequestException if the user does not have a pending invitation to the workspace * @throws NotFoundException if the workspace does not exist * @throws InternalServerErrorException if there is an error in the transaction */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L673-L707
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.leaveWorkspace
async leaveWorkspace( user: User, workspaceSlug: Workspace['slug'] ): Promise<void> { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_WORKSPACE], prisma: this.prisma }) const workspaceOwnerId = await this.prisma.workspace .findUnique({ where: { id: workspace.id }, select: { ownerId: true } }) .then((workspace) => workspace.ownerId) // Check if the user is the owner of the workspace if (workspaceOwnerId === user.id) throw new BadRequestException( `You cannot leave the workspace as you are the owner of the workspace. Please transfer the ownership to another member before leaving the workspace.` ) // Delete the membership await this.deleteMembership(workspace.id, user.id) await createEvent( { triggeredBy: user, entity: workspace, type: EventType.LEFT_WORKSPACE, source: EventSource.WORKSPACE, title: `User left workspace`, metadata: { workspaceId: workspace.id }, workspaceId: workspace.id }, this.prisma ) this.log.debug( `User ${user.name} (${user.id}) left workspace ${workspace.id}` ) }
/** * Leaves a workspace. * @throws BadRequestException if the user is the owner of the workspace * @param user The user to leave the workspace for * @param workspaceSlug The slug of the workspace to leave */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L715-L765
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.isUserMemberOfWorkspace
async isUserMemberOfWorkspace( user: User, workspaceSlug: Workspace['slug'], otherUserEmail: User['email'] ): Promise<boolean> { let otherUser: User | null = null try { otherUser = await getUserByEmailOrId(otherUserEmail, this.prisma) } catch (e) { return false } const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_USERS], prisma: this.prisma }) return await this.memberExistsInWorkspace(workspace.id, otherUser.id) }
/** * Checks if a user is a member of a workspace. * @param user The user to check if the other user is a member of the workspace for * @param workspaceSlug The slug of the workspace to check if the user is a member of * @param otherUserEmail The email of the user to check if is a member of the workspace * @returns True if the user is a member of the workspace, false otherwise */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L774-L796
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.addMembersToWorkspace
private async addMembersToWorkspace( workspace: Workspace, currentUser: User, members: CreateWorkspaceMember[] ) { const workspaceAdminRole = await this.getWorkspaceAdminRole(workspace.id) for (const member of members) { // Check if the admin role is tried to be assigned to the user if (member.roleSlugs.includes(workspaceAdminRole.slug)) { throw new BadRequestException( `Admin role cannot be assigned to the user` ) } const memberUser: User | null = await this.prisma.user.findUnique({ where: { email: member.email.toLowerCase() } }) const userId = memberUser?.id ?? v4() // Check if the user is already a member of the workspace if ( memberUser && (await this.memberExistsInWorkspace(workspace.id, userId)) ) { this.log.warn( `User ${ memberUser.name || memberUser.email } (${userId}) is already a member of workspace ${workspace.name} (${ workspace.slug }). Skipping.` ) throw new ConflictException( `User ${memberUser.name || memberUser.email} (${userId}) is already a member of workspace ${workspace.name} (${workspace.slug})` ) } const roleSet = new Set<WorkspaceRole>() for (const slug of member.roleSlugs) { const role = await this.prisma.workspaceRole.findUnique({ where: { slug } }) if (!role) { throw new NotFoundException(`Workspace role ${slug} does not exist`) } roleSet.add(role) } const invitedOn = new Date() // Create the workspace membership const createMembership = this.prisma.workspaceMember.create({ data: { workspaceId: workspace.id, userId, createdOn: invitedOn, roles: { create: Array.from(roleSet).map((role) => ({ role: { connect: { id: role.id } } })) } } }) if (memberUser) { await this.prisma.$transaction([createMembership]) this.mailService.invitedToWorkspace( member.email, workspace.name, `${process.env.WORKSPACE_FRONTEND_URL}/workspace/${workspace.slug}/join`, currentUser.name, invitedOn.toISOString(), true ) this.log.debug( `Sent workspace invitation mail to registered user ${memberUser}` ) } else { // Create the user await createUser( { id: userId, email: member.email, authProvider: AuthProvider.EMAIL_OTP }, this.prisma ) await this.prisma.$transaction([createMembership]) this.log.debug(`Created non-registered user ${memberUser}`) this.mailService.invitedToWorkspace( member.email, workspace.name, `${process.env.WORKSPACE_FRONTEND_URL}/workspace/${ workspace.id }/join?token=${await this.jwt.signAsync({ id: userId })}`, currentUser.name, new Date().toISOString(), false ) this.log.debug( `Sent workspace invitation mail to non-registered user ${memberUser}` ) } this.log.debug(`Added user ${memberUser} to workspace ${workspace.name}.`) } }
/** * Adds members to a workspace. * @param workspace The workspace to add members to * @param currentUser The user performing the action * @param members The members to add to the workspace * @throws BadRequestException if the admin role is tried to be assigned to the user * @throws ConflictException if the user is already a member of the workspace * @throws InternalServerErrorException if there is an error in the transaction * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L827-L953
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.memberExistsInWorkspace
private async memberExistsInWorkspace( workspaceId: string, userId: string ): Promise<boolean> { return ( (await this.prisma.workspaceMember.count({ where: { workspaceId, userId } })) > 0 ) }
/** * Checks if a user is a member of a workspace. * @param workspaceId The ID of the workspace to check * @param userId The ID of the user to check * @returns True if the user is a member of the workspace, false otherwise * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L962-L974
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.getWorkspaceMembership
private async getWorkspaceMembership( workspaceId: Workspace['id'], userId: User['id'] ): Promise<WorkspaceMember> { return await this.prisma.workspaceMember.findUnique({ where: { workspaceId_userId: { workspaceId, userId } } }) }
/** * Gets the workspace membership of a user in a workspace. * @param workspaceId The ID of the workspace to get the membership for * @param userId The ID of the user to get the membership for * @returns The workspace membership of the user in the workspace * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L983-L995
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.deleteMembership
private async deleteMembership( workspaceId: Workspace['id'], userId: User['id'] ): Promise<void> { await this.prisma.workspaceMember.delete({ where: { workspaceId_userId: { workspaceId, userId } } }) }
/** * Deletes the membership of a user in a workspace. * @param workspaceId The ID of the workspace to delete the membership from * @param userId The ID of the user to delete the membership for * @returns A promise that resolves when the membership is deleted * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L1004-L1016
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceMembershipService.checkInvitationPending
private async checkInvitationPending( workspaceSlug: Workspace['slug'], user: User ): Promise<void> { const membershipExists = await this.prisma.workspaceMember .count({ where: { workspace: { slug: workspaceSlug }, userId: user.id, invitationAccepted: false } }) .then((count) => count > 0) if (!membershipExists) throw new BadRequestException( `${user.email} is not invited to workspace ${workspaceSlug}` ) }
/** * Checks if a user has a pending invitation to a workspace. * @throws BadRequestException if the user is not invited to the workspace * @param workspaceSlug The slug of the workspace to check if the user is invited to * @param user The user to check if the user is invited to the workspace */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-membership/service/workspace-membership.service.ts#L1024-L1044
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.createWorkspaceRole
async createWorkspaceRole( user: User, workspaceSlug: Workspace['slug'], dto: CreateWorkspaceRole ) { if ( dto.authorities && dto.authorities.includes(Authority.WORKSPACE_ADMIN) ) { throw new BadRequestException( 'You can not explicitly assign workspace admin authority to a role' ) } const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.CREATE_WORKSPACE_ROLE], prisma: this.prisma }) const workspaceId = workspace.id if (await this.checkWorkspaceRoleExists(user, workspaceSlug, dto.name)) { throw new ConflictException( 'Workspace role with the same name already exists' ) } const workspaceRoleId = v4() const op = [] // Create the workspace role op.push( this.prisma.workspaceRole.create({ data: { id: workspaceRoleId, name: dto.name, slug: await generateEntitySlug( dto.name, 'WORKSPACE_ROLE', this.prisma ), description: dto.description, colorCode: dto.colorCode, authorities: dto.authorities ?? [], hasAdminAuthority: false, workspace: { connect: { id: workspaceId } } }, select: { id: true } }) ) if (dto.projectEnvironments) { // Create the project associations const projectSlugToIdMap = await this.getProjectSlugToIdMap( dto.projectEnvironments.map((pe) => pe.projectSlug) ) for (const pe of dto.projectEnvironments) { const projectId = projectSlugToIdMap.get(pe.projectSlug) if (projectId) { if (pe.environmentSlugs && pe.environmentSlugs.length === 0) throw new BadRequestException( `EnvironmentSlugs in the project ${pe.projectSlug} are required` ) if (pe.environmentSlugs) { //Check if all environments are part of the project const project = await this.prisma.project.findFirst({ where: { id: projectId, AND: pe.environmentSlugs.map((slug) => ({ environments: { some: { slug: slug } } })) } }) if (!project) { throw new BadRequestException( `All environmentSlugs in the project ${pe.projectSlug} are not part of the project` ) } // Check if the user has read authority over all the environments for (const environmentSlug of pe.environmentSlugs) { try { await this.authorityCheckerService.checkAuthorityOverEnvironment( { userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma } ) } catch { throw new UnauthorizedException( `User does not have read authority over environment ${environmentSlug}` ) } } } // Create the project workspace role association with the environments accessible on the project op.push( this.prisma.projectWorkspaceRoleAssociation.create({ data: { roleId: workspaceRoleId, projectId: projectId, environments: pe.environmentSlugs && { connect: pe.environmentSlugs.map((slug) => ({ slug })) } } }) ) } else { throw new NotFoundException( `Project with slug ${pe.projectSlug} not found` ) } } } // Fetch the new workspace role op.push( this.prisma.workspaceRole.findFirst({ where: { id: workspaceRoleId }, include: { projects: { select: { project: { select: { id: true, slug: true, name: true } }, environments: { select: { id: true, slug: true, name: true } } } } } }) ) const workspaceRole = (await this.prisma.$transaction(op)).pop() await createEvent( { triggeredBy: user, entity: workspaceRole, type: EventType.WORKSPACE_ROLE_CREATED, source: EventSource.WORKSPACE_ROLE, title: `Workspace role created`, metadata: { workspaceRoleId: workspaceRole.id, name: workspaceRole.name, workspaceId, workspaceName: workspace.name }, workspaceId }, this.prisma ) this.logger.log( `${user.email} created workspace role ${workspaceRole.slug}` ) return workspaceRole }
/** * Creates a new workspace role * @throws {BadRequestException} if the role has workspace admin authority * @throws {ConflictException} if a workspace role with the same name already exists * @param user the user that is creating the workspace role * @param workspaceSlug the slug of the workspace * @param dto the data for the new workspace role * @returns the newly created workspace role */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L47-L235
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.updateWorkspaceRole
async updateWorkspaceRole( user: User, workspaceRoleSlug: WorkspaceRole['slug'], dto: UpdateWorkspaceRole ) { if ( dto.authorities && dto.authorities.includes(Authority.WORKSPACE_ADMIN) ) { throw new BadRequestException( 'You can not explicitly assign workspace admin authority to a role' ) } const workspaceRole = (await this.getWorkspaceRoleWithAuthority( user.id, workspaceRoleSlug, Authority.UPDATE_WORKSPACE_ROLE )) as WorkspaceRoleWithProjects const workspaceRoleId = workspaceRole.id const { slug: workspaceSlug } = await this.prisma.workspace.findUnique({ where: { id: workspaceRole.workspaceId }, select: { slug: true } }) if ( dto.name && ((await this.checkWorkspaceRoleExists(user, workspaceSlug, dto.name)) || dto.name === workspaceRole.name) ) { throw new ConflictException( 'Workspace role with the same name already exists' ) } if (dto.projectEnvironments) { await this.prisma.projectWorkspaceRoleAssociation.deleteMany({ where: { roleId: workspaceRoleId } }) const projectSlugToIdMap = await this.getProjectSlugToIdMap( dto.projectEnvironments.map((pe) => pe.projectSlug) ) for (const pe of dto.projectEnvironments) { const projectId = projectSlugToIdMap.get(pe.projectSlug) if (projectId) { if (pe.environmentSlugs && pe.environmentSlugs.length === 0) throw new BadRequestException( `EnvironmentSlugs in the project ${pe.projectSlug} are required` ) if (pe.environmentSlugs) { //Check if all environments are part of the project const project = await this.prisma.project.findFirst({ where: { id: projectId, AND: pe.environmentSlugs.map((slug) => ({ environments: { some: { slug: slug } } })) } }) if (!project) { throw new BadRequestException( `All environmentSlugs in the project ${pe.projectSlug} are not part of the project` ) } // Check if the user has read authority over all the environments for (const environmentSlug of pe.environmentSlugs) { try { await this.authorityCheckerService.checkAuthorityOverEnvironment( { userId: user.id, entity: { slug: environmentSlug }, authorities: [Authority.READ_ENVIRONMENT], prisma: this.prisma } ) } catch { throw new UnauthorizedException( `User does not have update authority over environment ${environmentSlug}` ) } } } // Create or Update the project workspace role association with the environments accessible on the project await this.prisma.projectWorkspaceRoleAssociation.upsert({ where: { roleId_projectId: { roleId: workspaceRoleId, projectId: projectId } }, update: { environments: pe.environmentSlugs && { set: [], connect: pe.environmentSlugs.map((slug) => ({ slug })) } }, create: { roleId: workspaceRoleId, projectId: projectId, environments: pe.environmentSlugs && { connect: pe.environmentSlugs.map((slug) => ({ slug })) } } }) } else { throw new NotFoundException( `Project with slug ${pe.projectSlug} not found` ) } } } const updatedWorkspaceRole = await this.prisma.workspaceRole.update({ where: { id: workspaceRoleId }, data: { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'WORKSPACE_ROLE', this.prisma) : undefined, description: dto.description, colorCode: dto.colorCode, authorities: dto.authorities }, include: { projects: { select: { project: { select: { id: true, slug: true, name: true } }, environments: { select: { id: true, slug: true, name: true } } } } } }) await createEvent( { triggeredBy: user, entity: workspaceRole, type: EventType.WORKSPACE_ROLE_UPDATED, source: EventSource.WORKSPACE_ROLE, title: `Workspace role updated`, metadata: { workspaceRoleId: workspaceRole.id, name: workspaceRole.name, workspaceId: workspaceRole.workspaceId }, workspaceId: workspaceRole.workspaceId }, this.prisma ) this.logger.log(`${user.email} updated workspace role ${workspaceRoleSlug}`) return updatedWorkspaceRole }
/** * Updates a workspace role * @throws {BadRequestException} if the role has workspace admin authority * @throws {ConflictException} if a workspace role with the same name already exists * @param user the user that is updating the workspace role * @param workspaceRoleSlug the slug of the workspace role to be updated * @param dto the data for the updated workspace role * @returns the updated workspace role */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L246-L429
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.deleteWorkspaceRole
async deleteWorkspaceRole( user: User, workspaceRoleSlug: WorkspaceRole['slug'] ) { const workspaceRole = await this.getWorkspaceRoleWithAuthority( user.id, workspaceRoleSlug, Authority.DELETE_WORKSPACE_ROLE ) const workspaceRoleId = workspaceRole.id if (workspaceRole.hasAdminAuthority) { throw new UnauthorizedException( 'Cannot delete workspace role with administrative authority' ) } await this.prisma.workspaceRole.delete({ where: { id: workspaceRoleId } }) await createEvent( { triggeredBy: user, type: EventType.WORKSPACE_ROLE_DELETED, source: EventSource.WORKSPACE_ROLE, title: `Workspace role deleted`, entity: workspaceRole, metadata: { workspaceRoleId: workspaceRole.id, name: workspaceRole.name, workspaceId: workspaceRole.workspaceId }, workspaceId: workspaceRole.workspaceId }, this.prisma ) this.logger.log(`${user.email} deleted workspace role ${workspaceRoleSlug}`) }
/** * Deletes a workspace role * @throws {UnauthorizedException} if the role has administrative authority * @param user the user that is deleting the workspace role * @param workspaceRoleSlug the slug of the workspace role to be deleted */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L437-L478
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.checkWorkspaceRoleExists
async checkWorkspaceRoleExists( user: User, workspaceSlug: Workspace['slug'], name: string ) { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_WORKSPACE_ROLE], prisma: this.prisma }) const workspaceId = workspace.id return ( (await this.prisma.workspaceRole.count({ where: { workspaceId, name } })) > 0 ) }
/** * Checks if a workspace role with the given name exists * @throws {UnauthorizedException} if the user does not have the required authority * @param user the user performing the check * @param workspaceSlug the slug of the workspace * @param name the name of the workspace role to check * @returns true if a workspace role with the given name exists, false otherwise */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L488-L510
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.getWorkspaceRole
async getWorkspaceRole( user: User, workspaceRoleSlug: WorkspaceRole['slug'] ): Promise<WorkspaceRole> { return await this.getWorkspaceRoleWithAuthority( user.id, workspaceRoleSlug, Authority.READ_WORKSPACE_ROLE ) }
/** * Gets a workspace role by its slug * @throws {UnauthorizedException} if the user does not have the required authority * @param user the user performing the request * @param workspaceRoleSlug the slug of the workspace role to get * @returns the workspace role with the given slug */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L519-L528
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.getWorkspaceRolesOfWorkspace
async getWorkspaceRolesOfWorkspace( user: User, workspaceSlug: Workspace['slug'], page: number, limit: number, sort: string, order: string, search: string ): Promise<{ items: WorkspaceRole[]; metadata: PaginatedMetadata }> { const { id: workspaceId } = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_WORKSPACE_ROLE], prisma: this.prisma }) //get workspace roles of a workspace for given page and limit const items = await this.prisma.workspaceRole.findMany({ where: { workspaceId, name: { contains: search } }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { [sort]: order } }) //calculate metadata const totalCount = await this.prisma.workspaceRole.count({ where: { workspaceId, name: { contains: search } } }) const metadata = paginate( totalCount, `/workspace-role/${workspaceSlug}/all`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search } ) return { items, metadata } }
/** * Gets all workspace roles of a workspace, with pagination and optional filtering by name * @throws {UnauthorizedException} if the user does not have the required authority * @param user the user performing the request * @param workspaceSlug the slug of the workspace * @param page the page to get (0-indexed) * @param limit the maximum number of items to return * @param sort the field to sort the results by (e.g. "name", "slug", etc.) * @param order the order to sort the results in (e.g. "asc", "desc") * @param search an optional search string to filter the results by * @returns a PaginatedMetadata object containing the items and metadata */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L542-L597
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.getWorkspaceRoleWithAuthority
private async getWorkspaceRoleWithAuthority( userId: User['id'], workspaceRoleSlug: Workspace['slug'], authorities: Authority ) { const workspaceRole = (await this.prisma.workspaceRole.findUnique({ where: { slug: workspaceRoleSlug }, include: { projects: { select: { project: { select: { id: true, slug: true, name: true } }, environments: { select: { id: true, slug: true, name: true } } } } } })) as WorkspaceRoleWithProjects if (!workspaceRole) { throw new NotFoundException( `Workspace role ${workspaceRoleSlug} not found` ) } const permittedAuthorities = await getCollectiveWorkspaceAuthorities( workspaceRole.workspaceId, userId, this.prisma ) if ( !permittedAuthorities.has(authorities) && !permittedAuthorities.has(Authority.WORKSPACE_ADMIN) ) { throw new UnauthorizedException( `User ${userId} does not have the required authorities to perform the action` ) } return workspaceRole }
/** * Gets a workspace role by its slug, with additional authorities check * @throws {NotFoundException} if the workspace role does not exist * @throws {UnauthorizedException} if the user does not have the required authority * @param userId the user that is performing the request * @param workspaceRoleSlug the slug of the workspace role to get * @param authorities the authorities to check against * @returns the workspace role with the given slug */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L608-L661
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceRoleService.getProjectSlugToIdMap
private async getProjectSlugToIdMap(projectSlugs: string[]) { const projects = projectSlugs.length ? await this.prisma.project.findMany({ where: { slug: { in: projectSlugs } } }) : [] return new Map(projects.map((project) => [project.slug, project.id])) }
/** * Given an array of project slugs, returns a Map of slug to id for all projects * found in the database. * * @param projectSlugs the array of project slugs * @returns a Map of project slug to id */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace-role/service/workspace-role.service.ts#L670-L682
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.createWorkspace
async createWorkspace(user: User, dto: CreateWorkspace) { if (await this.existsByName(dto.name, user.id)) { throw new ConflictException('Workspace already exists') } return await createWorkspace(user, dto, this.prisma) }
/** * Creates a new workspace for the given user. * @throws ConflictException if the workspace with the same name already exists * @param user The user to create the workspace for * @param dto The data to create the workspace with * @returns The created workspace */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L51-L57
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.updateWorkspace
async updateWorkspace( user: User, workspaceSlug: Workspace['slug'], dto: UpdateWorkspace ) { // Fetch the workspace const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.UPDATE_WORKSPACE], prisma: this.prisma }) // Check if a same named workspace already exists if ( (dto.name && (await this.existsByName(dto.name, user.id))) || dto.name === workspace.name ) { throw new ConflictException('Workspace already exists') } const updatedWorkspace = await this.prisma.workspace.update({ where: { id: workspace.id }, data: { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'WORKSPACE', this.prisma) : undefined, icon: dto.icon, lastUpdatedBy: { connect: { id: user.id } } } }) this.log.debug(`Updated workspace ${workspace.name} (${workspace.id})`) await createEvent( { triggeredBy: user, entity: workspace, type: EventType.WORKSPACE_UPDATED, source: EventSource.WORKSPACE, title: `Workspace updated`, metadata: { workspaceId: workspace.id, name: workspace.name }, workspaceId: workspace.id }, this.prisma ) return updatedWorkspace }
/** * Updates a workspace * @throws ConflictException if the workspace with the same name already exists * @param user The user to update the workspace for * @param workspaceSlug The slug of the workspace to update * @param dto The data to update the workspace with * @returns The updated workspace */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L67-L126
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.deleteWorkspace
async deleteWorkspace( user: User, workspaceSlug: Workspace['slug'] ): Promise<void> { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.DELETE_WORKSPACE], prisma: this.prisma }) // We don't want the users to delete their default workspace if (workspace.isDefault) { throw new BadRequestException( `You cannot delete the default workspace ${workspace.name} (${workspace.slug})` ) } // Delete the workspace await this.prisma.workspace.delete({ where: { id: workspace.id } }) this.log.debug(`Deleted workspace ${workspace.name} (${workspace.slug})`) }
/** * Deletes a workspace. * @throws BadRequestException if the workspace is the default workspace * @param user The user to delete the workspace for * @param workspaceSlug The slug of the workspace to delete */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L134-L161
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.getWorkspaceBySlug
async getWorkspaceBySlug( user: User, workspaceSlug: Workspace['slug'] ): Promise<Workspace> { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.READ_USERS], prisma: this.prisma }) return { ...workspace, isDefault: workspace.isDefault && workspace.ownerId === user.id } }
/** * Gets a workspace by its slug. * @param user The user to get the workspace for * @param workspaceSlug The slug of the workspace to get * @returns The workspace * @throws NotFoundException if the workspace does not exist or the user does not have the authority to read the workspace */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L170-L186
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.getWorkspacesOfUser
async getWorkspacesOfUser( user: User, page: number, limit: number, sort: string, order: string, search: string ) { // Get all workspaces of user for page with limit const items = await this.prisma.workspace.findMany({ skip: page * limit, take: Number(limit), orderBy: { [sort]: order }, where: { members: { some: { userId: user.id } }, name: { contains: search } } }) for (const workspace of items) { workspace['projects'] = await this.getProjectsOfWorkspace( workspace.id, user.id ) } // get total count of workspaces of the user const totalCount = await this.prisma.workspace.count({ where: { members: { some: { userId: user.id } }, name: { contains: search } } }) //calculate metadata for pagination const metadata = paginate(totalCount, `/workspace`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search }) return { items: items.map((item) => ({ ...item, isDefault: item.isDefault && item.ownerId === user.id })), metadata } }
/** * Gets all workspaces of a user, paginated. * @param user The user to get the workspaces for * @param page The page number to get * @param limit The number of items per page to get * @param sort The field to sort by * @param order The order to sort in * @param search The search string to filter by * @returns The workspaces of the user, paginated, with metadata */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L198-L264
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.exportData
async exportData(user: User, workspaceSlug: Workspace['slug']) { const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [Authority.WORKSPACE_ADMIN], prisma: this.prisma }) // eslint-disable-next-line @typescript-eslint/no-explicit-any const data: any = {} data.name = workspace.name data.icon = workspace.icon // Get all the roles of the workspace data.workspaceRoles = await this.prisma.workspaceRole.findMany({ where: { workspaceId: workspace.id }, select: { name: true, description: true, colorCode: true, hasAdminAuthority: true, authorities: true } }) // Get all projects, environments, variables and secrets of the workspace data.projects = await this.prisma.project.findMany({ where: { workspaceId: workspace.id }, select: { name: true, description: true, publicKey: true, privateKey: true, storePrivateKey: true, accessLevel: true, environments: { select: { name: true, description: true } }, secrets: { select: { name: true, rotateAt: true, note: true, versions: { select: { value: true, version: true } } } }, variables: { select: { name: true, note: true, versions: { select: { value: true, version: true } } } } } }) return data }
/** * Exports all data of a workspace, including its roles, projects, environments, variables and secrets. * @param user The user to export the data for * @param workspaceSlug The slug of the workspace to export * @returns The exported data * @throws NotFoundException if the workspace does not exist or the user does not have the authority to read the workspace * @throws InternalServerErrorException if there is an error in the transaction */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L274-L350
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.globalSearch
async globalSearch( user: User, workspaceSlug: Workspace['slug'], searchTerm: string ): Promise<{ projects: Partial<Project>[] environments: Partial<Environment>[] secrets: Partial<Secret>[] variables: Partial<Variable>[] }> { // Check authority over workspace const workspace = await this.authorityCheckerService.checkAuthorityOverWorkspace({ userId: user.id, entity: { slug: workspaceSlug }, authorities: [ Authority.READ_WORKSPACE, Authority.READ_PROJECT, Authority.READ_ENVIRONMENT, Authority.READ_SECRET, Authority.READ_VARIABLE ], prisma: this.prisma }) // Get a list of project IDs that the user has access to READ const accessibleProjectIds = await this.getAccessibleProjectIds( user.id, workspace.id ) // Query all entities based on the search term and permissions const projects = await this.queryProjects(accessibleProjectIds, searchTerm) const environments = await this.queryEnvironments( accessibleProjectIds, searchTerm ) const secrets = await this.querySecrets(accessibleProjectIds, searchTerm) const variables = await this.queryVariables( accessibleProjectIds, searchTerm ) return { projects, environments, secrets, variables } }
/** * Searches for projects, environments, secrets and variables * based on a search term. The search is scoped to the workspace * and the user's permissions. * @param user The user to search for * @param workspaceSlug The slug of the workspace to search in * @param searchTerm The search term to search for * @returns An object with the search results */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L361-L405
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.getAllWorkspaceInvitations
async getAllWorkspaceInvitations( user: User, page: number, limit: number, sort: string, order: string, search: string ) { // fetch all workspaces of user where they are not admin const items = await this.prisma.workspaceMember.findMany({ skip: page * limit, take: limitMaxItemsPerPage(Number(limit)), orderBy: { workspace: { [sort]: order } }, where: { userId: user.id, invitationAccepted: false, workspace: { name: { contains: search } }, roles: { none: { role: { hasAdminAuthority: true } } } }, select: { workspace: { select: { id: true, name: true, slug: true, icon: true } }, roles: { select: { role: { select: { name: true, colorCode: true } } } }, createdOn: true } }) // get total count of workspaces of the user const totalCount = await this.prisma.workspaceMember.count({ where: { userId: user.id, invitationAccepted: false, workspace: { name: { contains: search } }, roles: { none: { role: { hasAdminAuthority: true } } } } }) //calculate metadata for pagination const metadata = paginate(totalCount, `/workspace/invitations`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search }) return { items: items.map((item) => ({ ...item, invitedOn: item.createdOn, createdOn: undefined })), metadata } }
/** * Gets all the invitations a user has to various workspaces, paginated. * @param user The user to get the workspaces for * @param page The page number to get * @param limit The number of items per page to get * @param sort The field to sort by * @param order The order to sort in * @param search The search string to filter by * @returns The workspace invitations of the user, paginated, with metadata */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L417-L510
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.getAccessibleProjectIds
private async getAccessibleProjectIds( userId: string, workspaceId: string ): Promise<string[]> { const projects = await this.prisma.project.findMany({ where: { workspaceId } }) const accessibleProjectIds: string[] = [] for (const project of projects) { if (project.accessLevel === ProjectAccessLevel.GLOBAL) { accessibleProjectIds.push(project.id) } const authorities = await getCollectiveProjectAuthorities( userId, project, this.prisma ) if ( authorities.has(Authority.READ_PROJECT) || authorities.has(Authority.WORKSPACE_ADMIN) ) { accessibleProjectIds.push(project.id) } } return accessibleProjectIds }
/** * Gets a list of project IDs that the user has access to READ. * The user has access to a project if the project is global or if the user has the READ_PROJECT authority. * @param userId The ID of the user to get the accessible project IDs for * @param workspaceId The ID of the workspace to get the accessible project IDs for * @returns The list of project IDs that the user has access to READ * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L520-L547
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.queryProjects
private async queryProjects( projectIds: string[], searchTerm: string ): Promise<Partial<Project>[]> { // Fetch projects where user has READ_PROJECT authority and match search term return this.prisma.project.findMany({ where: { id: { in: projectIds }, OR: [ { name: { contains: searchTerm, mode: 'insensitive' } }, { description: { contains: searchTerm, mode: 'insensitive' } } ] }, select: { slug: true, name: true, description: true } }) }
/** * Queries projects by IDs and search term. * @param projectIds The IDs of projects to query * @param searchTerm The search term to query by * @returns The projects that match the search term * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L556-L571
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.queryEnvironments
private async queryEnvironments( projectIds: string[], searchTerm: string ): Promise<Partial<Environment>[]> { return this.prisma.environment.findMany({ where: { project: { id: { in: projectIds } }, OR: [ { name: { contains: searchTerm, mode: 'insensitive' } }, { description: { contains: searchTerm, mode: 'insensitive' } } ] }, select: { slug: true, name: true, description: true } }) }
/** * Queries environments by IDs and search term. * @param projectIds The IDs of projects to query * @param searchTerm The search term to query by * @returns The environments that match the search term * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L580-L596
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.querySecrets
private async querySecrets( projectIds: string[], searchTerm: string ): Promise<Partial<Secret>[]> { // Fetch secrets associated with projects user has READ_SECRET authority on return await this.prisma.secret.findMany({ where: { project: { id: { in: projectIds } }, OR: [ { name: { contains: searchTerm, mode: 'insensitive' } }, { note: { contains: searchTerm, mode: 'insensitive' } } ] }, select: { slug: true, name: true, note: true } }) }
/** * Queries secrets by IDs and search term. * @param projectIds The IDs of projects to query * @param searchTerm The search term to query by * @returns The secrets that match the search term * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L605-L622
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
WorkspaceService.queryVariables
private async queryVariables( projectIds: string[], searchTerm: string ): Promise<Partial<Variable>[]> { return this.prisma.variable.findMany({ where: { project: { id: { in: projectIds } }, OR: [ { name: { contains: searchTerm, mode: 'insensitive' } }, { note: { contains: searchTerm, mode: 'insensitive' } } ] }, select: { slug: true, name: true, note: true } }) }
/** * Queries variables by IDs and search term. * @param projectIds The IDs of projects to query * @param searchTerm The search term to query by * @returns The variables that match the search term * @private */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/workspace/service/workspace.service.ts#L631-L647
557b3b63dd7c589d484d4eab0b46e90a7c696af3