diff --git a/server/src/creators/account-creator.js b/server/src/creators/account-creator.js index b9877ddbf..279bb760a 100644 --- a/server/src/creators/account-creator.js +++ b/server/src/creators/account-creator.js @@ -1,176 +1,178 @@ // @flow import invariant from 'invariant'; import bcrypt from 'twin-bcrypt'; import ashoat from 'lib/facts/ashoat'; import bots from 'lib/facts/bots'; import { validUsernameRegex, oldValidUsernameRegex, validEmailRegex, } from 'lib/shared/account-utils'; import { hasMinCodeVersion } from 'lib/shared/version-utils'; import type { RegisterResponse, RegisterRequest, } from 'lib/types/account-types'; import { messageTypes } from 'lib/types/message-types'; import { threadTypes } from 'lib/types/thread-types'; import { ServerError } from 'lib/utils/errors'; import { values } from 'lib/utils/objects'; import { dbQuery, SQL } from '../database/database'; import { deleteCookie } from '../deleters/cookie-deleters'; import { sendEmailAddressVerificationEmail } from '../emails/verification'; import { fetchThreadInfos } from '../fetchers/thread-fetchers'; import { fetchKnownUserInfos } from '../fetchers/user-fetchers'; import { verifyCalendarQueryThreadIDs } from '../responders/entry-responders'; import { createNewUserCookie, setNewSession } from '../session/cookies'; import type { Viewer } from '../session/viewer'; import createIDs from './id-creator'; import createMessages from './message-creator'; -import { createThread, createPrivateThread } from './thread-creator'; +import { + createThread, + createPrivateThread, + privateThreadDescription, +} from './thread-creator'; const { squadbot } = bots; const ashoatMessages = [ 'welcome to SquadCal! thanks for helping to test the alpha.', 'as you inevitably discover bugs, have feature requests, or design ' + 'suggestions, feel free to message them to me in the app.', ]; -const privateMessages = [ - 'This is your private thread, where you can set reminders and jot notes in private!', -]; +const privateMessages = [privateThreadDescription]; async function createAccount( viewer: Viewer, request: RegisterRequest, ): Promise { if (request.password.trim() === '') { throw new ServerError('empty_password'); } const usernameRegex = hasMinCodeVersion(viewer.platformDetails, 69) ? validUsernameRegex : oldValidUsernameRegex; if (request.username.search(usernameRegex) === -1) { throw new ServerError('invalid_username'); } if (request.email.search(validEmailRegex) === -1) { throw new ServerError('invalid_email'); } const usernameQuery = SQL` SELECT COUNT(id) AS count FROM users WHERE LCASE(username) = LCASE(${request.username}) `; const emailQuery = SQL` SELECT COUNT(id) AS count FROM users WHERE LCASE(email) = LCASE(${request.email}) `; const promises = [dbQuery(usernameQuery), dbQuery(emailQuery)]; const { calendarQuery } = request; if (calendarQuery) { promises.push(verifyCalendarQueryThreadIDs(calendarQuery)); } const [[usernameResult], [emailResult]] = await Promise.all(promises); if (usernameResult[0].count !== 0) { throw new ServerError('username_taken'); } if (emailResult[0].count !== 0) { throw new ServerError('email_taken'); } const hash = bcrypt.hashSync(request.password); const time = Date.now(); const deviceToken = request.deviceTokenUpdateRequest ? request.deviceTokenUpdateRequest.deviceToken : viewer.deviceToken; const [id] = await createIDs('users', 1); const newUserRow = [id, request.username, hash, request.email, time]; const newUserQuery = SQL` INSERT INTO users(id, username, hash, email, creation_time) VALUES ${[newUserRow]} `; const [userViewerData] = await Promise.all([ createNewUserCookie(id, { platformDetails: request.platformDetails, deviceToken, }), deleteCookie(viewer.cookieID), dbQuery(newUserQuery), sendEmailAddressVerificationEmail( id, request.username, request.email, true, ), ]); viewer.setNewCookie(userViewerData); if (calendarQuery) { await setNewSession(viewer, calendarQuery, 0); } const [privateThreadResult, ashoatThreadResult] = await Promise.all([ createPrivateThread(viewer, request.username), createThread( viewer, { type: threadTypes.PERSONAL, initialMemberIDs: [ashoat.id], }, { forceAddMembers: true }, ), ]); const ashoatThreadID = ashoatThreadResult.newThreadInfo ? ashoatThreadResult.newThreadInfo.id : ashoatThreadResult.newThreadID; const privateThreadID = privateThreadResult.newThreadInfo ? privateThreadResult.newThreadInfo.id : privateThreadResult.newThreadID; invariant( ashoatThreadID && privateThreadID, 'createThread should return either newThreadInfo or newThreadID', ); let messageTime = Date.now(); const ashoatMessageDatas = ashoatMessages.map((message) => ({ type: messageTypes.TEXT, threadID: ashoatThreadID, creatorID: ashoat.id, time: messageTime++, text: message, })); const privateMessageDatas = privateMessages.map((message) => ({ type: messageTypes.TEXT, threadID: privateThreadID, creatorID: squadbot.userID, time: messageTime++, text: message, })); const messageDatas = [...ashoatMessageDatas, ...privateMessageDatas]; const [messageInfos, threadsResult, userInfos] = await Promise.all([ createMessages(viewer, messageDatas), fetchThreadInfos(viewer), fetchKnownUserInfos(viewer), ]); const rawMessageInfos = [ ...ashoatThreadResult.newMessageInfos, ...privateThreadResult.newMessageInfos, ...messageInfos, ]; return { id, rawMessageInfos, cookieChange: { threadInfos: threadsResult.threadInfos, userInfos: values(userInfos), }, }; } export default createAccount; diff --git a/server/src/creators/thread-creator.js b/server/src/creators/thread-creator.js index d0b6bbe86..910180f5f 100644 --- a/server/src/creators/thread-creator.js +++ b/server/src/creators/thread-creator.js @@ -1,507 +1,509 @@ // @flow import invariant from 'invariant'; import bots from 'lib/facts/bots'; import { relationshipBlockedInEitherDirection } from 'lib/shared/relationship-utils'; import { generatePendingThreadColor, generateRandomColor, } from 'lib/shared/thread-utils'; import { hasMinCodeVersion } from 'lib/shared/version-utils'; import type { Shape } from 'lib/types/core'; import { messageTypes } from 'lib/types/message-types'; import { userRelationshipStatus } from 'lib/types/relationship-types'; import { type NewThreadRequest, type NewThreadResponse, threadTypes, threadPermissions, } from 'lib/types/thread-types'; import { ServerError } from 'lib/utils/errors'; import { promiseAll } from 'lib/utils/promises'; import { dbQuery, SQL } from '../database/database'; import { fetchMessageInfoByID } from '../fetchers/message-fetchers'; import { fetchThreadInfos } from '../fetchers/thread-fetchers'; import { checkThreadPermission } from '../fetchers/thread-permission-fetchers'; import { fetchKnownUserInfos } from '../fetchers/user-fetchers'; import type { Viewer } from '../session/viewer'; import { changeRole, recalculateAllPermissions, commitMembershipChangeset, setJoinsToUnread, getRelationshipRowsForUsers, getParentThreadRelationshipRowsForNewUsers, } from '../updaters/thread-permission-updaters'; import createIDs from './id-creator'; import createMessages from './message-creator'; import { createInitialRolesForNewThread } from './role-creator'; import type { UpdatesForCurrentSession } from './update-creator'; const { squadbot } = bots; +const privateThreadDescription = + 'This is your private thread, ' + + 'where you can set reminders and jot notes in private!'; + type CreateThreadOptions = Shape<{| +forceAddMembers: boolean, +updatesForCurrentSession: UpdatesForCurrentSession, +silentlyFailMembers: boolean, |}>; // If forceAddMembers is set, we will allow the viewer to add random users who // they aren't friends with. We will only fail if the viewer is trying to add // somebody who they have blocked or has blocked them. On the other hand, if // forceAddMembers is not set, we will fail if the viewer tries to add somebody // who they aren't friends with and doesn't have a membership row with a // nonnegative role for the parent thread. async function createThread( viewer: Viewer, request: NewThreadRequest, options?: CreateThreadOptions, ): Promise { if (!viewer.loggedIn) { throw new ServerError('not_logged_in'); } const forceAddMembers = options?.forceAddMembers ?? false; const updatesForCurrentSession = options?.updatesForCurrentSession ?? 'return'; const silentlyFailMembers = options?.silentlyFailMembers ?? false; const threadType = request.type; const shouldCreateRelationships = forceAddMembers || threadType === threadTypes.PERSONAL; const parentThreadID = request.parentThreadID ? request.parentThreadID : null; const initialMemberIDsFromRequest = request.initialMemberIDs && request.initialMemberIDs.length > 0 ? request.initialMemberIDs : null; const ghostMemberIDs = request.ghostMemberIDs && request.ghostMemberIDs.length > 0 ? request.ghostMemberIDs : null; const sourceMessageID = request.sourceMessageID ? request.sourceMessageID : null; invariant( threadType !== threadTypes.SIDEBAR || sourceMessageID, 'sourceMessageID should be set for sidebar', ); if ( threadType !== threadTypes.CHAT_SECRET && threadType !== threadTypes.PERSONAL && threadType !== threadTypes.PRIVATE && !parentThreadID ) { throw new ServerError('invalid_parameters'); } if ( threadType === threadTypes.PERSONAL && (request.initialMemberIDs?.length !== 1 || parentThreadID) ) { throw new ServerError('invalid_parameters'); } const checkPromises = {}; if (parentThreadID) { checkPromises.parentThreadFetch = fetchThreadInfos( viewer, SQL`t.id = ${parentThreadID}`, ); checkPromises.hasParentPermission = checkThreadPermission( viewer, parentThreadID, threadType === threadTypes.SIDEBAR ? threadPermissions.CREATE_SIDEBARS : threadPermissions.CREATE_SUBTHREADS, ); } const memberIDs = []; if (initialMemberIDsFromRequest) { memberIDs.push(...initialMemberIDsFromRequest); } if (ghostMemberIDs) { memberIDs.push(...ghostMemberIDs); } if (initialMemberIDsFromRequest || ghostMemberIDs) { checkPromises.fetchMemberIDs = fetchKnownUserInfos(viewer, memberIDs); } if (sourceMessageID) { checkPromises.sourceMessage = fetchMessageInfoByID(viewer, sourceMessageID); } const { parentThreadFetch, hasParentPermission, fetchMemberIDs, sourceMessage, } = await promiseAll(checkPromises); let parentThreadMembers; if (parentThreadID) { invariant(parentThreadFetch, 'parentThreadFetch should be set'); const parentThreadInfo = parentThreadFetch.threadInfos[parentThreadID]; if (!hasParentPermission) { throw new ServerError('invalid_credentials'); } parentThreadMembers = parentThreadInfo.members.map( (userInfo) => userInfo.id, ); } const viewerNeedsRelationshipsWith = []; const silencedMemberIDs = new Set(); if (fetchMemberIDs) { invariant(initialMemberIDsFromRequest || ghostMemberIDs, 'should be set'); for (const memberID of memberIDs) { const member = fetchMemberIDs[memberID]; if ( !member && shouldCreateRelationships && (threadType !== threadTypes.SIDEBAR || parentThreadMembers?.includes(memberID)) ) { viewerNeedsRelationshipsWith.push(memberID); continue; } else if (!member && silentlyFailMembers) { silencedMemberIDs.add(memberID); continue; } else if (!member) { throw new ServerError('invalid_credentials'); } const { relationshipStatus } = member; const memberRelationshipHasBlock = !!( relationshipStatus && relationshipBlockedInEitherDirection(relationshipStatus) ); if ( relationshipStatus === userRelationshipStatus.FRIEND && threadType !== threadTypes.SIDEBAR ) { continue; } else if (memberRelationshipHasBlock && silentlyFailMembers) { silencedMemberIDs.add(memberID); } else if (memberRelationshipHasBlock) { throw new ServerError('invalid_credentials'); } else if ( parentThreadMembers && parentThreadMembers.includes(memberID) ) { continue; } else if (!shouldCreateRelationships && silentlyFailMembers) { silencedMemberIDs.add(memberID); } else if (!shouldCreateRelationships) { throw new ServerError('invalid_credentials'); } } } const filteredInitialMemberIDs: ?$ReadOnlyArray = initialMemberIDsFromRequest?.filter( (id) => !silencedMemberIDs.has(id), ); const initialMemberIDs = filteredInitialMemberIDs && filteredInitialMemberIDs.length > 0 ? filteredInitialMemberIDs : null; const [id] = await createIDs('threads', 1); const newRoles = await createInitialRolesForNewThread(id, threadType); const name = request.name ? request.name : null; const description = request.description ? request.description : null; let color = request.color ? request.color.toLowerCase() : generateRandomColor(); if (threadType === threadTypes.PERSONAL) { color = generatePendingThreadColor( request.initialMemberIDs ?? [], viewer.id, ); } const time = Date.now(); const row = [ id, threadType, name, description, viewer.userID, time, color, parentThreadID, newRoles.default.id, sourceMessageID, ]; if (threadType === threadTypes.PERSONAL) { const otherMemberID = initialMemberIDs?.[0]; invariant( otherMemberID, 'Other member id should be set for a PERSONAL thread', ); const query = SQL` INSERT INTO threads(id, type, name, description, creator, creation_time, color, parent_thread_id, default_role, source_message) SELECT ${row} WHERE NOT EXISTS ( SELECT * FROM threads t INNER JOIN memberships m1 ON m1.thread = t.id AND m1.user = ${viewer.userID} INNER JOIN memberships m2 ON m2.thread = t.id AND m2.user = ${otherMemberID} WHERE t.type = ${threadTypes.PERSONAL} AND m1.role != -1 AND m2.role != -1 ) `; const [result] = await dbQuery(query); if (result.affectedRows === 0) { const personalThreadQuery = SQL` SELECT t.id FROM threads t INNER JOIN memberships m1 ON m1.thread = t.id AND m1.user = ${viewer.userID} INNER JOIN memberships m2 ON m2.thread = t.id AND m2.user = ${otherMemberID} WHERE t.type = ${threadTypes.PERSONAL} AND m1.role != -1 AND m2.role != -1 `; const deleteRoles = SQL` DELETE FROM roles WHERE id IN (${newRoles.default.id}, ${newRoles.creator.id}) `; const deleteIDs = SQL` DELETE FROM ids WHERE id IN (${id}, ${newRoles.default.id}, ${newRoles.creator.id}) `; const [[personalThreadResult]] = await Promise.all([ dbQuery(personalThreadQuery), dbQuery(deleteRoles), dbQuery(deleteIDs), ]); invariant( personalThreadResult.length > 0, 'PERSONAL thread should exist', ); const personalThreadID = personalThreadResult[0].id.toString(); return { newThreadID: personalThreadID, updatesResult: { newUpdates: [], }, userInfos: {}, newMessageInfos: [], }; } } else { const query = SQL` INSERT INTO threads(id, type, name, description, creator, creation_time, color, parent_thread_id, default_role, source_message) VALUES ${[row]} `; await dbQuery(query); } const [ creatorChangeset, initialMembersChangeset, ghostMembersChangeset, recalculatePermissionsChangeset, ] = await Promise.all([ changeRole(id, [viewer.userID], newRoles.creator.id), initialMemberIDs ? changeRole(id, initialMemberIDs, null) : undefined, ghostMemberIDs ? changeRole(id, ghostMemberIDs, -1) : undefined, recalculateAllPermissions(id, threadType), ]); if (!creatorChangeset) { throw new ServerError('unknown_error'); } const { membershipRows: creatorMembershipRows, relationshipRows: creatorRelationshipRows, } = creatorChangeset; const { membershipRows: recalculateMembershipRows, relationshipRows: recalculateRelationshipRows, } = recalculatePermissionsChangeset; const membershipRows = [ ...creatorMembershipRows, ...recalculateMembershipRows, ]; const relationshipRows = [ ...creatorRelationshipRows, ...recalculateRelationshipRows, ]; if (initialMemberIDs || ghostMemberIDs) { if (!initialMembersChangeset && !ghostMembersChangeset) { throw new ServerError('unknown_error'); } relationshipRows.push( ...getRelationshipRowsForUsers( viewer.userID, viewerNeedsRelationshipsWith, ), ); const membersMembershipRows = []; const membersRelationshipRows = []; if (initialMembersChangeset) { const { membershipRows: initialMembersMembershipRows, relationshipRows: initialMembersRelationshipRows, } = initialMembersChangeset; membersMembershipRows.push(...initialMembersMembershipRows); membersRelationshipRows.push(...initialMembersRelationshipRows); } if (ghostMembersChangeset) { const { membershipRows: ghostMembersMembershipRows, relationshipRows: ghostMembersRelationshipRows, } = ghostMembersChangeset; membersMembershipRows.push(...ghostMembersMembershipRows); membersRelationshipRows.push(...ghostMembersRelationshipRows); } const memberAndCreatorIDs = [...memberIDs, viewer.userID]; const parentRelationshipRows = getParentThreadRelationshipRowsForNewUsers( id, recalculateMembershipRows, memberAndCreatorIDs, ); membershipRows.push(...membersMembershipRows); relationshipRows.push( ...membersRelationshipRows, ...parentRelationshipRows, ); } setJoinsToUnread(membershipRows, viewer.userID, id); const changeset = { membershipRows, relationshipRows }; const { threadInfos, viewerUpdates, userInfos, } = await commitMembershipChangeset(viewer, changeset, { updatesForCurrentSession, }); const initialMemberAndCreatorIDs = initialMemberIDs ? [...initialMemberIDs, viewer.userID] : [viewer.userID]; const messageDatas = []; if (threadType !== threadTypes.SIDEBAR) { messageDatas.push({ type: messageTypes.CREATE_THREAD, threadID: id, creatorID: viewer.userID, time, initialThreadState: { type: threadType, name, parentThreadID, color, memberIDs: initialMemberAndCreatorIDs, }, }); } else { invariant(parentThreadID, 'parentThreadID should be set for sidebar'); if (!sourceMessage || sourceMessage.type === messageTypes.SIDEBAR_SOURCE) { throw new ServerError('invalid_parameters'); } messageDatas.push( { type: messageTypes.CREATE_SIDEBAR, threadID: id, creatorID: viewer.userID, time, sourceMessageAuthorID: sourceMessage.creatorID, initialThreadState: { name, parentThreadID, color, memberIDs: initialMemberAndCreatorIDs, }, }, { type: messageTypes.SIDEBAR_SOURCE, threadID: id, creatorID: viewer.userID, time, sourceMessage, }, ); } if (parentThreadID && threadType !== threadTypes.SIDEBAR) { messageDatas.push({ type: messageTypes.CREATE_SUB_THREAD, threadID: parentThreadID, creatorID: viewer.userID, time, childThreadID: id, }); } const newMessageInfos = await createMessages( viewer, messageDatas, updatesForCurrentSession, ); if (hasMinCodeVersion(viewer.platformDetails, 62)) { return { newThreadID: id, updatesResult: { newUpdates: viewerUpdates, }, userInfos, newMessageInfos, }; } return { newThreadInfo: threadInfos[id], updatesResult: { newUpdates: viewerUpdates, }, userInfos, newMessageInfos, }; } function createPrivateThread( viewer: Viewer, username: string, ): Promise { return createThread( viewer, { type: threadTypes.PRIVATE, name: username, - description: - 'This is your private thread, ' + - 'where you can set reminders and jot notes in private!', + description: privateThreadDescription, ghostMemberIDs: [squadbot.userID], }, { forceAddMembers: true, }, ); } -export { createThread, createPrivateThread }; +export { createThread, createPrivateThread, privateThreadDescription }; diff --git a/server/src/scripts/create-private-threads.js b/server/src/scripts/create-private-threads.js index a07bc844b..2b86d9deb 100644 --- a/server/src/scripts/create-private-threads.js +++ b/server/src/scripts/create-private-threads.js @@ -1,71 +1,68 @@ // @flow import bots from 'lib/facts/bots.json'; import { threadTypes } from 'lib/types/thread-types'; import { getRolePermissionBlobsForChat } from '../creators/role-creator'; +import { privateThreadDescription } from '../creators/thread-creator'; import { dbQuery, SQL } from '../database/database'; import { createScriptViewer } from '../session/scripts'; import { commitMembershipChangeset, recalculateAllPermissions, } from '../updaters/thread-permission-updaters'; import { main } from './utils'; async function markThreadsAsPrivate() { const findThreadsToUpdate = SQL` SELECT t.id, r.id AS role FROM ( SELECT t.id FROM threads t INNER JOIN memberships m ON m.thread = t.id WHERE t.type = ${threadTypes.CHAT_SECRET} GROUP BY id HAVING COUNT(m.thread) = 1 ) t INNER JOIN roles r ON r.thread = t.id `; const [result] = await dbQuery(findThreadsToUpdate); const threadIDs = result.map((row) => row.id); if (threadIDs.length === 0) { return; } - const description = - 'This is your private thread, ' + - 'where you can set reminders and jot notes in private!'; - const updateThreads = SQL` UPDATE threads - SET type = ${threadTypes.PRIVATE}, description = ${description} + SET type = ${threadTypes.PRIVATE}, description = ${privateThreadDescription} WHERE id IN (${threadIDs}) `; const defaultRolePermissions = getRolePermissionBlobsForChat( threadTypes.PRIVATE, ).Members; const defaultRolePermissionString = JSON.stringify(defaultRolePermissions); const viewer = createScriptViewer(bots.squadbot.userID); const permissionPromises = result.map(async ({ id, role }) => { console.log(`Updating thread ${id} and role ${role}`); const updatePermissions = SQL` UPDATE roles SET permissions = ${defaultRolePermissionString} WHERE id = ${role} `; await dbQuery(updatePermissions); const changeset = await recalculateAllPermissions( id.toString(), threadTypes.PRIVATE, ); return await commitMembershipChangeset(viewer, changeset); }); await Promise.all([dbQuery(updateThreads), ...permissionPromises]); } main([markThreadsAsPrivate]);