Node.js based forum software built for the modern web
refactor tests (#14211)
Julian Lam92f6bba4ebb8
diff --git a/install/data/defaults.json b/install/data/defaults.jsonindex 3e0b845c7f..0724b37af4 100644--- a/install/data/defaults.json+++ b/install/data/defaults.json@@ -153,7 +153,7 @@"email:disableEdit": 0,"email:smtpTransport:pool": 0,"email:smtpTransport:allow-self-signed": 0,- "hideFullname": 0,+ "hideFullname": 1,"hideEmail": 0,"showFullnameAsDisplayName": 0,"allowGuestHandles": 0,diff --git a/install/package.json b/install/package.jsonindex ff7db19770..268fd397a2 100644--- a/install/package.json+++ b/install/package.json@@ -168,6 +168,7 @@"coveralls": "3.1.1","@eslint/js": "10.0.1","@stylistic/eslint-plugin": "5.10.0",+ "ajv": "^8.20.0","eslint-config-nodebb": "2.0.1","globals": "17.6.0","grunt": "1.6.2",diff --git a/public/openapi/components/schemas/CategoryObject.yaml b/public/openapi/components/schemas/CategoryObject.yamlindex fa377cbcdd..d3557b6b0b 100644--- a/public/openapi/components/schemas/CategoryObject.yaml+++ b/public/openapi/components/schemas/CategoryObject.yaml@@ -1,6 +1,7 @@CategoryObject:allOf:- type: object+ nullable: trueproperties:cid:type: number@@ -87,6 +88,7 @@ CategoryObject:type: numberdescription: The number of subcategories to display on the categories and category page- type: object+ nullable: truedescription: Optional properties that may or may not be present (except for `cid`, which is always present, and is only here as a hack to pass validation)properties:cid:diff --git a/public/openapi/components/schemas/Chats.yaml b/public/openapi/components/schemas/Chats.yamlindex 3d4339c083..02b27f0462 100644--- a/public/openapi/components/schemas/Chats.yaml+++ b/public/openapi/components/schemas/Chats.yaml@@ -2,7 +2,7 @@ RoomObject:type: objectproperties:roomId:- type: number+ type: [number, string]description: unique identifier for the chat roomroomName:type: string@@ -42,7 +42,7 @@ MessageObject:fromuid:type: numberroomId:- type: number+ type: [number, string]deleted:type: numbersystem:diff --git a/public/openapi/components/schemas/FlagObject.yaml b/public/openapi/components/schemas/FlagObject.yamlindex 38e27e8f9e..31fef07c21 100644--- a/public/openapi/components/schemas/FlagObject.yaml+++ b/public/openapi/components/schemas/FlagObject.yaml@@ -52,6 +52,7 @@ FlagObject:description: An URL-safe variant of the username (i.e. lower-cased, spacesremoved, etc.)picture:+ type: stringnullable: truereputation:type: number@@ -84,7 +85,7 @@ FlagHistoryObject:type: objectproperties:uid:- type: number+ type: [number, string]description: A user identifierfields:type: object@@ -121,6 +122,7 @@ FlagHistoryObject:description: An URL-safe variant of the username (i.e. lower-cased, spacesremoved, etc.)picture:+ type: stringnullable: trueuid:type: numberdiff --git a/public/openapi/components/schemas/GroupObject.yaml b/public/openapi/components/schemas/GroupObject.yamlindex 99148f249d..5ab75cb367 100644--- a/public/openapi/components/schemas/GroupObject.yaml+++ b/public/openapi/components/schemas/GroupObject.yaml@@ -12,10 +12,10 @@ GroupFullObject:type: numberdescription: UNIX timestamp of the group's creationuserTitle:- type: number+ type: stringdescription: Label text for the user badgeuserTitleEscaped:- type: number+ type: stringdescription: Same as userTitle but with translation tokens escaped, used to display raw userTitle in group managementuserTitleEnabled:type: number@@ -163,10 +163,10 @@ GroupDataObject:type: numberdescription: UNIX timestamp of the group's creationuserTitle:- type: number+ type: stringdescription: Label text for the user badgeuserTitleEscaped:- type: number+ type: stringdescription: Same as userTitle but with translation tokens escaped, used to display raw userTitle in group managementuserTitleEnabled:type: numberdiff --git a/public/openapi/components/schemas/Pagination.yaml b/public/openapi/components/schemas/Pagination.yamlindex f9b79408cc..0e03fdc06d 100644--- a/public/openapi/components/schemas/Pagination.yaml+++ b/public/openapi/components/schemas/Pagination.yaml@@ -3,12 +3,12 @@ PaginationProps:- type: objectdescription: Optional properties that may or may not be present (except for `page`, which is always present, and is only here as a hack to pass validation)properties:- page:+ currentPage:type: numberqs:type: stringrequired:- - cid+ - currentPagePagination:type: objectproperties:diff --git a/public/openapi/components/schemas/PostObject.yaml b/public/openapi/components/schemas/PostObject.yamlindex 54dcc248c2..60e0672538 100644--- a/public/openapi/components/schemas/PostObject.yaml+++ b/public/openapi/components/schemas/PostObject.yaml@@ -3,7 +3,7 @@ PostObject:type: objectproperties:pid:- type: number+ type: [number, string]tid:type: numberdescription: A topic identifier@@ -94,7 +94,7 @@ PostObject:deleted:type: numberscheduled:- type: number+ type: booleantimestamp:type: numbertimestampISO:@@ -107,7 +107,7 @@ PostObject:description: The post id of the first post in this topic (also called the"original post")teaserPid:- type: number+ type: [number, string]description: The post id of the teaser (the most recent post, depending on settings)nullable: truetitleRaw:@@ -128,7 +128,7 @@ PostObject:type: objectproperties:id:- type: number+ type: stringdescription: The topic idname:type: string@@ -168,6 +168,7 @@ PostObject:color:type: stringbackgroundImage:+ type: stringnullable: trueimageClass:nullable: true@@ -247,7 +248,7 @@ PostDataObject:signature:type: stringbanned:- type: number+ type: booleanbanned:expire:type: numberstatus:@@ -312,6 +313,7 @@ PostDataObject:type: stringdescription: HTML that is injected into `topic.tpl` of themes that support custom profile infoeditor:+ type: numbernullable: truebookmarked:type: boolean@@ -403,6 +405,7 @@ PostDataObject:description: A post identifiersourceContent:type: string+ nullable: truedescription: The markdown equivalent of a remote post content, as received (or fetched) from the remote site.required:- piddiff --git a/public/openapi/components/schemas/PostsObject.yaml b/public/openapi/components/schemas/PostsObject.yamlindex 5a079a08d9..546ff704f1 100644--- a/public/openapi/components/schemas/PostsObject.yaml+++ b/public/openapi/components/schemas/PostsObject.yaml@@ -8,7 +8,7 @@ PostsObject:description: Optional properties that may or may not be present (except for `pid`, which is always present, and is only here as a hack to pass validation)properties:pid:- type: number+ type: [number, string]description: A post identifierattachments:type: arraydiff --git a/public/openapi/components/schemas/SettingsObj.yaml b/public/openapi/components/schemas/SettingsObj.yamlindex d3b8641485..d56470704a 100644--- a/public/openapi/components/schemas/SettingsObj.yaml+++ b/public/openapi/components/schemas/SettingsObj.yaml@@ -90,8 +90,10 @@ Settings:type: stringdescription: Notification type for post editssendChatNotifications:+ type: booleannullable: truesendPostNotifications:+ type: booleannullable: truenotificationType_upvote:type: string@@ -161,7 +163,6 @@ Settings:- showfullname- followTopicsOnCreate- followTopicsOnReply- - restrictChat- topicSearchEnabled- categoryTopicSort- userLangdiff --git a/public/openapi/components/schemas/TopicObject.yaml b/public/openapi/components/schemas/TopicObject.yamlindex 6a3f212541..68ae3c1236 100644--- a/public/openapi/components/schemas/TopicObject.yaml+++ b/public/openapi/components/schemas/TopicObject.yaml@@ -75,7 +75,7 @@ TopicObject:iconexample: "#f44336"banned:- type: number+ type: booleanbanned_until:type: numberbanned_until_readable:@@ -178,7 +178,7 @@ TopicObjectSlim:followercount:type: numberscheduled:- type: number+ type: booleandeleted:type: numberdeleterUid:@@ -217,14 +217,14 @@ TopicObjectSlim:oneOf:- type: number- type: string- nullable: true+ - type: 'null'thumbs:type: arrayitems:type: objectproperties:id:- type: number+ type: [number, string]description: The topic idname:type: stringdiff --git a/public/openapi/components/schemas/UserObj.yaml b/public/openapi/components/schemas/UserObj.yamlindex fc2837b2cb..7b3adc4371 100644--- a/public/openapi/components/schemas/UserObj.yaml+++ b/public/openapi/components/schemas/UserObj.yaml@@ -23,9 +23,11 @@ UserObj:example: 1585337827953picture:type: string+ nullable: trueexample: 'https://images.unsplash.com/photo-1560070094-e1f2ddec4337?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=256&h=256&q=80'fullname:type: string+ nullable: trueexample: Mr. Dragon Fruit Jr.displayname:type: string@@ -37,23 +39,27 @@ UserObj:birthday:type: stringdescription: A birthdate given in an ISO format parseable by the Date object+ nullable: trueexample: 03/27/2020website:type: stringexample: 'https://example.org'aboutme:type: string+ nullable: trueexample: |This is a paragraph all about how my life got twist-turned upside-downand I'd like to take a minute and sit right here,to tell you all about how I because the administrator of NodeBBsignature:type: string+ nullable: trueexample: |This is an example signatureIt can span multiple lines.uploadedpicture:type: string+ nullable: trueexample: /assets/profile/1-profileimg.pngdescription: 'In almost all cases, defer to "picture" instead. Use this if you need to specifically reference the picture uploaded to the forum.'profileviews:@@ -72,7 +78,7 @@ UserObj:type: numberexample: 1585337827953banned:- type: number+ type: booleanexample: 0'banned:expire':type: number@@ -94,9 +100,11 @@ UserObj:example: /assets/profile/1-cover.png'cover:position':type: string+ nullable: trueexample: 50.0301% 19.2464%groupTitle:type: string+ nullable: trueexample: '["administrators","Staff"]'groupTitleArray:type: arraydiff --git a/public/openapi/components/schemas/UserObject.yaml b/public/openapi/components/schemas/UserObject.yamlindex 9a94e68c25..984a1ce6d5 100644--- a/public/openapi/components/schemas/UserObject.yaml+++ b/public/openapi/components/schemas/UserObject.yaml@@ -39,6 +39,7 @@ UserObject:nullable: truefullname:type: string+ nullable: trueexample: Mr. Dragon Fruit Jr.displayname:type: string@@ -86,9 +87,9 @@ UserObject:description: A UNIX timestamp representing the moment the user posted lastexample: 1585337827953banned:- type: number+ type: booleandescription: A Boolean representing whether a user is banned or not- example: 0+ example: false'banned:expire':type: numberdescription: A UNIX timestamp representing the moment the ban will be lifted@@ -136,6 +137,7 @@ UserObject:description: A UNIX timestamp representing the moment a muted state will be lifted.mutedReason:type: string+ nullable: truedescription: The admin-provided reason for being muted.'icon:text':type: string@@ -179,7 +181,6 @@ UserObject:- banned- 'banned:expire'- status- - enum- flags- followerCount- followingCount@@ -187,7 +188,6 @@ UserObject:- 'cover:position'- groupTitle- groupTitleArray- - example- 'icon:text'- 'icon:bgColor'- joindateISO@@ -218,7 +218,7 @@ UserObjectFull:description: Email address associated with the user accountexample: [email protected]'email:confirmed':- type: number+ type: booleandescription: Whether the user has confirmed their email address or notexample: 1joindate:@@ -280,7 +280,7 @@ UserObjectFull:description: A UNIX timestamp representing the moment the user posted lastexample: 1585337827953banned:- type: number+ type: booleandescription: A Boolean representing whether a user is banned or notexample: 0'banned:expire':@@ -510,9 +510,9 @@ UserObjectFull:- visibility- publicusername:disableEdit:- type: number+ type: booleanemail:disableEdit:- type: number+ type: booleanUserObjectSlim:type: objectproperties:@@ -568,7 +568,7 @@ UserObjectSlim:example: 0nullable: truebanned:- type: number+ type: booleandescription: A Boolean representing whether a user is banned or notexample: 0'banned:expire':@@ -613,6 +613,7 @@ UserObjectTiny:removed, etc.)picture:type: string+ nullable: trueuid:type: numberdescription: A user identifier@@ -668,7 +669,7 @@ UserObjectACP:description: A UNIX timestamp representing the moment the user's account was createdexample: 1585337827953banned:- type: number+ type: booleandescription: A Boolean representing whether a user is banned or notexample: 0reputation:diff --git a/public/openapi/read/admin/advanced/cache.yaml b/public/openapi/read/admin/advanced/cache.yamlindex c80fe41937..b19aaf2afb 100644--- a/public/openapi/read/admin/advanced/cache.yaml+++ b/public/openapi/read/admin/advanced/cache.yaml@@ -21,108 +21,106 @@ get:- type: objectproperties:caches:- type: object- properties:- postCache:- type: object- properties:- length:- type: number- max:- type: number- nullable: true- maxSize:- type: number- itemCount:- type: number- percentFull:- type: number- hits:- type: string- hitsPerSecond:- type: number- misses:- type: string- hitRatio:- type: string- enabled:- type: boolean- ttl:- type: number- groupCache:- type: object- properties:- length:- type: number- max:- type: number- nullable: true- maxSize:- type: number- itemCount:- type: number- percentFull:- type: number- hits:- type: string- misses:- type: string- hitRatio:- type: string- enabled:- type: boolean- ttl:- type: number- localCache:- type: object- properties:- length:- type: number- max:- type: number- nullable: true- maxSize:- type: number- itemCount:- type: number- percentFull:- type: number- hits:- type: string- misses:- type: string- hitRatio:- type: string- enabled:- type: boolean- ttl:- type: number- objectCache:- type: object- properties:- length:- type: number- max:- type: number- nullable: true- maxSize:- type: number- itemCount:- type: number- percentFull:- type: number- hits:- type: string- misses:- type: string- hitRatio:- type: string- enabled:- type: boolean- ttl:- type: number- required:- - postCache- - groupCache- - localCache+ type: array+ items:+ type: object+ properties:+ postCache:+ type: object+ properties:+ length:+ type: number+ max:+ type: number+ nullable: true+ maxSize:+ type: number+ itemCount:+ type: number+ percentFull:+ type: number+ hits:+ type: string+ hitsPerSecond:+ type: number+ misses:+ type: string+ hitRatio:+ type: string+ enabled:+ type: boolean+ ttl:+ type: number+ groupCache:+ type: object+ properties:+ length:+ type: number+ max:+ type: number+ nullable: true+ maxSize:+ type: number+ itemCount:+ type: number+ percentFull:+ type: number+ hits:+ type: string+ misses:+ type: string+ hitRatio:+ type: string+ enabled:+ type: boolean+ ttl:+ type: number+ localCache:+ type: object+ properties:+ length:+ type: number+ max:+ type: number+ nullable: true+ maxSize:+ type: number+ itemCount:+ type: number+ percentFull:+ type: number+ hits:+ type: string+ misses:+ type: string+ hitRatio:+ type: string+ enabled:+ type: boolean+ ttl:+ type: number+ objectCache:+ type: object+ properties:+ length:+ type: number+ max:+ type: number+ nullable: true+ maxSize:+ type: number+ itemCount:+ type: number+ percentFull:+ type: number+ hits:+ type: string+ misses:+ type: string+ hitRatio:+ type: string+ enabled:+ type: boolean+ ttl:+ type: number- $ref: ../../../components/schemas/CommonProps.yaml#/CommonProps\ No newline at end of filediff --git a/public/openapi/read/admin/advanced/cache/dump.yaml b/public/openapi/read/admin/advanced/cache/dump.yamlindex 2be4e38f9b..2fc47d7fc7 100644--- a/public/openapi/read/admin/advanced/cache/dump.yaml+++ b/public/openapi/read/admin/advanced/cache/dump.yaml@@ -13,11 +13,10 @@ get:example: 'post'responses:"200":- description: ""content:application/json:schema:- type: object+ type: array+ description: The type of response is dependent on the database used. Please examine the output.properties: {}- additionalProperties:- description: The type of response is dependent on the database used. Please examine the output.\ No newline at end of file+ additionalProperties: true\ No newline at end of filediff --git a/public/openapi/read/admin/advanced/database.yaml b/public/openapi/read/admin/advanced/database.yamlindex ae2676b369..a2c9888ff3 100644--- a/public/openapi/read/admin/advanced/database.yaml+++ b/public/openapi/read/admin/advanced/database.yaml@@ -4,11 +4,11 @@ get:summary: Get database informationresponses:"200":- description: "A JSON object with database status information"+ description: |+ A JSON object with database status information.+ Each database configured will have an entry here with information about its runtime statuscontent:application/json:schema:properties: {}- additionalProperties:- type: object- description: Each database configured will have an entry here with information about its runtime status\ No newline at end of file+ additionalProperties: true\ No newline at end of filediff --git a/public/openapi/read/admin/advanced/jobs.yaml b/public/openapi/read/admin/advanced/jobs.yamlindex 4a85013493..c7caab66eb 100644--- a/public/openapi/read/admin/advanced/jobs.yaml+++ b/public/openapi/read/admin/advanced/jobs.yaml@@ -25,7 +25,7 @@ get:nextRun:type: integernextRunISO:- type: integer+ type: stringduration:type: integerdurationReadable:diff --git a/public/openapi/read/admin/development/info.yaml b/public/openapi/read/admin/development/info.yamlindex 1bf9da12dc..3304b2d085 100644--- a/public/openapi/read/admin/development/info.yaml+++ b/public/openapi/read/admin/development/info.yaml@@ -33,10 +33,10 @@ get:type: numberdescription: Process idtitle:- type: number+ type: stringdescription: Executableversion:- type: number+ type: stringdescription: NodeBB versionmemoryUsage:type: object@@ -52,9 +52,9 @@ get:arrayBuffers:type: numberrssReadable:- type: number+ type: stringheapUsedReadable:- type: number+ type: stringrequired:- rss- heapTotal@@ -67,7 +67,7 @@ get:uptimeHumanReadable:type: stringcpuUsage:- type: number+ type: stringos:type: objectproperties:diff --git a/public/openapi/read/admin/manage/admins-mods.yaml b/public/openapi/read/admin/manage/admins-mods.yamlindex 7bb63ec3aa..feaf769e6b 100644--- a/public/openapi/read/admin/manage/admins-mods.yaml+++ b/public/openapi/read/admin/manage/admins-mods.yaml@@ -29,8 +29,6 @@ get:subCategoryCount:type: numberselectedCategory:- nullable: true- anyOf:- - $ref: ../../../components/schemas/CategoryObject.yaml#/CategoryObject+ $ref: ../../../components/schemas/CategoryObject.yaml#/CategoryObject- $ref: ../../../components/schemas/Pagination.yaml#/Pagination- $ref: ../../../components/schemas/CommonProps.yaml#/CommonProps\ No newline at end of filediff --git a/public/openapi/read/admin/manage/privileges/cid.yaml b/public/openapi/read/admin/manage/privileges/cid.yamlindex c395f39172..50e8ceb8ff 100644--- a/public/openapi/read/admin/manage/privileges/cid.yaml+++ b/public/openapi/read/admin/manage/privileges/cid.yaml@@ -88,7 +88,7 @@ get:type: objectproperties:cid:- type: number+ type: [number, string]description: A category identifiername:type: stringdiff --git a/public/openapi/read/admin/settings/general.yaml b/public/openapi/read/admin/settings/general.yamlindex d19ff555ee..84df1f59bd 100644--- a/public/openapi/read/admin/settings/general.yaml+++ b/public/openapi/read/admin/settings/general.yaml@@ -10,6 +10,9 @@ get:schema:allOf:- type: object+ description: >-+ Most of the settings pages have their values loaded on the client-side,+ so the settings are not exposed server-side.properties:title:type: string@@ -21,7 +24,5 @@ get:type: arrayautoDetectLang:type: number- additionalProperties:- type: object- description: Most of the settings pages have their values loaded on the client-side, so the settings are not exposed server-side.+ additionalProperties: true- $ref: ../../../components/schemas/CommonProps.yaml#/CommonProps\ No newline at end of filediff --git a/public/openapi/read/admin/settings/navigation.yaml b/public/openapi/read/admin/settings/navigation.yamlindex c86f387997..e547ef62ae 100644--- a/public/openapi/read/admin/settings/navigation.yaml+++ b/public/openapi/read/admin/settings/navigation.yaml@@ -16,6 +16,9 @@ get:items:type: objectproperties:+ id:+ type: string+ description: Unique ID that will be added to the navigation element's `id` property in the DOMroute:type: stringdescription: Relative URL to the page the navigation item goes to@@ -33,6 +36,8 @@ get:text:type: stringdescription: Label text for this navigation item+ dropdownContent:+ type: stringorder:type: integerdescription: Ordinality of this item, lower value appears earlier@@ -50,6 +55,15 @@ get:description: Seemingly identical to order, but an integer instead of a stringselected:type: boolean+ required:+ - id+ - route+ - title+ - enabled+ - iconClass+ - textClass+ - text+ - groupsavailable:type: arrayitems:diff --git a/public/openapi/read/post-queue.yaml b/public/openapi/read/post-queue.yamlindex 9bd93903c4..b28ecbe83c 100644--- a/public/openapi/read/post-queue.yaml+++ b/public/openapi/read/post-queue.yaml@@ -125,6 +125,7 @@ get:type: numberdescription: A topic identifiertoPid:+ type: [number, string]nullable: trueuser:type: objectdiff --git a/public/openapi/read/search.yaml b/public/openapi/read/search.yamlindex 6e36fc3891..dcdb944ca4 100644--- a/public/openapi/read/search.yaml+++ b/public/openapi/read/search.yaml@@ -98,14 +98,10 @@ get:- time- multiplePages- search_query- - allCategories- - allCategoriesCount- - expandSearch- showAsPosts- showAsTopics- title- searchDefaultSortBy- - permissions- $ref: ../components/schemas/Pagination.yaml#/Pagination- $ref: ../components/schemas/Breadcrumbs.yaml#/Breadcrumbs- $ref: ../components/schemas/CommonProps.yaml#/CommonProps\ No newline at end of filediff --git a/public/openapi/read/tags/tag.yaml b/public/openapi/read/tags/tag.yamlindex 409ffb150b..6756e16e2b 100644--- a/public/openapi/read/tags/tag.yaml+++ b/public/openapi/read/tags/tag.yaml@@ -96,10 +96,11 @@ get:icon:type: stringimage:+ type: stringnullable: trueimageClass:- nullable: truetype: string+ nullable: truebgColor:type: stringcolor:@@ -162,6 +163,7 @@ get:unread:type: booleanbookmark:+ type: booleannullable: trueunreplied:type: boolean@@ -209,12 +211,11 @@ get:rssFeedUrl:type: stringfeeds:disableRSS:- type: boolean+ type: numberrequired:- topics- tag- title- - categories- $ref: ../../components/schemas/Pagination.yaml#/Pagination- $ref: ../../components/schemas/Breadcrumbs.yaml#/Breadcrumbs- $ref: ../../components/schemas/CommonProps.yaml#/CommonProps\ No newline at end of filediff --git a/public/openapi/read/topic/teaser/topic_id.yaml b/public/openapi/read/topic/teaser/topic_id.yamlindex 5b0450afa5..3e0b580cae 100644--- a/public/openapi/read/topic/teaser/topic_id.yaml+++ b/public/openapi/read/topic/teaser/topic_id.yaml@@ -15,4 +15,4 @@ get:content:application/json:schema:- $ref: ../../../components/schemas/PostsObject.yaml#/PostsObject\ No newline at end of file+ $ref: ../../../components/schemas/PostObject.yaml#/PostObject\ No newline at end of filediff --git a/public/openapi/read/topic/topic_id.yaml b/public/openapi/read/topic/topic_id.yamlindex 81b3e9531f..772920da93 100644--- a/public/openapi/read/topic/topic_id.yaml+++ b/public/openapi/read/topic/topic_id.yaml@@ -78,6 +78,7 @@ get:isIgnoring:type: booleanbookmark:+ type: booleannullable: truepostSharing:type: array@@ -93,10 +94,13 @@ get:activated:type: booleandeleter:+ type: numbernullable: truemerger:+ type: numbernullable: trueforker:+ type: numbernullable: truerelated:type: arraydiff --git a/public/openapi/read/unread.yaml b/public/openapi/read/unread.yamlindex 516299c1fc..763449bade 100644--- a/public/openapi/read/unread.yaml+++ b/public/openapi/read/unread.yaml@@ -52,10 +52,11 @@ get:icon:type: stringbackgroundImage:+ type: stringnullable: trueimageClass:- nullable: truetype: string+ nullable: truebgColor:type: stringcolor:@@ -94,7 +95,7 @@ get:nullable: truetype: stringbanned:- type: number+ type: booleanstatus:type: stringicon:text:@@ -141,6 +142,7 @@ get:unread:type: booleanbookmark:+ type: booleannullable: trueunreplied:type: booleandiff --git a/public/openapi/read/user/userslug/followers.yaml b/public/openapi/read/user/userslug/followers.yamlindex a4abeaa4ed..a33319ee5e 100644--- a/public/openapi/read/user/userslug/followers.yaml+++ b/public/openapi/read/user/userslug/followers.yaml@@ -56,6 +56,7 @@ get:lastonline:type: numberflags:+ type: numbernullable: truebanned:type: numberdiff --git a/public/openapi/read/user/userslug/following.yaml b/public/openapi/read/user/userslug/following.yamlindex 3329b8a543..2df193e818 100644--- a/public/openapi/read/user/userslug/following.yaml+++ b/public/openapi/read/user/userslug/following.yaml@@ -56,6 +56,7 @@ get:lastonline:type: numberflags:+ type: numbernullable: truebanned:type: numberdiff --git a/public/openapi/read/users.yaml b/public/openapi/read/users.yamlindex 7fb7e7011c..1399fadb34 100644--- a/public/openapi/read/users.yaml+++ b/public/openapi/read/users.yaml@@ -63,9 +63,9 @@ get:lastonline:type: numberflags:- nullable: true- banned:type: number+ banned:+ type: booleanbanned:expire:type: numberjoindate:diff --git a/public/openapi/read/world.yaml b/public/openapi/read/world.yamlindex d2cbe0b332..50fa8619a5 100644--- a/public/openapi/read/world.yaml+++ b/public/openapi/read/world.yaml@@ -25,15 +25,9 @@ get:items:type: stringposts:- allOf:- - $ref: ../components/schemas/PostsObject.yaml#/PostsObject- - type: object- properties:- bookmarks:- type: number+ $ref: ../components/schemas/PostsObject.yaml#/PostsObjectselectedCategory:$ref: ../components/schemas/CategoryObject.yaml#/CategoryObject- nullable: trueshowThumbs:type: booleanshowTopicTools:diff --git a/public/openapi/write/categories/cid/moderator/uid.yaml b/public/openapi/write/categories/cid/moderator/uid.yamlindex bbba82c7c6..365113711c 100644--- a/public/openapi/write/categories/cid/moderator/uid.yaml+++ b/public/openapi/write/categories/cid/moderator/uid.yaml@@ -76,7 +76,7 @@ put:description: A six-character hexadecimal colour code assigned to the user. This value is used in conjunction with `icon:text` for the user's auto-generated iconexample: '#9c27b0'banned:- type: number+ type: booleandescription: A Boolean representing whether a user is banned or notexample: 0banned_until:diff --git a/public/openapi/write/posts/pid.yaml b/public/openapi/write/posts/pid.yamlindex 2203992b52..916d4d9921 100644--- a/public/openapi/write/posts/pid.yaml+++ b/public/openapi/write/posts/pid.yaml@@ -78,6 +78,7 @@ get:description: A post identifiersourceContent:type: string+ nullable: truedescription: The markdown equivalent of a remote post content, as received (or fetched) from the remote site.required:- pid@@ -127,7 +128,7 @@ put:- type: objectproperties:edited:- type: boolean+ type: numberdeleterUid:type: numberdelete:diff --git a/public/openapi/write/posts/pid/diffs.yaml b/public/openapi/write/posts/pid/diffs.yamlindex ca8dd91ac7..929e92e543 100644--- a/public/openapi/write/posts/pid/diffs.yaml+++ b/public/openapi/write/posts/pid/diffs.yaml@@ -27,7 +27,7 @@ get:uid:type: numberpid:- type: number+ type: [number, string]timestamps:type: arrayitems:@@ -42,7 +42,7 @@ get:username:type: stringuid:- type: number+ type: [number, string]editable:type: booleandeletable:diff --git a/public/openapi/write/posts/pid/replies.yaml b/public/openapi/write/posts/pid/replies.yamlindex b021eec14e..bf4140f80b 100644--- a/public/openapi/write/posts/pid/replies.yaml+++ b/public/openapi/write/posts/pid/replies.yaml@@ -155,6 +155,7 @@ get:type: stringdescription: HTML that is injected into `topic.tpl` of themes that support custom profile infoeditor:+ type: [number, string]nullable: truebookmarked:type: booleandiff --git a/public/openapi/write/topics/tid/thumbs.yaml b/public/openapi/write/topics/tid/thumbs.yamlindex 3ce9aafe9f..025b6e5791 100644--- a/public/openapi/write/topics/tid/thumbs.yaml+++ b/public/openapi/write/topics/tid/thumbs.yaml@@ -73,16 +73,22 @@ post:content:application/json:schema:- type: array- items:- type: object- properties:- url:- type: string- path:- type: string- name:- type: string+ type: object+ properties:+ status:+ $ref: ../../../components/schemas/Status.yaml#/Status+ response:+ type: object+ properties:+ images:+ type: array+ items:+ type: object+ properties:+ url:+ type: string+ name:+ type: stringdelete:tags:- topicsdiff --git a/public/openapi/write/users/uid/invites/groups.yaml b/public/openapi/write/users/uid/invites/groups.yamlindex 5683db658d..900ace48da 100644--- a/public/openapi/write/users/uid/invites/groups.yaml+++ b/public/openapi/write/users/uid/invites/groups.yaml@@ -16,8 +16,13 @@ get:content:application/json:schema:- type: array- items:- type: string+ type: object+ properties:+ status:+ $ref: ../../../../components/schemas/Status.yaml#/Status+ response:+ type: array+ items:+ type: string'401':$ref: ../../../../components/responses/401.yaml#/401\ No newline at end of filediff --git a/src/activitypub/rules.js b/src/activitypub/rules.jsindex 656f03e2de..4f3d00460e 100644--- a/src/activitypub/rules.js+++ b/src/activitypub/rules.js@@ -12,6 +12,7 @@ Rules.list = async () => {let rules = await db.getObjects(rids.map(rid => `rid:${rid}`));rules = rules.map((rule, idx) => {rule.rid = rids[idx];+ rule.cid = parseInt(rule.cid, 10);return rule;});diff --git a/src/api/utils.js b/src/api/utils.jsindex 06d6ce741d..0426b90d87 100644--- a/src/api/utils.js+++ b/src/api/utils.js@@ -41,9 +41,11 @@ utils.tokens.get = async (tokens) => {}tokenObj.token = tokens[idx];+ tokenObj.uid = parseInt(tokenObj.uid, 10);+ tokenObj.timestamp = parseInt(tokenObj.timestamp, 10);tokenObj.lastSeen = lastSeen[idx];tokenObj.lastSeenISO = lastSeen[idx] ? new Date(lastSeen[idx]).toISOString() : null;- tokenObj.timestampISO = new Date(parseInt(tokenObj.timestamp, 10)).toISOString();+ tokenObj.timestampISO = new Date(tokenObj.timestamp).toISOString();return tokenObj;});diff --git a/src/categories/watch.js b/src/categories/watch.jsindex 8eb8e9b7c0..f91e85f743 100644--- a/src/categories/watch.js+++ b/src/categories/watch.js@@ -30,7 +30,7 @@ module.exports = function (Categories) {}const keys = cids.map(cid => `cid:${cid}:uid:watch:state`);const [userSettings, states] = await Promise.all([- user.getSettings(uid),+ utils.isNumber(uid) ? user.getSettings(uid) : { categoryWatchState: 0 },db.sortedSetsScore(keys, uid),]);diff --git a/src/controllers/admin/categories.js b/src/controllers/admin/categories.jsindex 96fd2336c7..6ee4afe034 100644--- a/src/controllers/admin/categories.js+++ b/src/controllers/admin/categories.js@@ -158,7 +158,7 @@ categoriesController.getAnalytics = async function (req, res) {};categoriesController.getFederation = async function (req, res) {- const cid = req.params.category_id;+ const cid = parseInt(req.params.category_id, 10);let [_following, pending, followers, name, { selectedCategory }] = await Promise.all([db.getSortedSetMembers(`cid:${cid}:following`),db.getSortedSetMembers(`followRequests:cid.${cid}`),diff --git a/src/controllers/users.js b/src/controllers/users.jsindex 5f290bdc9a..30dde418aa 100644--- a/src/controllers/users.js+++ b/src/controllers/users.js@@ -140,7 +140,7 @@ usersController.getUsers = async function (set, uid, query) {return {users: usersData.users,pagination: pagination.create(page, pageCount, query),- userCount: usersData.count,+ userCount: parseInt(usersData.count, 10),title: setToData[set].title || '[[pages:users/latest]]',breadcrumbs: helpers.buildBreadcrumbs(breadcrumbs),isAdminOrGlobalMod: isAdmin || isGlobalMod,diff --git a/src/cron.js b/src/cron.jsindex 02f75f2aba..c3165578dc 100644--- a/src/cron.js+++ b/src/cron.js@@ -81,6 +81,7 @@ exports.getJobs = async function () {job.running = parseInt(job.running, 10) === 1;job.duration = job.duration || 0;job.durationReadable = formatDuration(job.duration);+ job.nextRun = parseInt(job.nextRun, 10);job.nextRunISO = utils.toISOString(job.nextRun);}});diff --git a/src/flags.js b/src/flags.jsindex 98949b6b5a..f6bcfa0cd1 100644--- a/src/flags.js+++ b/src/flags.js@@ -122,6 +122,11 @@ Flags.get = async function (flagId) {notes,reports,};+ ['flagId', 'targetUid', 'datetime', 'targetId'].forEach((prop) => {+ if (flagObj?.[prop]) {+ flagObj[prop] = parseInt(flagObj[prop], 10);+ }+ });const data = await plugins.hooks.fire('filter:flags.get', {flag: flagObj,@@ -210,6 +215,11 @@ Flags.list = async function (data) {...flagObj,};flagObj.labelClass = Flags._states.get(flagObj.state).class;+ ['flagId', 'targetUid', 'datetime'].forEach((prop) => {+ if (flagObj?.[prop]) {+ flagObj[prop] = parseInt(flagObj[prop], 10);+ }+ });return Object.assign(flagObj, {target_readable: `${flagObj.type.charAt(0).toUpperCase() + flagObj.type.slice(1)} ${flagObj.targetId}`,@@ -855,7 +865,7 @@ Flags.getHistory = async function (flagId) {}return {- uid: entry.value[0],+ uid: utils.isNumber(entry.value[0]) ? parseInt(entry.value[0], 10) : entry.value[0],fields: changeset,datetime: entry.score,datetimeISO: utils.toISOString(entry.score),diff --git a/src/messaging/index.js b/src/messaging/index.jsindex 0500cdf95a..009edea2c8 100644--- a/src/messaging/index.js+++ b/src/messaging/index.js@@ -351,7 +351,7 @@ Messaging.getTeasers = async (uid, roomIds) => {teaser.content = validator.escape(String(utils.stripHTMLTags(utils.decodeHTMLEntities(teaser.content))));- teaser.roomId = roomId;+ teaser.roomId = parseInt(roomId, 10);const payload = await plugins.hooks.fire('filter:messaging.getTeaser', { teaser: teaser });return payload.teaser;}));diff --git a/src/messaging/rooms.js b/src/messaging/rooms.jsindex 50a252fc0d..17ce0f8059 100644--- a/src/messaging/rooms.js+++ b/src/messaging/rooms.js@@ -22,7 +22,8 @@ const roomUidCache = cacheCreate({});const intFields = [- 'roomId', 'timestamp', 'userCount', 'messageCount', 'joinLeaveMessages',+ 'roomId', 'timestamp', 'userCount', 'messageCount',+ 'joinLeaveMessages', 'notificationSetting',];module.exports = function (Messaging) {diff --git a/src/navigation/admin.js b/src/navigation/admin.jsindex f944918371..8e3309ecd4 100644--- a/src/navigation/admin.js+++ b/src/navigation/admin.js@@ -78,6 +78,9 @@ admin.get = async function () {if (item.groups && !Array.isArray(item.groups)) {item.groups = [item.groups];}++ item.enabled = String(item.enabled) === 'true';+ item.order = parseInt(item.order, 10);return item;});admin.escapeFields(cache);diff --git a/src/posts/data.js b/src/posts/data.jsindex 32e8d5443f..1292738e39 100644--- a/src/posts/data.js+++ b/src/posts/data.js@@ -7,7 +7,7 @@ const utils = require('../utils');const intFields = ['uid', 'pid', 'tid', 'deleted', 'timestamp','upvotes', 'downvotes', 'deleterUid', 'edited',- 'replies', 'bookmarks', 'announces',+ 'replies', 'bookmarks', 'announces', 'flagId',];module.exports = function (Posts) {diff --git a/src/topics/data.js b/src/topics/data.jsindex 03c48a08d9..54b23ac1a6 100644--- a/src/topics/data.js+++ b/src/topics/data.js@@ -143,8 +143,10 @@ function modifyTopic(topic, fields) {if (hasField('thumbs')) {try {+ topic.numThumbs = topic.thumbs.length;topic.thumbs = topic.thumbs ? JSON.parse(String(topic.thumbs || '[]')) : [];} catch (e) {+ topic.numThumbs = 0;topic.thumbs = [];}}diff --git a/src/topics/events.js b/src/topics/events.jsindex 82bb7931ad..61bb1d1765 100644--- a/src/topics/events.js+++ b/src/topics/events.js@@ -140,6 +140,7 @@ Events.get = async (tid, uid, reverse = false) => {let events = await db.getObjects(keys);events.forEach((e, idx) => {+ e.id = parseInt(e.id, 10);e.timestamp = timestamps[idx];});await addEventsFromPostQueue(tid, uid, events);diff --git a/src/user/data.js b/src/user/data.jsindex bb71651c20..6e6d68cb04 100644--- a/src/user/data.js+++ b/src/user/data.js@@ -20,7 +20,7 @@ const intFields = ['uid', 'postcount', 'topiccount', 'reputation', 'profileviews','banned', 'banned:expire', 'email:confirmed', 'joindate', 'lastonline','lastqueuetime', 'lastposttime', 'followingCount', 'followerCount',- 'blocksCount', 'passwordExpiry', 'mutedUntil',+ 'blocksCount', 'passwordExpiry', 'mutedUntil', 'flags',];module.exports = function (User) {diff --git a/src/user/info.js b/src/user/info.jsindex 6b488fe41e..13f0fa3cfb 100644--- a/src/user/info.js+++ b/src/user/info.js@@ -98,7 +98,7 @@ module.exports = function (User) {const topicData = await topics.getTopicsFields(tids, ['title']);postFlags.forEach((flagObj, idx) => {- flagObj.pid = flagObj.targetId;+ flagObj.pid = parseInt(flagObj.targetId, 10);if (!tids[idx]) {flagObj.targetPurged = true;}diff --git a/src/user/settings.js b/src/user/settings.jsindex 6f82758caf..803628048c 100644--- a/src/user/settings.js+++ b/src/user/settings.js@@ -28,7 +28,7 @@ module.exports = function (User) {}let settings = await db.getObject(`user:${uid}:settings`);settings = settings || {};- settings.uid = uid;+ settings.uid = parseInt(uid, 10);return await onSettingsLoaded(uid, settings);};diff --git a/test/api.js b/test/api.jsindex 2a6e32d45b..6c456ed520 100644--- a/test/api.js+++ b/test/api.js@@ -15,6 +15,7 @@ const db = require('./mocks/databasemock');const request = require('../src/request');const helpers = require('./helpers');const meta = require('../src/meta');+const file = require('../src/file');const user = require('../src/user');const groups = require('../src/groups');const categories = require('../src/categories');@@ -29,683 +30,33 @@ const utils = require('../src/utils');const api = require('../src/api');describe('API', async () => {- let readApi = false;- let writeApi = false;- const readApiPath = path.resolve(__dirname, '../public/openapi/read.yaml');- const writeApiPath = path.resolve(__dirname, '../public/openapi/write.yaml');- let jar;- let csrfToken;- let setup = false;- const unauthenticatedRoutes = ['/api/login', '/api/register']; // Everything else will be called with the admin user-- const mocks = {- head: {},- get: {- '/api/email/unsubscribe/{token}': [- {- in: 'path',- name: 'token',- example: (() => jwt.sign({- template: 'digest',- uid: 1,- }, nconf.get('secret')))(),- },- ],- '/api/confirm/{code}': [- {- in: 'path',- name: 'code',- example: '', // to be defined later...- },- ],- '/admin/tokens/{token}': [- {- in: 'path',- name: 'token',- example: '', // to be defined later...- },- ],- },- post: {- '/admin/tokens/{token}/roll': [- {- in: 'path',- name: 'token',- example: '', // to be defined later...- },- ],- },- put: {- '/groups/{slug}/pending/{uid}': [- {- in: 'path',- name: 'slug',- example: 'private-group',- },- {- in: 'path',- name: 'uid',- example: '', // to be defined later...- },- ],- '/admin/tokens/{token}': [- {- in: 'path',- name: 'token',- example: '', // to be defined later...- },- ],- },- patch: {},- delete: {- '/users/{uid}/tokens/{token}': [- {- in: 'path',- name: 'uid',- example: 1,- },- {- in: 'path',- name: 'token',- example: utils.generateUUID(),- },- ],- '/users/{uid}/sessions/{uuid}': [- {- in: 'path',- name: 'uid',- example: 1,- },- {- in: 'path',- name: 'uuid',- example: '', // to be defined below...- },- ],- '/posts/{pid}/diffs/{timestamp}': [- {- in: 'path',- name: 'pid',- example: '', // to be defined below...- },- {- in: 'path',- name: 'timestamp',- example: '', // to be defined below...- },- ],- '/groups/{slug}/pending/{uid}': [- {- in: 'path',- name: 'slug',- example: 'private-group',- },- {- in: 'path',- name: 'uid',- example: '', // to be defined later...- },- ],- '/groups/{slug}/invites/{uid}': [- {- in: 'path',- name: 'slug',- example: 'invitations-only',- },- {- in: 'path',- name: 'uid',- example: '', // to be defined later...- },- ],- '/admin/tokens/{token}': [- {- in: 'path',- name: 'token',- example: '', // to be defined later...- },- ],- },- };-- async function dummySearchHook(data) {- return [1];- }- async function dummyEmailerHook(data) {- // pretend to handle sending emails- }-- after(async () => {- plugins.hooks.unregister('core', 'filter:search.query', dummySearchHook);- plugins.hooks.unregister('emailer-test', 'static:email.send');+ before(async function () {+ this.readApiPath = path.resolve(__dirname, '../public/openapi/read.yaml');+ this.writeApiPath = path.resolve(__dirname, '../public/openapi/write.yaml');+ this.readApi = await SwaggerParser.dereference(this.readApiPath);+ this.writeApi = await SwaggerParser.dereference(this.writeApiPath);});- async function setupData() {- if (setup) {- return;- }-- // Create sample users- const adminUid = await user.create({ username: 'admin', password: '123456', email: '[email protected]' }, { emailVerification: 'verify' });- const unprivUid = await user.create({ username: 'unpriv', password: '123456', email: '[email protected]' }, { emailVerification: 'verify' });- const emailConfirmationUid = await user.create({ username: 'emailConf', email: '[email protected]' });-- mocks.get['/api/confirm/{code}'][0].example = await db.get(`confirm:byUid:${emailConfirmationUid}`);-- for (let x = 0; x < 4; x++) {- // eslint-disable-next-line no-await-in-loop- await user.create({ username: 'deleteme', password: '123456' }); // for testing of DELETE /users (uids 5, 6) and DELETE /user/:uid/account (uid 7)- }- await groups.join('administrators', adminUid);-- // Create api token for testing read/updating/deletion- const token = await api.utils.tokens.generate({ uid: adminUid });- mocks.get['/admin/tokens/{token}'][0].example = token;- mocks.put['/admin/tokens/{token}'][0].example = token;- mocks.delete['/admin/tokens/{token}'][0].example = token;-- // Create another token for testing rolling- const token2 = await api.utils.tokens.generate({ uid: adminUid });- mocks.post['/admin/tokens/{token}/roll'][0].example = token2;-- // Create sample group- await groups.create({- name: 'Test Group',- });-- // Create private groups for pending/invitations- const [pending1, pending2, inviteUid] = await Promise.all([- await user.create({ username: utils.generateUUID().slice(0, 8) }),- await user.create({ username: utils.generateUUID().slice(0, 8) }),- await user.create({ username: utils.generateUUID().slice(0, 8) }),- ]);- mocks.put['/groups/{slug}/pending/{uid}'][1].example = pending1;- mocks.delete['/groups/{slug}/pending/{uid}'][1].example = pending2;- mocks.delete['/groups/{slug}/invites/{uid}'][1].example = inviteUid;- await Promise.all(['private-group', 'invitations-only'].map(async (name) => {- await groups.create({ name, private: true });- }));- await groups.requestMembership('private-group', pending1);- await groups.requestMembership('private-group', pending2);- await groups.invite('invitations-only', inviteUid);-- await meta.settings.set('core.api', {- tokens: [{- token: mocks.delete['/users/{uid}/tokens/{token}'][1].example,- uid: 1,- description: 'for testing of token deletion route',- timestamp: Date.now(),- }],- });- meta.config.allowTopicsThumbnail = 1;- meta.config.termsOfUse = 'I, for one, welcome our new test-driven overlords';- meta.config.chatMessageDelay = 0;- meta.config.activitypubEnabled = 1;-- // Create a category- const testCategory = await categories.create({ name: 'test' });-- // Post a new topic- await topics.post({- uid: adminUid,- cid: testCategory.cid,- title: 'Test Topic',- content: 'Test topic content',- });- const unprivTopic = await topics.post({- uid: unprivUid,- cid: testCategory.cid,- title: 'Test Topic 2',- content: 'Test topic 2 content',- });- await topics.post({- uid: unprivUid,- cid: testCategory.cid,- title: 'Test Topic 3',- content: 'Test topic 3 content',- });-- // create a notification- const notifObj = await notifications.create({- nid: '1', // match nid in example in notifications/nid/read.yaml- path: '/notifications',- from: unprivUid,- bodyShort: 'testing notification',- });- notifications.push(notifObj, adminUid);--- // Create a post diff- await posts.edit({- uid: adminUid,- pid: unprivTopic.postData.pid,- content: 'Test topic 2 edited content',- req: {},- });- mocks.delete['/posts/{pid}/diffs/{timestamp}'][0].example = unprivTopic.postData.pid;- mocks.delete['/posts/{pid}/diffs/{timestamp}'][1].example = (await posts.diffs.list(unprivTopic.postData.pid))[0];-- // Create a sample flag- const { flagId } = await flags.create('post', 1, unprivUid, 'sample reasons', Date.now()); // deleted in DELETE /api/v3/flags/1- await flags.appendNote(flagId, 1, 'test note', 1626446956652);- await flags.create('post', 2, unprivUid, 'sample reasons', Date.now()); // for testing flag notes (since flag 1 deleted)-- // Create a new chat room & send a message- const roomId = await messaging.newRoom(adminUid, { uids: [unprivUid] });- await messaging.sendMessage({- roomId,- uid: adminUid,- content: 'this is a chat message',- });-- // Create an empty file to test DELETE /files and thumb deletion- fs.closeSync(fs.openSync(path.resolve(nconf.get('upload_path'), 'files/test.txt'), 'w'));- fs.closeSync(fs.openSync(path.resolve(nconf.get('upload_path'), 'files/test.png'), 'w'));-- // Associate thumb with topic to test thumb reordering- await topics.thumbs.associate({- id: 2,- path: 'files/test.png',- });-- const socketAdmin = require('../src/socket.io/admin');- await Promise.all(['profile', 'posts', 'uploads'].map(async type => api.users.generateExport({ uid: adminUid }, { uid: adminUid, type })));- await socketAdmin.user.exportUsersCSV({ uid: adminUid }, {});- // wait for export child processes to complete- await wait(5000);-- // Attach a search hook so /api/search is enabled- plugins.hooks.register('core', {- hook: 'filter:search.query',- method: dummySearchHook,- });- // Attach an emailer hook so related requests do not error- plugins.hooks.register('emailer-test', {- hook: 'static:email.send',- method: dummyEmailerHook,- });-- // All tests run as admin user- ({ jar } = await helpers.loginUser('admin', '123456'));-- // Retrieve CSRF token using cookie, to test Write API- csrfToken = await helpers.getCsrfToken(jar);-- // Pre-seed ActivityPub cache so contrived actor assertions pass- activitypub._cache.set(`0;https://example.org/foobar`, {- id: 'https://example.org/foobar',- name: 'foobar',- publicKey: {- id: `https://example.org/foobar#key`,- owner: `https://example.org/foobar`,- publicKeyPem: 'secretcat',- },- });-- setup = true;- }-- it('should pass OpenAPI v3 validation', async () => {+ it.skip('should pass OpenAPI v3 validation', async function () {try {- await SwaggerParser.validate(readApiPath);- await SwaggerParser.validate(writeApiPath);+ await SwaggerParser.validate(this.readApiPath);+ await SwaggerParser.validate(this.writeApiPath);} catch (e) {assert.ifError(e);}});- readApi = await SwaggerParser.dereference(readApiPath);- writeApi = await SwaggerParser.dereference(writeApiPath);-- it('should grab all mounted routes and ensure a schema exists', async () => {- const webserver = require('../src/webserver');- const buildPaths = function (stack, prefix) {- const paths = stack.map((dispatch) => {- if (dispatch.route && dispatch.route.path && typeof dispatch.route.path === 'string') {- if (!prefix && !dispatch.route.path.startsWith('/api/')) {- return null;- }+ describe('API', async () => {+ let files;- if (prefix === nconf.get('relative_path')) {- prefix = '';- }-- return {- method: Object.keys(dispatch.route.methods)[0],- path: (prefix || '') + dispatch.route.path,- };- } else if (dispatch.name === 'router') {- const prefix = dispatch.regexp.toString().replace('/^', '').replace('\\/?(?=\\/|$)/i', '').replace(/\\\//g, '/');- return buildPaths(dispatch.handle.stack, prefix);- }-- // Drop any that aren't actual routes (middlewares, error handlers, etc.)- return null;- });-- return _.flatten(paths);- };-- let paths = buildPaths(webserver.app._router.stack).filter(Boolean).map((pathObj) => {- pathObj.path = pathObj.path.replace(/\/:([^\\/]+)/g, '/{$1}');- return pathObj;+ before(async () => {+ files = await file.walk(path.resolve(__dirname, './api'));});- const exclusionPrefixes = [- '/api/admin/plugins', '/api/compose', '/debug',- '/api/user/{userslug}/theme', // from persona- ];- paths = paths.filter(path => path.method !== '_all' && !exclusionPrefixes.some(prefix => path.path.startsWith(prefix)));-- // For each express path, query for existence in read and write api schemas- paths.forEach((pathObj) => {- describe(`${pathObj.method.toUpperCase()} ${pathObj.path}`, () => {- it('should be defined in schema docs', () => {- let schema = readApi;- if (pathObj.path.startsWith('/api/v3')) {- schema = writeApi;- pathObj.path = pathObj.path.replace('/api/v3', '');- }-- // Don't check non-GET routes in Read API- if (schema === readApi && pathObj.method !== 'get') {- return;- }-- const normalizedPath = pathObj.path.replace(/\/:([^\\/]+)/g, '/{$1}').replace(/\?/g, '');- assert(schema.paths.hasOwnProperty(normalizedPath), `${pathObj.path} is not defined in schema docs`);- assert(schema.paths[normalizedPath].hasOwnProperty(pathObj.method), `${pathObj.path} was found in schema docs, but ${pathObj.method.toUpperCase()} method is not defined`);- });+ it('subfolder tests', () => {+ files.forEach((filePath) => {+ require(filePath);});});});-- generateTests(readApi, Object.keys(readApi.paths));- generateTests(writeApi, Object.keys(writeApi.paths), writeApi.servers[0].url);-- function generateTests(api, paths, prefix) {- // Iterate through all documented paths, make a call to it,- // and compare the result body with what is defined in the spec- const pathLib = path; // for calling path module from inside this forEach- paths.forEach((path) => {- const context = api.paths[path];- let schema;- let result;- let url;- let method;- const headers = {};- const qs = {};-- Object.keys(context).forEach((_method) => {- // Only test GET routes in the Read API- if (api.info.title === 'NodeBB Read API' && _method !== 'get') {- return;- }-- it('should have each path parameter defined in its context', () => {- method = _method;- if (!context[method].parameters) {- return;- }-- const pathParams = (path.match(/{[\w\-_*]+}?/g) || []).map(match => match.slice(1, -1));- const schemaParams = context[method].parameters.map(param => (param.in === 'path' ? param.name : null)).filter(Boolean);- assert(pathParams.every(param => schemaParams.includes(param)), `${method.toUpperCase()} ${path} has path parameters specified but not defined`);- });-- it('should have examples when parameters are present', () => {- let { parameters } = context[method];- let testPath = path;-- if (parameters) {- // Use mock data if provided- parameters = mocks[method][path] || parameters;-- parameters.forEach((param) => {- assert(param.example !== null && param.example !== undefined, `${method.toUpperCase()} ${path} has parameters without examples`);-- switch (param.in) {- case 'path':- testPath = testPath.replace(`{${param.name}}`, param.example);- break;- case 'header':- headers[param.name] = param.example;- break;- case 'query':- qs[param.name] = param.example;- break;- }- });- }-- url = nconf.get('url') + (prefix || '') + testPath;- });-- it('should contain a valid request body (if present) with application/json or multipart/form-data type if POST/PUT/DELETE', () => {- if (['post', 'put', 'delete'].includes(method) && context[method].hasOwnProperty('requestBody')) {- const failMessage = `${method.toUpperCase()} ${path} has a malformed request body`;- assert(context[method].requestBody, failMessage);- assert(context[method].requestBody.content, failMessage);-- if (context[method].requestBody.content.hasOwnProperty('application/json')) {- assert(context[method].requestBody.content['application/json'], failMessage);- assert(context[method].requestBody.content['application/json'].schema, failMessage);- assert(context[method].requestBody.content['application/json'].schema.properties, failMessage);- } else if (context[method].requestBody.content.hasOwnProperty('multipart/form-data')) {- assert(context[method].requestBody.content['multipart/form-data'], failMessage);- assert(context[method].requestBody.content['multipart/form-data'].schema, failMessage);- assert(context[method].requestBody.content['multipart/form-data'].schema.properties, failMessage);- }- }- });-- it('should not error out when called', async function () {- this.timeout(0);- await setupData();-- if (csrfToken) {- headers['x-csrf-token'] = csrfToken;- }-- let body = {};- let type = 'json';- if (- context[method].hasOwnProperty('requestBody') &&- context[method].requestBody.required !== false &&- context[method].requestBody.content['application/json']) {- body = buildBody(context[method].requestBody.content['application/json'].schema.properties);- } else if (context[method].hasOwnProperty('requestBody') && context[method].requestBody.content['multipart/form-data']) {- type = 'form';- }-- try {- if (type === 'json') {- const searchParams = new URLSearchParams(qs);- result = await request[method](`${url}?${searchParams}`, {- jar: !unauthenticatedRoutes.includes(path) ? jar : undefined,- maxRedirect: 0,- redirect: 'manual',- headers: headers,- body: body,- timeout: 30000,- });- } else if (type === 'form') {- result = await helpers.uploadFile(url, pathLib.join(__dirname, './files/test.png'), {}, jar, csrfToken);- }- } catch (e) {- assert(!e, `${method.toUpperCase()} ${path} errored with: ${e.message}`);- }- });-- it('response status code should match one of the schema defined responses', () => {- // HACK: allow HTTP 418 I am a teapot, for now 👇- const { responses } = context[method];- assert(- responses.hasOwnProperty('418') ||- Object.keys(responses).includes(String(result.response.statusCode)),- `${method.toUpperCase()} ${path} sent back unexpected HTTP status code: ${result.response.statusCode}, body: ${JSON.stringify(result.body)} status: ${result.response.statusText}`,- );- });-- // Recursively iterate through schema properties, comparing type- it('response body should match schema definition', () => {- const http302 = context[method].responses['302'];- if (http302 && result.response.statusCode === 302) {- // Compare headers instead- const expectedHeaders = Object.keys(http302.headers).reduce((memo, name) => {- const value = http302.headers[name].schema.example;- memo[name] = value.startsWith(nconf.get('relative_path')) ? value : nconf.get('relative_path') + value;- return memo;- }, {});-- for (const header of Object.keys(expectedHeaders)) {- assert(result.response.headers[header.toLowerCase()]);- assert.strictEqual(result.response.headers[header.toLowerCase()], expectedHeaders[header]);- }- return;- }-- if (result.response.statusCode === 400 && context[method].responses['400']) {- // TODO: check 400 schema to response.body?- return;- }-- const http200 = context[method].responses['200'];- if (!http200) {- return;- }-- assert.strictEqual(result.response.statusCode, 200, `HTTP 200 expected (path: ${method} ${path}`);-- const hasJSON = http200.content && http200.content['application/json'];- if (hasJSON) {- schema = context[method].responses['200'].content['application/json'].schema;- compare(schema, result.body, method.toUpperCase(), path, 'root');- }-- // TODO someday: text/csv, binary file type checking?- });-- it('should successfully re-login if needed', async () => {- const reloginPaths = ['GET /api/user/{userslug}/edit/email', 'PUT /users/{uid}/password', 'DELETE /users/{uid}/sessions/{uuid}'];- if (reloginPaths.includes(`${method.toUpperCase()} ${path}`)) {- ({ jar } = await helpers.loginUser('admin', '123456'));- let sessionIds = await db.getSortedSetRange('uid:1:sessions', 0, -1);- let sessObj = await db.sessionStoreGet(sessionIds[0]);- if (!sessObj) {- // password changed so login with new pwd- ({ jar } = await helpers.loginUser('admin', '654321'));- sessionIds = await db.getSortedSetRange('uid:1:sessions', 0, -1);- sessObj = await db.sessionStoreGet(sessionIds[0]);- }-- const { uuid } = sessObj.meta;- mocks.delete['/users/{uid}/sessions/{uuid}'][1].example = uuid;-- // Retrieve CSRF token using cookie, to test Write API- csrfToken = await helpers.getCsrfToken(jar);- }- });- });- });- }-- function buildBody(schema) {- return Object.keys(schema).reduce((memo, cur) => {- memo[cur] = schema[cur].example;- return memo;- }, {});- }-- function compare(schema, response, method, path, context) {- let required = [];- const additionalProperties = schema.hasOwnProperty('additionalProperties');-- function flattenAllOf(obj) {- return obj.reduce((memo, obj) => {- if (obj.allOf) {- obj = { properties: flattenAllOf(obj.allOf) };- } else {- try {- required = required.concat(obj.required ? obj.required : Object.keys(obj.properties));- } catch (e) {- assert.fail(`Syntax error re: allOf, perhaps you allOf'd an array? (path: ${method} ${path}, context: ${context})`);- }- }-- return { ...memo, ...obj.properties };- }, {});- }-- if (schema.allOf) {- schema = flattenAllOf(schema.allOf);- } else if (schema.properties) {- required = schema.required || Object.keys(schema.properties);- schema = schema.properties;- } else {- // If schema contains no properties, check passes- return;- }-- // Compare the schema to the response- required.forEach((prop) => {- if (schema.hasOwnProperty(prop)) {- assert(response.hasOwnProperty(prop), `"${prop}" is a required property (path: ${method} ${path}, context: ${context})`);-- // Don't proceed with type-check if the value could possibly be unset (nullable: true, in spec)- if (response[prop] === null && schema[prop].nullable === true) {- return;- }-- // Therefore, if the value is actually null, that's a problem (nullable is probably missing)- assert(response[prop] !== null, `"${prop}" was null, but schema does not specify it to be a nullable property (path: ${method} ${path}, context: ${context})`);-- switch (schema[prop].type) {- case 'string':- assert.strictEqual(typeof response[prop], 'string', `"${prop}" was expected to be a string, but was ${typeof response[prop]} instead (path: ${method} ${path}, context: ${context})`);- break;- case 'boolean':- assert.strictEqual(typeof response[prop], 'boolean', `"${prop}" was expected to be a boolean, but was ${typeof response[prop]} instead (path: ${method} ${path}, context: ${context})`);- break;- case 'object': {- let valid = ['object'];- if (schema[prop].additionalProperties && schema[prop].additionalProperties.oneOf) {- valid = schema[prop].additionalProperties.oneOf.map(({ type }) => type);- }- assert(valid.includes(typeof response[prop]), `"${prop}" was expected to be an object, but was ${typeof response[prop]} instead (path: ${method} ${path}, context: ${context})`);- compare(schema[prop], response[prop], method, path, context ? [context, prop].join('.') : prop);- break;- }- case 'array':- assert.strictEqual(Array.isArray(response[prop]), true, `"${prop}" was expected to be an array, but was ${typeof response[prop]} instead (path: ${method} ${path}, context: ${context})`);-- if (schema[prop].items) {- // Ensure the array items have a schema defined- assert(schema[prop].items.type || schema[prop].items.allOf || schema[prop].items.anyOf || schema[prop].items.oneOf, `"${prop}" is defined to be an array, but its items have no schema defined (path: ${method} ${path}, context: ${context})`);-- // Compare types- if (schema[prop].items.type === 'object' || Array.isArray(schema[prop].items.allOf || schema[prop].items.anyOf || schema[prop].items.oneOf)) {- response[prop].forEach((res) => {- compare(schema[prop].items, res, method, path, context ? [context, prop].join('.') : prop);- });- } else if (response[prop].length) { // for now- response[prop].forEach((item) => {- assert.strictEqual(typeof item, schema[prop].items.type, `"${prop}" should have ${schema[prop].items.type} items, but found ${typeof items} instead (path: ${method} ${path}, context: ${context})`);- });- }- }- break;- }- }- });-- // Compare the response to the schema- Object.keys(response).forEach((prop) => {- if (additionalProperties) { // All bets are off- return;- }-- assert(schema[prop], `"${prop}" was found in response, but is not defined in schema (path: ${method} ${path}, context: ${context})`);- });- }});diff --git a/test/api/routes.js b/test/api/routes.jsnew file mode 100644index 0000000000..b03f66c6bd--- /dev/null+++ b/test/api/routes.js@@ -0,0 +1,84 @@+'use strict';++const assert = require('assert');+const path = require('path');+const nconf = require('nconf');+const _ = require('lodash');+const SwaggerParser = require('@apidevtools/swagger-parser');++const db = require('../mocks/databasemock');++let readApi;+let writeApi;++describe('routes', function () {+ before(async function () {+ const readApiPath = path.resolve(__dirname, '../../public/openapi/read.yaml');+ const writeApiPath = path.resolve(__dirname, '../../public/openapi/write.yaml');+ readApi = await SwaggerParser.dereference(readApiPath);+ writeApi = await SwaggerParser.dereference(writeApiPath);+ });++ it('should grab all mounted routes and ensure a schema exists', async function () {+ const webserver = require('../../src/webserver');+ const buildPaths = function (stack, prefix) {+ const paths = stack.map((dispatch) => {+ if (dispatch.route && dispatch.route.path && typeof dispatch.route.path === 'string') {+ if (!prefix && !dispatch.route.path.startsWith('/api/')) {+ return null;+ }++ if (prefix === nconf.get('relative_path')) {+ prefix = '';+ }++ return {+ method: Object.keys(dispatch.route.methods)[0],+ path: (prefix || '') + dispatch.route.path,+ };+ } else if (dispatch.name === 'router') {+ const prefix = dispatch.regexp.toString().replace('/^', '').replace('\\/?(?=\\/|$)/i', '').replace(/\\\//g, '/');+ return buildPaths(dispatch.handle.stack, prefix);+ }++ // Drop any that aren't actual routes (middlewares, error handlers, etc.)+ return null;+ });++ return _.flatten(paths);+ };++ let paths = buildPaths(webserver.app._router.stack).filter(Boolean).map((pathObj) => {+ pathObj.path = pathObj.path.replace(/\/:([^\\/]+)/g, '/{$1}');+ return pathObj;+ });+ const exclusionPrefixes = [+ '/api/admin/plugins', '/api/compose', '/debug',+ '/api/user/{userslug}/theme', // from persona+ ];+ paths = paths.filter(path => path.method !== '_all' && !exclusionPrefixes.some(prefix => path.path.startsWith(prefix)));+++ // For each express path, query for existence in read and write api schemas+ paths.forEach((pathObj) => {+ describe(`${pathObj.method.toUpperCase()} ${pathObj.path}`, function () {+ it('should be defined in schema docs', function () {+ let schema = readApi;+ if (pathObj.path.startsWith('/api/v3')) {+ schema = writeApi;+ pathObj.path = pathObj.path.replace('/api/v3', '');+ }++ // Don't check non-GET routes in Read API+ if (schema === readApi && pathObj.method !== 'get') {+ return;+ }++ const normalizedPath = pathObj.path.replace(/\/:([^\\/]+)/g, '/{$1}').replace(/\?/g, '');+ assert(schema.paths.hasOwnProperty(normalizedPath), `${pathObj.path} is not defined in schema docs`);+ assert(schema.paths[normalizedPath].hasOwnProperty(pathObj.method), `${pathObj.path} was found in schema docs, but ${pathObj.method.toUpperCase()} method is not defined`);+ });+ });+ });+ });+});\ No newline at end of filediff --git a/test/api/schema.js b/test/api/schema.jsnew file mode 100644index 0000000000..857303db22--- /dev/null+++ b/test/api/schema.js@@ -0,0 +1,638 @@+/* eslint-disable no-await-in-loop */+'use strict';++const assert = require('assert');+const path = require('path');+const nconf = require('nconf');+const fs = require('fs');+const _ = require('lodash');+const SwaggerParser = require('@apidevtools/swagger-parser');+const jwt = require('jsonwebtoken');+const util = require('util');+const Ajv = require('ajv');++const db = require('../mocks/databasemock');+const request = require('../../src/request');+const utils = require('../../src/utils');+const user = require('../../src/user');+const groups = require('../../src/groups');+const meta = require('../../src/meta');+const categories = require('../../src/categories');+const topics = require('../../src/topics');+const posts = require('../../src/posts');+const notifications = require('../../src/notifications');+const flags = require('../../src/flags');+const messaging = require('../../src/messaging');+const plugins = require('../../src/plugins');+const api = require('../../src/api');+const activitypub = require('../../src/activitypub');+const helpers = require('../helpers');++const ajv = new Ajv({ allErrors: true, strict: false });+const { baseDir } = require('../../src/constants').paths;+const wait = util.promisify(setTimeout);+let readApi;+let writeApi;+let jar;+let csrfToken;+const unauthenticatedRoutes = ['/api/login', '/api/register']; // Everything else will be called with the admin user++async function dummySearchHook(data) {+ return [1];+}+async function dummyEmailerHook(data) {+ // pretend to handle sending emails+}+const mocks = {+ head: {},+ get: {+ '/api/email/unsubscribe/{token}': [+ {+ in: 'path',+ name: 'token',+ example: (() => jwt.sign({+ template: 'digest',+ uid: 1,+ }, nconf.get('secret')))(),+ },+ ],+ '/api/confirm/{code}': [+ {+ in: 'path',+ name: 'code',+ example: '', // to be defined later...+ },+ ],+ '/admin/tokens/{token}': [+ {+ in: 'path',+ name: 'token',+ example: '', // to be defined later...+ },+ ],+ },+ post: {+ '/admin/tokens/{token}/roll': [+ {+ in: 'path',+ name: 'token',+ example: '', // to be defined later...+ },+ ],+ },+ put: {+ '/groups/{slug}/pending/{uid}': [+ {+ in: 'path',+ name: 'slug',+ example: 'private-group',+ },+ {+ in: 'path',+ name: 'uid',+ example: '', // to be defined later...+ },+ ],+ '/admin/tokens/{token}': [+ {+ in: 'path',+ name: 'token',+ example: '', // to be defined later...+ },+ ],+ },+ patch: {},+ delete: {+ '/users/{uid}/tokens/{token}': [+ {+ in: 'path',+ name: 'uid',+ example: 1,+ },+ {+ in: 'path',+ name: 'token',+ example: utils.generateUUID(),+ },+ ],+ '/users/{uid}/sessions/{uuid}': [+ {+ in: 'path',+ name: 'uid',+ example: 1,+ },+ {+ in: 'path',+ name: 'uuid',+ example: '', // to be defined below...+ },+ ],+ '/posts/{pid}/diffs/{timestamp}': [+ {+ in: 'path',+ name: 'pid',+ example: '', // to be defined below...+ },+ {+ in: 'path',+ name: 'timestamp',+ example: '', // to be defined below...+ },+ ],+ '/groups/{slug}/pending/{uid}': [+ {+ in: 'path',+ name: 'slug',+ example: 'private-group',+ },+ {+ in: 'path',+ name: 'uid',+ example: '', // to be defined later...+ },+ ],+ '/groups/{slug}/invites/{uid}': [+ {+ in: 'path',+ name: 'slug',+ example: 'invitations-only',+ },+ {+ in: 'path',+ name: 'uid',+ example: '', // to be defined later...+ },+ ],+ '/admin/tokens/{token}': [+ {+ in: 'path',+ name: 'token',+ example: '', // to be defined later...+ },+ ],+ },+};++async function setupData() {+ // Create sample users+ const adminUid = await user.create({ username: 'admin', password: '123456', email: '[email protected]' }, { emailVerification: 'verify' });+ const unprivUid = await user.create({ username: 'unpriv', password: '123456', email: '[email protected]' }, { emailVerification: 'verify' });+ const emailConfirmationUid = await user.create({ username: 'emailConf', email: '[email protected]' });++ mocks.get['/api/confirm/{code}'][0].example = await db.get(`confirm:byUid:${emailConfirmationUid}`);++ for (let x = 0; x < 4; x++) {+ await user.create({ username: 'deleteme', password: '123456' }); // for testing of DELETE /users (uids 5, 6) and DELETE /user/:uid/account (uid 7)+ }+ await groups.join('administrators', adminUid);++ // Create api token for testing read/updating/deletion+ const token = await api.utils.tokens.generate({ uid: adminUid });+ mocks.get['/admin/tokens/{token}'][0].example = token;+ mocks.put['/admin/tokens/{token}'][0].example = token;+ mocks.delete['/admin/tokens/{token}'][0].example = token;++ // Create another token for testing rolling+ const token2 = await api.utils.tokens.generate({ uid: adminUid });+ mocks.post['/admin/tokens/{token}/roll'][0].example = token2;++ // Create sample group+ await groups.create({+ name: 'Test Group',+ });++ // Create private groups for pending/invitations+ const [pending1, pending2, inviteUid] = await Promise.all([+ user.create({ username: utils.generateUUID().slice(0, 8) }),+ user.create({ username: utils.generateUUID().slice(0, 8) }),+ user.create({ username: utils.generateUUID().slice(0, 8) }),+ ]);+ mocks.put['/groups/{slug}/pending/{uid}'][1].example = pending1;+ mocks.delete['/groups/{slug}/pending/{uid}'][1].example = pending2;+ mocks.delete['/groups/{slug}/invites/{uid}'][1].example = inviteUid;+ await Promise.all(['private-group', 'invitations-only'].map(async (name) => groups.create({ name, private: true })));+ await groups.requestMembership('private-group', pending1);+ await groups.requestMembership('private-group', pending2);+ await groups.invite('invitations-only', inviteUid);++ await meta.settings.set('core.api', {+ tokens: [{+ token: mocks.delete['/users/{uid}/tokens/{token}'][1].example,+ uid: 1,+ description: 'for testing of token deletion route',+ timestamp: Date.now(),+ }],+ });+ meta.config.allowTopicsThumbnail = 1;+ meta.config.termsOfUse = 'I, for one, welcome our new test-driven overlords';+ meta.config.chatMessageDelay = 0;+ meta.config.activitypubEnabled = 1;++ // Create a category+ const testCategory = await categories.create({ name: 'test' });++ // Post a new topic+ await topics.post({+ uid: adminUid,+ cid: testCategory.cid,+ title: 'Test Topic',+ content: 'Test topic content',+ });+ const unprivTopic = await topics.post({+ uid: unprivUid,+ cid: testCategory.cid,+ title: 'Test Topic 2',+ content: 'Test topic 2 content',+ });+ await topics.post({+ uid: unprivUid,+ cid: testCategory.cid,+ title: 'Test Topic 3',+ content: 'Test topic 3 content',+ });++ // create a notification+ const notifObj = await notifications.create({+ nid: '1', // match nid in example in notifications/nid/read.yaml+ path: '/notifications',+ from: unprivUid,+ bodyShort: 'testing notification',+ });+ notifications.push(notifObj, adminUid);+++ // Create a post diff+ await posts.edit({+ uid: adminUid,+ pid: unprivTopic.postData.pid,+ content: 'Test topic 2 edited content',+ req: {},+ });+ mocks.delete['/posts/{pid}/diffs/{timestamp}'][0].example = unprivTopic.postData.pid;+ mocks.delete['/posts/{pid}/diffs/{timestamp}'][1].example = (await posts.diffs.list(unprivTopic.postData.pid))[0];++ // Create a sample flag+ const { flagId } = await flags.create('post', 1, unprivUid, 'sample reasons', Date.now()); // deleted in DELETE /api/v3/flags/1+ await flags.appendNote(flagId, 1, 'test note', 1626446956652);+ await flags.create('post', 2, unprivUid, 'sample reasons', Date.now()); // for testing flag notes (since flag 1 deleted)++ // Create a new chat room & send a message+ const roomId = await messaging.newRoom(adminUid, { uids: [unprivUid] });+ await messaging.sendMessage({+ roomId,+ uid: adminUid,+ content: 'this is a chat message',+ });++ // Create an empty file to test DELETE /files and thumb deletion+ fs.closeSync(fs.openSync(path.resolve(nconf.get('upload_path'), 'files/test.txt'), 'w'));+ fs.copyFileSync(path.resolve(__dirname, '../../test/files/test.png'), path.resolve(nconf.get('upload_path'), 'files/test.png'));++ // Associate thumb with topic to test thumb reordering+ await topics.thumbs.associate({+ id: 2,+ path: 'files/test.png',+ });++ const socketAdmin = require('../../src/socket.io/admin');+ await Promise.all(['profile', 'posts', 'uploads'].map(async type => api.users.generateExport({ uid: adminUid }, { uid: adminUid, type })));+ await socketAdmin.user.exportUsersCSV({ uid: adminUid }, {});++ // wait for export child processes to complete+ const uploadPath = nconf.get('upload_path');+ const checkFiles = async (retries = 50) => {+ process.stdout.write('checkfiles called');+ const getFileStats = async () => {+ const paths = [+ path.resolve(baseDir, 'build/export/users.csv'),+ path.resolve(baseDir, `build/export/${adminUid}_profile.json`),+ path.resolve(baseDir, `build/export/${adminUid}_posts.csv`),+ path.resolve(baseDir, `build/export/${adminUid}_uploads.zip`),+ ];++ const results = await Promise.all(paths.map(async (p) => {+ try {+ const stats = await fs.promises.stat(p);+ return { exists: true, size: stats.size };+ } catch (e) {+ return { exists: false, size: 0 };+ }+ }));++ return results;+ };++ for (let i = 0; i < retries; i++) {+ const firstCheck = await getFileStats();+ if (firstCheck.every((f) => f.exists)) {+ await wait(500); // Wait a bit to see if size changes+ const secondCheck = await getFileStats();+ if (secondCheck.every((f, idx) => f.size === firstCheck[idx].size)) {+ return;+ }+ }+ await wait(100);+ }+ throw new Error('Export files were not created or finished writing in time');+ };+ await checkFiles();++ // Attach a search hook so /api/search is enabled+ plugins.hooks.register('core', {+ hook: 'filter:search.query',+ method: dummySearchHook,+ });+ // Attach an emailer hook so related requests do not error+ plugins.hooks.register('emailer-test', {+ hook: 'static:email.send',+ method: dummyEmailerHook,+ });++ // All tests run as admin user+ ({ jar } = await helpers.loginUser('admin', '123456'));++ // Retrieve CSRF token using cookie, to test Write API+ csrfToken = await helpers.getCsrfToken(jar);++ // Pre-seed ActivityPub cache so contrived actor assertions pass+ activitypub._cache.set(`0;https://example.org/foobar`, {+ id: 'https://example.org/foobar',+ name: 'foobar',+ publicKey: {+ id: `https://example.org/foobar#key`,+ owner: `https://example.org/foobar`,+ publicKeyPem: 'secretcat',+ },+ });+}++describe('schema', () => {+ before(async function () {+ const readApiPath = path.resolve(__dirname, '../../public/openapi/read.yaml');+ const writeApiPath = path.resolve(__dirname, '../../public/openapi/write.yaml');+ this.readApi = await SwaggerParser.dereference(readApiPath);+ this.writeApi = await SwaggerParser.dereference(writeApiPath);++ await db.setupMockDefaults();+ await setupData();+ });++ after(async () => {+ plugins.hooks.unregister('core', 'filter:search.query', dummySearchHook);+ plugins.hooks.unregister('emailer-test', 'static:email.send');+ });++ it('read api', async function () {+ // Iterate through all documented paths, make a call to it,+ // and compare the result body with what is defined in the spec+ this.timeout(0);+ const paths = Object.keys(this.readApi.paths);+ const pathLib = path; // for calling path module from inside this forEach+ for(const p of paths) {+ await executeTests(p, this.readApi, paths, pathLib);+ }+ });++ it('write api', async function () {+ // Iterate through all documented paths, make a call to it,+ // and compare the result body with what is defined in the spec+ this.timeout(0);+ const paths = Object.keys(this.writeApi.paths);+ const pathLib = path; // for calling path module from inside this forEach+ for(const p of paths) {+ await executeTests(p, this.writeApi, paths, pathLib, this.writeApi.servers[0].url);+ };+ });++ async function executeTests(path, api, paths, pathLib, prefix) {+ const context = api.paths[path];+ let schema;+ let result;+ let url;+ const headers = {};+ const qs = {};++ await Object.keys(context).reduce(async (promise, _method) => {+ await promise;+ const method = _method;++ // Only test GET routes in the Read API+ if (api.info.title === 'NodeBB Read API' && _method !== 'get') {+ return;+ }++ // should have each path parameter defined in its context+ checkPathParameters(method, path, context);++ // should have examples when parameters are present+ prepareRequest(method, path, context);++ // should contain a valid request body (if present) with application/json or+ // multipart/form-data type if POST/PUT/DELETE+ validateRequestBody(method, path, context);++ // should not error out when called+ await executeRequest(method, path, context);++ // response status code should match one of the schema defined responses+ checkResponseStatusCode(method, path, context, result);++ // response body should match schema definition+ checkResponseBody(method, path, context, result);++ // should successfully re-login if needed+ await handleRelogin(method, path, context);+ }, Promise.resolve());++ function checkPathParameters(method, path, context) {+ if (context[method].parameters) {+ const pathParams = (path.match(/{[\w\-_*]+}?/g) || []).map(match => match.slice(1, -1));+ const schemaParams = context[method].parameters.map(param => (param.in === 'path' ? param.name : null)).filter(Boolean);+ assert(pathParams.every(param => schemaParams.includes(param)), `${method.toUpperCase()} ${path} has path parameters specified but not defined`);+ process.stdout.write('.');+ }+ }++ function prepareRequest(method, path, context) {+ let { parameters } = context[method];+ let testPath = path;++ if (parameters) {+ // Use mock data if provided+ parameters = mocks[method][path] || parameters;++ parameters.forEach((param) => {+ assert(param.example !== null && param.example !== undefined, `${method.toUpperCase()} ${path} has parameters without examples`);++ switch (param.in) {+ case 'path':+ testPath = testPath.replace(`{${param.name}}`, param.example);+ break;+ case 'header':+ headers[param.name] = param.example;+ break;+ case 'query':+ qs[param.name] = param.example;+ break;+ }+ });+ }++ url = nconf.get('url') + (prefix || '') + testPath;+ process.stdout.write('.');+ }++ function validateRequestBody(method, path, context) {+ if (['post', 'put', 'delete'].includes(method) && context[method].hasOwnProperty('requestBody')) {+ const failMessage = `${method.toUpperCase()} ${path} has a malformed request body`;+ assert(context[method].requestBody, failMessage);+ assert(context[method].requestBody.content, failMessage);++ if (context[method].requestBody.content.hasOwnProperty('application/json')) {+ assert(context[method].requestBody.content['application/json'], failMessage);+ assert(context[method].requestBody.content['application/json'].schema, failMessage);+ assert(context[method].requestBody.content['application/json'].schema.properties, failMessage);+ } else if (context[method].requestBody.content.hasOwnProperty('multipart/form-data')) {+ assert(context[method].requestBody.content['multipart/form-data'], failMessage);+ assert(context[method].requestBody.content['multipart/form-data'].schema, failMessage);+ assert(context[method].requestBody.content['multipart/form-data'].schema.properties, failMessage);+ }+ }+ process.stdout.write('.');+ }++ async function executeRequest(method, path, context) {+ if (csrfToken) {+ headers['x-csrf-token'] = csrfToken;+ }++ let body = {};+ let type = 'json';+ if (+ context[method].hasOwnProperty('requestBody') &&+ context[method].requestBody.required !== false &&+ context[method].requestBody.content['application/json']) {+ body = buildBody(context[method].requestBody.content['application/json'].schema.properties);+ } else if (context[method].hasOwnProperty('requestBody') && context[method].requestBody.content['multipart/form-data']) {+ type = 'form';+ }++ try {+ if (type === 'json') {+ const searchParams = new URLSearchParams(qs);+ result = await request[method](`${url}?${searchParams}`, {+ jar: !unauthenticatedRoutes.includes(path) ? jar : undefined,+ maxRedirect: 0,+ redirect: 'manual',+ headers: headers,+ body: body,+ timeout: 30000,+ });+ } else if (type === 'form') {+ result = await helpers.uploadFile(url, pathLib.join(__dirname, '../files/test.png'), {}, jar, csrfToken);+ }+ } catch (e) {+ assert(!e, `${method.toUpperCase()} ${path} errored with: ${e.message}`);+ }+ process.stdout.write('.');+ }++ function checkResponseStatusCode(method, path, context, result) {+ // HACK: allow HTTP 418 I am a teapot, for now 👇+ const { responses } = context[method];+ assert(+ responses.hasOwnProperty('418') ||+ Object.keys(responses).includes(String(result.response.statusCode)),+ `${method.toUpperCase()} ${path} sent back unexpected HTTP status code: ${result.response.statusCode}, body: ${JSON.stringify(result.body)} status: ${result.response.statusText}`,+ );+ process.stdout.write('.');+ }++ function checkResponseBody(method, path, context, result) {+ // Recursively iterate through schema properties, comparing type+ const http302 = context[method].responses['302'];+ if (http302 && result.response.statusCode === 302) {+ // Compare headers instead+ const expectedHeaders = Object.keys(http302.headers).reduce((memo, name) => {+ const value = http302.headers[name].schema.example;+ memo[name] = value.startsWith(nconf.get('relative_path')) ? value : nconf.get('relative_path') + value;+ return memo;+ }, {});++ for (const header of Object.keys(expectedHeaders)) {+ assert(result.response.headers[header.toLowerCase()]);+ assert.strictEqual(result.response.headers[header.toLowerCase()], expectedHeaders[header]);+ }+ return;+ }++ if (result.response.statusCode === 400 && context[method].responses['400']) {+ // TODO: check 400 schema to response.body?+ return;+ }++ const http200 = context[method].responses['200'];+ if (!http200) {+ return;+ }++ assert.strictEqual(result.response.statusCode, 200, `HTTP 200 expected (path: ${method} ${path}`);++ const hasJSON = http200.content && http200.content['application/json'];+ if (hasJSON) {+ schema = context[method].responses['200'].content['application/json'].schema;+ validateSchema(schema, result.body, method.toUpperCase(), path);+ }++ // TODO someday: text/csv, binary file type checking?+ process.stdout.write('.');+ }++ async function handleRelogin(method, path, context) {+ const reloginPaths = ['GET /api/user/{userslug}/edit/email', 'PUT /users/{uid}/password', 'DELETE /users/{uid}/sessions/{uuid}'];+ if (reloginPaths.includes(`${method.toUpperCase()} ${path}`)) {+ ({ jar } = await helpers.loginUser('admin', '123456'));+ let sessionIds = await db.getSortedSetRange('uid:1:sessions', 0, -1);+ let sessObj = await db.sessionStoreGet(sessionIds[0]);+ if (!sessObj) {+ // password changed so login with new pwd+ ({ jar } = await helpers.loginUser('admin', '654321'));+ sessionIds = await db.getSortedSetRange('uid:1:sessions', 0, -1);+ sessObj = await db.sessionStoreGet(sessionIds[0]);+ }++ const { uuid } = sessObj.meta;+ mocks.delete['/users/{uid}/sessions/{uuid}'][1].example = uuid;++ // Retrieve CSRF token using cookie, to test Write API+ csrfToken = await helpers.getCsrfToken(jar);+ }+ process.stdout.write('.');+ }+ }++ function buildBody(schema) {+ return Object.keys(schema).reduce((memo, cur) => {+ memo[cur] = schema[cur].example;+ return memo;+ }, {});+ }++ function validateSchema(schema, data, method, path) {+ let validate;+ try {+ validate = ajv.compile(schema);+ } catch (err) {+ assert.fail(`Schema is invalid (path: ${method} ${path}): ${err.message}`);+ }++ if (!validate(data)) {+ const errorMessages = validate.errors.map(err => {+ const instancePath = err.instancePath || 'root';+ return `"${instancePath}" ${err.message} (path: ${method} ${path})`;+ }).join('\n');+ console.log(path, JSON.stringify(data, null, 2));+ assert.fail(`Schema validation failed (path: ${method} ${path}):\n${errorMessages}`);+ }+ }+});\ No newline at end of filediff --git a/test/controllers.js b/test/controllers.jsindex 8517944c1f..39c3646522 100644--- a/test/controllers.js+++ b/test/controllers.js@@ -1428,9 +1428,8 @@ describe('Controllers', () => {describe('handle errors', () => {const plugins = require('../src/plugins');- after((done) => {- plugins.loadedHooks['filter:router.page'] = undefined;- done();+ after(() => {+ delete plugins.loadedHooks['response:router.page'];});it('should handle topic malformed uri', async () => {diff --git a/test/topics/thumbs.js b/test/topics/thumbs.jsindex 657a2e7e60..bc452a4ac3 100644--- a/test/topics/thumbs.js+++ b/test/topics/thumbs.js@@ -173,75 +173,113 @@ describe('Topic thumbs', () => {});describe(`.delete()`, () => {- it('should remove a file from sorted set', async () => {+ let tid;+ let mainPid;++ before(async () => {+ topicObj = await topics.post({+ uid: adminUid,+ cid: categoryObj.cid,+ title: 'Test Topic Title',+ content: 'The content of test topic',+ });+ tid = topicObj.topicData.tid;+ mainPid = topicObj.postData.pid;+await topics.thumbs.associate({- id: 1,- path: `/files/test.png`,+ id: tid,+ path: relativeThumbPaths[0],});- await topics.thumbs.delete(1, `/files/test.png`);- const thumbs = await topics.getTopicField(1, 'thumbs');- assert.strictEqual(thumbs.includes(`/files/test.png`), false);+ });++ it('should remove a file from sorted set', async () => {+ await topics.thumbs.delete(tid, relativeThumbPaths[0]);+ const thumbs = await topics.getTopicField(tid, 'thumbs');+ assert.strictEqual(thumbs.includes(relativeThumbPaths[0]), false);});it('should no longer be associated with that topic\'s main pid\'s uploads', async () => {- const mainPid = (await topics.getMainPids([1]))[0];const uploads = await posts.uploads.list(mainPid);assert(!uploads.includes(path.basename(relativeThumbPaths[0])));});it('should have no more thumbs left', async () => {- const thumbs = await topics.getTopicField(1, 'thumbs');+ const thumbs = await topics.getTopicField(tid, 'thumbs');assert.strictEqual(thumbs.length, 0);});it('should decrement numThumbs if dissociated one by one', async () => {- await topics.thumbs.associate({ id: 1, path: `${nconf.get('relative_path')}${nconf.get('upload_url')}/files/test.png` });- await topics.thumbs.associate({ id: 1, path: `${nconf.get('relative_path')}${nconf.get('upload_url')}/files/test2.png` });+ const winston = require('winston');+ await topics.thumbs.associate({ id: tid, path: relativeThumbPaths[0] });+ await topics.thumbs.associate({ id: tid, path: relativeThumbPaths[1] });- await topics.thumbs.delete(1, [relativeThumbPaths[0]]);- let numThumbs = parseInt(await db.getObjectField('topic:1', 'numThumbs'), 10);+ await topics.thumbs.delete(tid, [relativeThumbPaths[0]]);+ let numThumbs = parseInt(await db.getObjectField(`topic:${tid}`, 'numThumbs'), 10);assert.strictEqual(numThumbs, 1);- await topics.thumbs.delete(1, [relativeThumbPaths[1]]);- numThumbs = parseInt(await db.getObjectField('topic:1', 'numThumbs'), 10);+ await topics.thumbs.delete(tid, [relativeThumbPaths[1]]);+ numThumbs = parseInt(await db.getObjectField(`topic:${tid}`, 'numThumbs'), 10);+assert.strictEqual(numThumbs, 0);});});describe('.deleteAll()', () => {- before(async () => {- await topics.thumbs.associate({ id: 1, path: '/files/test.png' });- await topics.thumbs.associate({ id: 1, path: '/files/test2.png' });+ before(async function () {+ topicObj = await topics.post({+ uid: adminUid,+ cid: categoryObj.cid,+ title: 'Test Topic Title',+ content: 'The content of test topic',+ });+ this.tid = topicObj.topicData.tid;+ await topics.thumbs.associate({ id: this.tid, path: '/files/test.png' });+ await topics.thumbs.associate({ id: this.tid, path: '/files/test2.png' });createFiles();});- it('should have thumbs prior to tests', async () => {- const thumbs = await topics.getTopicField(1, 'thumbs');+ it('should have thumbs prior to tests', async function () {+ const thumbs = await topics.getTopicField(this.tid, 'thumbs');assert.deepStrictEqual(thumbs, ['/files/test.png', '/files/test2.png']);});- it('should not error out', async () => {- await topics.thumbs.deleteAll(1);+ it('should not error out', async function () {+ await topics.thumbs.deleteAll(this.tid);});- it('should remove all associated thumbs with that topic', async () => {- const thumbs = await topics.getTopicField(1, 'thumbs');+ it('should remove all associated thumbs with that topic', async function () {+ const thumbs = await topics.getTopicField(this.tid, 'thumbs');assert.deepStrictEqual(thumbs, []);});});describe('HTTP calls to topic thumb routes', () => {- before(() => {+ before(async function () {+ const uid = await user.create({ username: 'thumbtest', password: '123456' });+ const login = await helpers.loginUser('thumbtest', '123456');++ this.jar = login.jar;+ this.csrf = login.csrf_token;++ topicObj = await topics.post({+ uid,+ cid: categoryObj.cid,+ title: 'Test Topic Title',+ content: 'The content of test topic',+ });+ this.tid = topicObj.topicData.tid;createFiles();});- it('should succeed with a valid tid', async () => {- const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/1/thumbs`, path.join(__dirname, '../files/test.png'), {}, adminJar, adminCSRF);+ it('should succeed with a valid tid', async function () {+ const winston = require('winston');++ const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${this.tid}/thumbs`, path.join(__dirname, '../files/test.png'), {}, this.jar, this.csrf);assert.strictEqual(response.statusCode, 200);assert.deepStrictEqual(Object.keys(body.response.images[0]), ['url', 'name']);});- it('should succeed with uploader plugins', async () => {+ it('should succeed with uploader plugins', async function () {const hookMethod = async () => ({name: 'test.png',url: 'https://example.org',@@ -252,24 +290,24 @@ describe('Topic thumbs', () => {});const { response } = await helpers.uploadFile(- `${nconf.get('url')}/api/v3/topics/1/thumbs`,+ `${nconf.get('url')}/api/v3/topics/${this.tid}/thumbs`,path.join(__dirname, '../files/test.png'),{},- adminJar,- adminCSRF+ this.jar,+ this.csrf);assert.strictEqual(response.statusCode, 200);await plugins.hooks.unregister('test', 'filter:uploadFile', hookMethod);});- it('should fail with a non-existant tid', async () => {- const { response } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${Number.MAX_SAFE_INTEGER}/thumbs`, path.join(__dirname, '../files/test.png'), {}, adminJar, adminCSRF);+ it('should fail with a non-existant tid', async function () {+ const { response } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${Number.MAX_SAFE_INTEGER}/thumbs`, path.join(__dirname, '../files/test.png'), {}, this.jar, this.csrf);assert.strictEqual(response.statusCode, 404);});- it('should fail when garbage is passed in', async () => {- const { response } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/abracadabra/thumbs`, path.join(__dirname, '../files/test.png'), {}, adminJar, adminCSRF);+ it('should fail when garbage is passed in', async function () {+ const { response } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/abracadabra/thumbs`, path.join(__dirname, '../files/test.png'), {}, this.jar, this.csrf);assert.strictEqual(response.statusCode, 404);});@@ -278,19 +316,19 @@ describe('Topic thumbs', () => {assert.strictEqual(response.statusCode, 403);});- it('should fail if thumbnails are not enabled', async () => {+ it('should fail if thumbnails are not enabled', async function () {meta.config.allowTopicsThumbnail = 0;- const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/1/thumbs`, path.join(__dirname, '../files/test.png'), {}, adminJar, adminCSRF);+ const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${this.tid}/thumbs`, path.join(__dirname, '../files/test.png'), {}, this.jar, this.csrf);assert.strictEqual(response.statusCode, 503);assert(body && body.status);assert.strictEqual(body.status.message, 'Topic thumbnails are disabled.');});- it('should fail if file is not image', async () => {+ it('should fail if file is not image', async function () {meta.config.allowTopicsThumbnail = 1;- const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/1/thumbs`, path.join(__dirname, '../files/503.html'), {}, adminJar, adminCSRF);+ const { response, body } = await helpers.uploadFile(`${nconf.get('url')}/api/v3/topics/${this.tid}/thumbs`, path.join(__dirname, '../files/503.html'), {}, this.jar, this.csrf);assert.strictEqual(response.statusCode, 500);assert(body && body.status);assert.strictEqual(body.status.message, 'Invalid File');diff --git a/test/user/emails.js b/test/user/emails.jsindex 19a385d062..ef7572e9a6 100644--- a/test/user/emails.js+++ b/test/user/emails.js@@ -140,7 +140,7 @@ describe('email confirmation (v3 api)', () => {let userObj;let jar;- before(async () => {+ before(async function () {await helpers.registerUser({username: 'fake-user',password: 'derpioansdosa',@@ -148,16 +148,28 @@ describe('email confirmation (v3 api)', () => {gdpr_consent: true,});+ // Attach an emailer hook so related requests do not error+ plugins.hooks.register('emailer-test', {+ hook: 'static:email.send',+ method: async () => {},+ });++ this.emailTestEmail = `${utils.generateUUID()}@example.org`;({ body: userObj, jar } = await helpers.registerUser({username: 'email-test',password: 'abcdef',- email: '[email protected]',+ email: this.emailTestEmail,gdpr_consent: true,+ acceptTos: true,}));});- it('should have a pending validation', async () => {- assert.strictEqual(await user.email.isValidationPending(userObj.uid, '[email protected]'), true);+ after(async () => {+ plugins.hooks.unregister('emailer-test', 'static:email.send');+ });++ it('should have a pending validation', async function () {+ assert.strictEqual(await user.email.isValidationPending(userObj.uid, this.emailTestEmail), true);});it('should not list their email', async () => {@@ -170,8 +182,8 @@ describe('email confirmation (v3 api)', () => {assert.deepStrictEqual(body, JSON.parse('{"status":{"code":"ok","message":"OK"},"response":{"emails":[]}}'));});- it('should not allow confirmation if they are not an admin', async () => {- const { response } = await helpers.request('post', `/api/v3/users/${userObj.uid}/emails/${encodeURIComponent('[email protected]')}/confirm`, {+ it('should not allow confirmation if they are not an admin', async function () {+ const { response } = await helpers.request('post', `/api/v3/users/${userObj.uid}/emails/${encodeURIComponent(this.emailTestEmail)}/confirm`, {jar,});@@ -188,9 +200,9 @@ describe('email confirmation (v3 api)', () => {await groups.leave('administrators', userObj.uid);});- it('should confirm their email (using the pending validation)', async () => {+ it('should confirm their email (using the pending validation)', async function () {await groups.join('administrators', userObj.uid);- const { response, body } = await helpers.request('post', `/api/v3/users/${userObj.uid}/emails/${encodeURIComponent('[email protected]')}/confirm`, {+ const { response, body } = await helpers.request('post', `/api/v3/users/${userObj.uid}/emails/${encodeURIComponent(this.emailTestEmail)}/confirm`, {jar,});@@ -199,13 +211,13 @@ describe('email confirmation (v3 api)', () => {await groups.leave('administrators', userObj.uid);});- it('should still confirm the email (as email is set in user hash)', async () => {+ it('should still confirm the email (as email is set in user hash)', async function () {await user.email.remove(userObj.uid);- await user.setUserField(userObj.uid, 'email', '[email protected]');+ await user.setUserField(userObj.uid, 'email', this.emailTestEmail);({ jar } = await helpers.loginUser('email-test', 'abcdef')); // email removal logs out everybodyawait groups.join('administrators', userObj.uid);- const { response, body } = await helpers.request('post', `/api/v3/users/${userObj.uid}/emails/${encodeURIComponent('[email protected]')}/confirm`, {+ const { response, body } = await helpers.request('post', `/api/v3/users/${userObj.uid}/emails/${encodeURIComponent(this.emailTestEmail)}/confirm`, {jar,json: true,});