diff --git a/plugins/webhooks/server/api/webhookSubscriptions.test.ts b/plugins/webhooks/server/api/webhookSubscriptions.test.ts index 5801c92cb8..a849b3f32d 100644 --- a/plugins/webhooks/server/api/webhookSubscriptions.test.ts +++ b/plugins/webhooks/server/api/webhookSubscriptions.test.ts @@ -256,6 +256,51 @@ describe("#webhookSubscriptions.update", () => { expect(webhook.enabled).toEqual(true); }); + it("should preserve the signing secret when it is omitted", async () => { + const user = await buildAdmin(); + const existingWebhook = await buildWebhookSubscription({ + createdById: user.id, + teamId: user.teamId, + secret: "Test secret", + }); + + const res = await server.post("/api/webhookSubscriptions.update", user, { + body: { + id: existingWebhook.id, + name: "Updated webhook name", + url: existingWebhook.url, + events: existingWebhook.events, + }, + }); + + expect(res.status).toEqual(200); + await existingWebhook.reload(); + expect(existingWebhook.secret).toEqual("Test secret"); + }); + + it("should clear the signing secret when it is empty", async () => { + const user = await buildAdmin(); + const existingWebhook = await buildWebhookSubscription({ + createdById: user.id, + teamId: user.teamId, + secret: "Test secret", + }); + + const res = await server.post("/api/webhookSubscriptions.update", user, { + body: { + id: existingWebhook.id, + name: existingWebhook.name, + url: existingWebhook.url, + events: existingWebhook.events, + secret: "", + }, + }); + + expect(res.status).toEqual(200); + await existingWebhook.reload(); + expect(existingWebhook.secret).toBeNull(); + }); + it("should update a webhook subscription without a signing secret", async () => { const user = await buildAdmin(); const name = "Updated webhook name"; diff --git a/plugins/webhooks/server/api/webhookSubscriptions.ts b/plugins/webhooks/server/api/webhookSubscriptions.ts index 31f7f22eb9..6eab44ee0e 100644 --- a/plugins/webhooks/server/api/webhookSubscriptions.ts +++ b/plugins/webhooks/server/api/webhookSubscriptions.ts @@ -161,7 +161,7 @@ router.post( url, events: compact(events), enabled: true, - secret: isEmpty(secret) ? undefined : secret, + secret: secret === "" ? null : secret, }); ctx.body = { diff --git a/server/commands/documentUpdater.ts b/server/commands/documentUpdater.ts index 84abe17c08..ba176a0590 100644 --- a/server/commands/documentUpdater.ts +++ b/server/commands/documentUpdater.ts @@ -75,33 +75,21 @@ export default async function documentUpdater( const { transaction } = ctx.state; const cId = collectionId || document.collectionId; - if (title !== undefined) { - document.title = title.trim(); - } - if (icon !== undefined) { - document.icon = icon; - } - if (color !== undefined) { - document.color = color; - } - if (editorVersion) { - document.editorVersion = editorVersion; - } - if (templateId) { - document.templateId = templateId; - } - if (fullWidth !== undefined) { - document.fullWidth = fullWidth; - } + document.fill({ + title: title?.trim(), + icon, + color, + editorVersion: editorVersion || undefined, + templateId: templateId || undefined, + fullWidth, + insightsEnabled, + }); if (preferences) { document.preferences = { ...document.preferences, ...preferences, }; } - if (insightsEnabled !== undefined) { - document.insightsEnabled = insightsEnabled; - } if (text !== undefined) { document = DocumentHelper.applyMarkdownToDocument( document, diff --git a/server/commands/teamUpdater.ts b/server/commands/teamUpdater.ts index 4b320471ae..344da7349f 100644 --- a/server/commands/teamUpdater.ts +++ b/server/commands/teamUpdater.ts @@ -14,7 +14,7 @@ type Props = { const teamUpdater = async (ctx: APIContext, { params, user, team }: Props) => { const { allowedDomains, preferences, subdomain, ...attributes } = params; - team.setAttributes(attributes); + team.fill(attributes); if (attributes.defaultCollectionId) { const collection = await Collection.findOne({ diff --git a/server/models/base/Model.test.ts b/server/models/base/Model.test.ts index 4be329c7c4..544c9e1f80 100644 --- a/server/models/base/Model.test.ts +++ b/server/models/base/Model.test.ts @@ -1,10 +1,12 @@ import { faker } from "@faker-js/faker"; import { randomUUID } from "node:crypto"; import { CommentingAccess, TeamPreference } from "@shared/types"; +import { createContext } from "@server/context"; import { buildDocument, buildSearchQuery, buildTeam, + buildUser, } from "@server/test/factories"; import SearchQuery from "../SearchQuery"; import User from "../User"; @@ -57,6 +59,39 @@ describe("Model", () => { }); }); + describe("fill", () => { + it("should skip undefined values", async () => { + const team = await buildTeam({ name: "Test Team", guestSignin: true }); + team.fill({ name: undefined, guestSignin: false }); + + expect(team.name).toEqual("Test Team"); + expect(team.guestSignin).toEqual(false); + expect(team.changed()).toEqual(["guestSignin"]); + }); + + it("should set null values", async () => { + const team = await buildTeam({ avatarUrl: "https://example.com/a.png" }); + team.fill({ avatarUrl: null }); + + expect(team.avatarUrl).toBeNull(); + }); + }); + + describe("updateWithCtx", () => { + it("should not clear attributes with undefined values", async () => { + const team = await buildTeam({ name: "Test Team" }); + const user = await buildUser({ teamId: team.id }); + await team.updateWithCtx(createContext({ user }), { + name: undefined, + guestSignin: false, + }); + await team.reload(); + + expect(team.name).toEqual("Test Team"); + expect(team.guestSignin).toEqual(false); + }); + }); + describe("batch load", () => { it("should return data in batches", async () => { const team = await buildTeam(); diff --git a/server/models/base/Model.ts b/server/models/base/Model.ts index b6b9a1cd72..c8000325c8 100644 --- a/server/models/base/Model.ts +++ b/server/models/base/Model.ts @@ -1,4 +1,5 @@ import isEqual from "fast-deep-equal"; +import { isUndefined, omitBy } from "es-toolkit"; import { isArray, isObject, pick } from "es-toolkit/compat"; import type { Attributes, @@ -83,7 +84,7 @@ class Model< } /** - * This is the same as calling `set` and then calling `save`. + * This is the same as calling `fill` and then calling `save`. */ public updateWithCtx( ctx: APIContext, @@ -97,10 +98,21 @@ class Model< publish: true, }, }; - this.set(keys); + this.fill(keys); return this.save(hookContext); } + /** + * Sets the given attributes on the instance, skipping any with an undefined + * value. Use `null` to clear an attribute. + * + * @param keys the attributes to set. + * @returns the instance. + */ + public fill(keys: Partial) { + return this.set(omitBy(keys, isUndefined)); + } + /** * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will * either be completely deleted, or have its deletedAt timestamp set to the current time. diff --git a/server/routes/api/collections/collections.test.ts b/server/routes/api/collections/collections.test.ts index b7386f8b56..c9d16e58f5 100644 --- a/server/routes/api/collections/collections.test.ts +++ b/server/routes/api/collections/collections.test.ts @@ -871,6 +871,30 @@ describe("#collections.export_all", () => { }); describe("#collections.add_user", () => { + it("should preserve existing permission when permission is omitted", async () => { + const admin = await buildAdmin(); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + permission: null, + }); + const anotherUser = await buildUser({ teamId: admin.teamId }); + const membership = await UserMembership.create({ + createdById: admin.id, + collectionId: collection.id, + userId: anotherUser.id, + permission: CollectionPermission.Admin, + }); + + const res = await server.post("/api/collections.add_user", admin, { + body: { id: collection.id, userId: anotherUser.id }, + }); + + expect(res.status).toEqual(200); + await membership.reload(); + expect(membership.permission).toEqual(CollectionPermission.Admin); + }); + it("should add user to collection with manage permission", async () => { const user = await buildUser(); const collection = await buildCollection({ @@ -976,6 +1000,30 @@ describe("#collections.add_user", () => { }); describe("#collections.add_group", () => { + it("should preserve existing permission when permission is omitted", async () => { + const admin = await buildAdmin(); + const collection = await buildCollection({ + teamId: admin.teamId, + userId: admin.id, + permission: null, + }); + const group = await buildGroup({ teamId: admin.teamId }); + const membership = await GroupMembership.create({ + createdById: admin.id, + collectionId: collection.id, + groupId: group.id, + permission: CollectionPermission.Admin, + }); + + const res = await server.post("/api/collections.add_group", admin, { + body: { id: collection.id, groupId: group.id }, + }); + + expect(res.status).toEqual(200); + await membership.reload(); + expect(membership.permission).toEqual(CollectionPermission.Admin); + }); + it("should add group to collection", async () => { const user = await buildAdmin(); const collection = await buildCollection({ @@ -1916,6 +1964,24 @@ describe("#collections.duplicate", () => { }); describe("#collections.update", () => { + it("should not add a membership when permission is omitted", async () => { + const admin = await buildAdmin(); + const collection = await buildCollection({ + teamId: admin.teamId, + permission: CollectionPermission.ReadWrite, + }); + + const res = await server.post("/api/collections.update", admin, { + body: { id: collection.id, name: "Renamed" }, + }); + + expect(res.status).toEqual(200); + const membership = await UserMembership.findOne({ + where: { collectionId: collection.id, userId: admin.id }, + }); + expect(membership).toBeNull(); + }); + describe("deprecatedReason", () => { it.each(["admin", "manager"])( "should let a collection %s save a reason without changing archive attribution", diff --git a/server/routes/api/collections/collections.ts b/server/routes/api/collections/collections.ts index 89f2a4a10d..725060b5a3 100644 --- a/server/routes/api/collections/collections.ts +++ b/server/routes/api/collections/collections.ts @@ -255,14 +255,16 @@ router.post( ); if (membership) { - membership.permission = permission; - await membership.save(ctx.context); + if (permission !== undefined) { + membership.permission = permission; + await membership.save(ctx.context); + } } else { membership = await GroupMembership.create( { collectionId: id, groupId, - permission, + permission: permission ?? CollectionPermission.ReadWrite, createdById: user.id, }, ctx.context @@ -409,8 +411,10 @@ router.post( ); if (membership) { - membership.permission = permission || user.defaultCollectionPermission; - await membership.save(ctx.context); + if (permission !== undefined) { + membership.permission = permission; + await membership.save(ctx.context); + } } else { membership = await UserMembership.create( { @@ -642,6 +646,7 @@ router.post( // we're making this collection have no default access, ensure that the // current user has an admin membership so that at least they can manage it. if ( + permission !== undefined && permission !== CollectionPermission.ReadWrite && collection.permission === CollectionPermission.ReadWrite ) { @@ -666,50 +671,21 @@ router.post( } } - let privacyChanged = false; - let sharingChanged = false; + collection.fill({ + name: name?.trim(), + description, + content: data, + icon, + color, + permission, + sharing, + sort, + commenting, + templateManagement, + }); - if (name !== undefined) { - collection.name = name.trim(); - } - - if (description !== undefined) { - collection.description = description; - } - - if (data !== undefined) { - collection.content = data; - } - - if (icon !== undefined) { - collection.icon = icon; - } - - if (color !== undefined) { - collection.color = color; - } - - if (permission !== undefined) { - privacyChanged = permission !== collection.permission; - collection.permission = permission ? permission : null; - } - - if (sharing !== undefined) { - sharingChanged = sharing !== collection.sharing; - collection.sharing = sharing; - } - - if (sort !== undefined) { - collection.sort = sort; - } - - if (commenting !== undefined) { - collection.commenting = commenting; - } - - if (templateManagement !== undefined) { - collection.templateManagement = templateManagement; - } + const privacyChanged = collection.changed("permission"); + const sharingChanged = collection.changed("sharing"); await collection.saveWithCtx(ctx); diff --git a/server/routes/api/collections/schema.ts b/server/routes/api/collections/schema.ts index f5a7c7e743..8e45e563eb 100644 --- a/server/routes/api/collections/schema.ts +++ b/server/routes/api/collections/schema.ts @@ -117,9 +117,7 @@ export type CollectionsImportReq = z.infer; export const CollectionsAddGroupSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ groupId: z.uuid(), - permission: z - .enum(CollectionPermission) - .prefault(CollectionPermission.ReadWrite), + permission: z.enum(CollectionPermission).optional(), }), }); diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index d4a02bd4ec..ab09a3c581 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -8882,6 +8882,35 @@ describe("#documents.remove_user", () => { }); describe("#documents.add_group", () => { + it("should preserve existing permission when permission is omitted", async () => { + const user = await buildUser(); + const collection = await buildCollection({ + teamId: user.teamId, + createdById: user.id, + permission: null, + }); + const document = await buildDocument({ + collectionId: collection.id, + createdById: user.id, + teamId: user.teamId, + }); + const group = await buildGroup({ teamId: user.teamId }); + const membership = await GroupMembership.create({ + createdById: user.id, + documentId: document.id, + groupId: group.id, + permission: DocumentPermission.Admin, + }); + + const res = await server.post("/api/documents.add_group", user, { + body: { id: document.id, groupId: group.id }, + }); + + expect(res.status).toEqual(200); + await membership.reload(); + expect(membership.permission).toEqual(DocumentPermission.Admin); + }); + it("should require id", async () => { const user = await buildUser(); const res = await server.post("/api/documents.add_group", user); diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index 028a26c952..a8b271e42a 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -13,6 +13,7 @@ import { randomUUID } from "node:crypto"; import type { DirectionFilter, SortFilter } from "@shared/types"; import { type NavigationNode } from "@shared/types"; import { + DocumentPermission, ExportContentType, FileOperationFormat, StatusFilter, @@ -2101,7 +2102,7 @@ router.post( { documentId: id, groupId, - permission: permission || user.defaultDocumentPermission, + permission: permission ?? DocumentPermission.ReadWrite, createdById: user.id, }, ctx.context diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index f533cbbb3e..4948645c95 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -689,9 +689,7 @@ export type DocumentsRemoveUserReq = z.infer; export const DocumentsAddGroupSchema = BaseSchema.extend({ body: BaseIdSchema.extend({ groupId: z.uuid(), - permission: z - .enum(DocumentPermission) - .prefault(DocumentPermission.ReadWrite), + permission: z.enum(DocumentPermission).optional(), }), }); diff --git a/server/routes/api/integrations/integrations.test.ts b/server/routes/api/integrations/integrations.test.ts index 58000ebf97..a7bdb2015f 100644 --- a/server/routes/api/integrations/integrations.test.ts +++ b/server/routes/api/integrations/integrations.test.ts @@ -13,6 +13,24 @@ import { getTestServer } from "@server/test/support"; const server = getTestServer(); describe("#integrations.update", () => { + it("should preserve settings and events when they are omitted", async () => { + const admin = await buildAdmin(); + const integration = await buildIntegration({ + userId: admin.id, + teamId: admin.teamId, + }); + const { settings, events } = integration; + + const res = await server.post("/api/integrations.update", admin, { + body: { id: integration.id }, + }); + + expect(res.status).toEqual(200); + await integration.reload(); + expect(integration.settings).toEqual(settings); + expect(integration.events).toEqual(events); + }); + it("should allow updating integration events", async () => { const team = await buildTeam(); const user = await buildAdmin({ teamId: team.id }); diff --git a/server/routes/api/integrations/integrations.ts b/server/routes/api/integrations/integrations.ts index fdd1bdb1eb..244a79eea3 100644 --- a/server/routes/api/integrations/integrations.ts +++ b/server/routes/api/integrations/integrations.ts @@ -133,13 +133,15 @@ router.post( }); authorize(user, "update", integration); - if (integration.type === IntegrationType.Post) { + if (events !== undefined && integration.type === IntegrationType.Post) { integration.events = events.filter((event: string) => ["documents.update", "documents.publish"].includes(event) ); } - integration.settings = settings; + if (settings !== undefined) { + integration.settings = settings; + } await integration.saveWithCtx(ctx); diff --git a/server/routes/api/integrations/schema.ts b/server/routes/api/integrations/schema.ts index bf72b0245d..06eb0f9f26 100644 --- a/server/routes/api/integrations/schema.ts +++ b/server/routes/api/integrations/schema.ts @@ -135,7 +135,7 @@ export const IntegrationsUpdateSchema = BaseSchema.extend({ .optional(), /** Integration events */ - events: z.array(z.string()).prefault([]), + events: z.array(z.string()).optional(), }), }); diff --git a/server/routes/api/notifications/notifications.ts b/server/routes/api/notifications/notifications.ts index 40509e031a..811a1d1d1b 100644 --- a/server/routes/api/notifications/notifications.ts +++ b/server/routes/api/notifications/notifications.ts @@ -218,12 +218,7 @@ router.post( }); authorize(user, "update", notification); - if (!isUndefined(viewedAt)) { - notification.viewedAt = viewedAt; - } - if (!isUndefined(archivedAt)) { - notification.archivedAt = archivedAt; - } + notification.fill({ viewedAt, archivedAt }); await notification.saveWithCtx(ctx); ctx.body = { diff --git a/server/routes/api/shares/shares.ts b/server/routes/api/shares/shares.ts index 320bcbfc07..d5ad638408 100644 --- a/server/routes/api/shares/shares.ts +++ b/server/routes/api/shares/shares.ts @@ -1,5 +1,4 @@ import Router from "@koa/router"; -import { isUndefined } from "es-toolkit/compat"; import type { FindOptions, WhereAttributeHash, WhereOptions } from "sequelize"; import { Op } from "sequelize"; import { randomString } from "@shared/random"; @@ -376,41 +375,22 @@ router.post( authorize(user, "update", share); - if (published !== undefined) { - share.published = published; - if (published) { - share.includeChildDocuments = true; - } + // Publishing a share includes child documents unless specified otherwise. + if (published) { + share.includeChildDocuments = true; } - if (includeChildDocuments !== undefined) { - share.includeChildDocuments = includeChildDocuments; - } - - if (!isUndefined(urlId)) { - share.urlId = urlId; - } - - if (allowIndexing !== undefined) { - share.allowIndexing = allowIndexing; - } - if (allowSubscriptions !== undefined) { - share.allowSubscriptions = allowSubscriptions; - } - if (showLastUpdated !== undefined) { - share.showLastUpdated = showLastUpdated; - } - if (showTOC !== undefined) { - share.showTOC = showTOC; - } - - if (!isUndefined(title)) { - share.title = title || null; - } - - if (!isUndefined(iconUrl)) { - share.iconUrl = iconUrl || null; - } + share.fill({ + published, + includeChildDocuments, + urlId, + allowIndexing, + allowSubscriptions, + showLastUpdated, + showTOC, + title: title === "" ? null : title, + iconUrl: iconUrl === "" ? null : iconUrl, + }); await share.saveWithCtx(ctx); diff --git a/server/routes/api/users/users.ts b/server/routes/api/users/users.ts index 03f9f4f20b..40129ca80d 100644 --- a/server/routes/api/users/users.ts +++ b/server/routes/api/users/users.ts @@ -287,28 +287,24 @@ router.post( authorize(actor, "update", user); const includeDetails = !!can(actor, "readDetails", user); - if (name) { - user.name = name; - } - if (avatarUrl !== undefined) { - user.avatarUrl = avatarUrl; + user.fill({ + name: name || undefined, + avatarUrl, + language: language || undefined, + timezone: timezone || undefined, + }); - // Mark that the user has manually changed their avatar - // This prevents automatic syncing from identity providers + // Mark that the user has manually changed their avatar + // This prevents automatic syncing from identity providers + if (avatarUrl !== undefined) { user.setFlag(UserFlag.AvatarUpdated, avatarUrl ? true : false); } - if (language) { - user.language = language; - } if (preferences) { user.preferences = { ...user.preferences, ...preferences, }; } - if (timezone) { - user.timezone = timezone; - } await user.saveWithCtx(ctx);