Add basically support for encrypted app list syncing

This commit is contained in:
Jonas Lochmann
2022-07-25 02:00:00 +02:00
parent acdec990ea
commit 8a5e46811e
104 changed files with 5287 additions and 55 deletions
+3 -1
View File
@@ -64,5 +64,7 @@ export const prepareDeviceEntry = ({ familyId, userId, deviceAuthToken, deviceId
wasAsEnabled: false,
activityLevelBlocking: false,
isQorLater: false,
manipulationFlags: 0
manipulationFlags: 0,
publicKey: null,
nextKeyReplySequenceNumber: '1'
})
+3 -2
View File
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2021 Jonas Lochmann
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -65,7 +65,8 @@ export const createFamily = async ({ database, mailAuthToken, firstParentDevice,
deviceListVersion: generateVersionId(),
// 14 days demo version
fullVersionUntil: (Date.now() + 1000 * 60 * 60 * 24 * 14).toString(10),
hasFullVersion: true
hasFullVersion: true,
nextServerKeyRequestSeq: '1'
}, { transaction })
// create parent user
@@ -0,0 +1,34 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { FinishKeyRequestAction } from '../../../../action'
import { Cache } from '../cache'
export async function dispatchFinishKeyRequestAction ({ action, cache, deviceId }: {
deviceId: string
action: FinishKeyRequestAction
cache: Cache
}) {
await cache.database.keyRequest.destroy({
where: {
familyId: cache.familyId,
senderDeviceId: deviceId,
senderSequenceNumber: action.deviceSequenceNumber.toString(10)
},
transaction: cache.transaction
})
}
@@ -1,6 +1,6 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2020 Jonas Lochmann
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
@@ -20,13 +20,18 @@ import {
AddUsedTimeAction,
AddUsedTimeActionVersion2,
AppLogicAction,
FinishKeyRequestAction,
ForceSyncAction,
MarkTaskPendingAction,
ReplyToKeyRequestAction,
RemoveInstalledAppsAction,
SendKeyRequestAction,
SignOutAtDeviceAction,
TriedDisablingDeviceAdminAction,
UpdateAppActivitiesAction,
UpdateDeviceStatusAction
UpdateDeviceStatusAction,
UpdateInstalledAppsAction,
UploadDevicePublicKeyAction
} from '../../../../action'
import { EventHandler } from '../../../../monitoring/eventhandler'
import { Cache } from '../cache'
@@ -34,13 +39,18 @@ import { ActionObjectTypeNotHandledException } from '../exception/illegal-state'
import { dispatchAddInstalledApps } from './addinstalledapps'
import { dispatchAddUsedTime } from './addusedtime'
import { dispatchAddUsedTimeVersion2 } from './addusedtime2'
import { dispatchFinishKeyRequestAction } from './finishkeyrequest'
import { dispatchForceSyncAction } from './forcesync'
import { dispatchMarkTaskPendingAction } from './marktaskpendingaction'
import { dispatchReplyToKeyRequestAction } from './replytokeyrequest'
import { dispatchRemoveInstalledApps } from './removeinstalledapps'
import { dispatchSendKeyRequestAction } from './sendkeyrequest'
import { dispatchSignOutAtDevice } from './signoutatdevice'
import { dispatchTriedDisablingDeviceAdmin } from './trieddisablingdeviceadmin'
import { dispatchUpdateAppActivities } from './updateappactivities'
import { dispatchUpdateDeviceStatus } from './updatedevicestatus'
import { dispatchUpdateInstalledApps } from './updateinstalledapps'
import { dispatchUploadDevicePublicKeyAction } from './uploaddevicepublickey'
export const dispatchAppLogicAction = async ({ action, deviceId, cache, eventHandler }: {
action: AppLogicAction
@@ -54,12 +64,18 @@ export const dispatchAppLogicAction = async ({ action, deviceId, cache, eventHan
await dispatchAddUsedTime({ deviceId, action, cache })
} else if (action instanceof AddUsedTimeActionVersion2) {
await dispatchAddUsedTimeVersion2({ deviceId, action, cache, eventHandler })
} else if (action instanceof FinishKeyRequestAction) {
await dispatchFinishKeyRequestAction({ deviceId, action, cache })
} else if (action instanceof ForceSyncAction) {
await dispatchForceSyncAction({ deviceId, action, cache })
} else if (action instanceof MarkTaskPendingAction) {
await dispatchMarkTaskPendingAction({ deviceId, action, cache })
} else if (action instanceof ReplyToKeyRequestAction) {
await dispatchReplyToKeyRequestAction({ deviceId, action, cache, eventHandler })
} else if (action instanceof RemoveInstalledAppsAction) {
await dispatchRemoveInstalledApps({ deviceId, action, cache })
} else if (action instanceof SendKeyRequestAction) {
await dispatchSendKeyRequestAction({ deviceId, action, cache })
} else if (action instanceof SignOutAtDeviceAction) {
await dispatchSignOutAtDevice({ deviceId, action, cache })
} else if (action instanceof UpdateDeviceStatusAction) {
@@ -68,6 +84,10 @@ export const dispatchAppLogicAction = async ({ action, deviceId, cache, eventHan
await dispatchUpdateAppActivities({ deviceId, action, cache })
} else if (action instanceof TriedDisablingDeviceAdminAction) {
await dispatchTriedDisablingDeviceAdmin({ deviceId, action, cache })
} else if (action instanceof UpdateInstalledAppsAction) {
await dispatchUpdateInstalledApps({ deviceId, action, cache })
} else if (action instanceof UploadDevicePublicKeyAction) {
await dispatchUploadDevicePublicKeyAction({ deviceId, action, cache, eventHandler })
} else {
throw new ActionObjectTypeNotHandledException()
}
@@ -0,0 +1,108 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { ReplyToKeyRequestAction } from '../../../../action'
import { Cache } from '../cache'
import { EventHandler } from '../../../../monitoring/eventhandler'
import { SourceDeviceNotFoundException } from '../exception/illegal-state'
export async function dispatchReplyToKeyRequestAction ({ deviceId, action, cache, eventHandler }: {
deviceId: string
action: ReplyToKeyRequestAction
cache: Cache
eventHandler: EventHandler
}) {
const requestUnsafe = await cache.database.keyRequest.findOne({
where: {
familyId: cache.familyId,
serverSequenceNumber: action.requestServerSequenceNumber.toString(10)
},
attributes: ['senderDeviceId', 'senderSequenceNumber'],
transaction: cache.transaction
})
if (!requestUnsafe) {
eventHandler.countEvent('dispatchReplyToKeyRequestAction:request does not exists (anymore)')
return
}
const request = {
senderDeviceId: requestUnsafe.senderDeviceId,
senderSequenceNumber: requestUnsafe.senderSequenceNumber
}
const oldReplyCounter = await cache.database.keyResponse.count({
where: {
familyId: cache.familyId,
receiverDeviceId: request.senderDeviceId,
requestServerSequenceNumber: action.requestServerSequenceNumber.toString(10),
senderDeviceId: deviceId
},
transaction: cache.transaction
})
if (oldReplyCounter !== 0) {
eventHandler.countEvent('dispatchReplyToKeyRequestAction:got duplicate reply which was ignored')
return
}
const deviceEntryUnsafe = await cache.database.device.findOne({
where: {
familyId: cache.familyId,
deviceId
},
transaction: cache.transaction,
attributes: ['nextKeyReplySequenceNumber']
})
if (!deviceEntryUnsafe) {
throw new SourceDeviceNotFoundException()
}
const deviceEntry = {
nextKeyReplySequenceNumber: deviceEntryUnsafe.nextKeyReplySequenceNumber
}
await cache.database.device.update({
nextKeyReplySequenceNumber: (parseInt(deviceEntry.nextKeyReplySequenceNumber) + 1).toString(10)
}, {
where: {
familyId: cache.familyId,
deviceId
},
transaction: cache.transaction
})
await cache.database.keyResponse.create({
familyId: cache.familyId,
receiverDeviceId: request.senderDeviceId,
requestServerSequenceNumber: action.requestServerSequenceNumber.toString(10),
senderDeviceId: deviceId,
replyServerSequenceNumber: deviceEntry.nextKeyReplySequenceNumber,
requestClientSequenceNumber: requestUnsafe.senderSequenceNumber,
tempKey: action.tempKey,
encryptedKey: action.encryptedKey,
signature: action.signature
}, {
transaction: cache.transaction
})
// there is no way (yet) to inform the specific device only
cache.areChangesImportant = true
}
@@ -0,0 +1,76 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { SendKeyRequestAction } from '../../../../action'
import { Cache } from '../cache'
import { SourceFamilyNotFoundException } from '../exception/illegal-state'
export async function dispatchSendKeyRequestAction ({ action, cache, deviceId }: {
deviceId: string
action: SendKeyRequestAction
cache: Cache
}) {
const familyEntryUnsafe = await cache.database.family.findOne({
where: {
familyId: cache.familyId
},
transaction: cache.transaction,
attributes: ['nextServerKeyRequestSeq']
})
if (!familyEntryUnsafe) {
throw new SourceFamilyNotFoundException()
}
const serverSequenceNumber = familyEntryUnsafe.nextServerKeyRequestSeq
await cache.database.family.update({
nextServerKeyRequestSeq: (parseInt(serverSequenceNumber, 10) + 1).toString(10)
}, {
where: {
familyId: cache.familyId
},
transaction: cache.transaction
})
await cache.database.keyRequest.destroy({
where: {
familyId: cache.familyId,
senderDeviceId: deviceId,
type: action.type,
deviceId: action.deviceId || null,
categoryId: action.categoryId || null
},
transaction: cache.transaction
})
await cache.database.keyRequest.create({
familyId: cache.familyId,
serverSequenceNumber: serverSequenceNumber,
senderDeviceId: deviceId,
senderSequenceNumber: action.deviceSequenceNumber.toString(10),
deviceId: action.deviceId || null,
categoryId: action.categoryId || null,
type: action.type,
tempKey: action.tempKey,
signature: action.signature
}, {
transaction: cache.transaction
})
cache.areChangesImportant = true
}
@@ -0,0 +1,59 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { UpdateInstalledAppsAction } from '../../../../action'
import { types } from '../../../../database/encryptedapplist'
import { generateVersionId } from '../../../../util/token'
import { Cache } from '../cache'
export async function dispatchUpdateInstalledApps ({ deviceId, action, cache }: {
deviceId: string
action: UpdateInstalledAppsAction
cache: Cache
}) {
if (action.base) {
await cache.database.encryptedAppList.upsert({
familyId: cache.familyId,
deviceId,
type: types.base,
version: generateVersionId(),
data: action.base
}, { transaction: cache.transaction })
}
if (action.diff) {
await cache.database.encryptedAppList.upsert({
familyId: cache.familyId,
deviceId,
type: types.diff,
version: generateVersionId(),
data: action.diff
}, { transaction: cache.transaction })
}
if (action.wipe) {
await cache.database.app.destroy({
where: {
familyId: cache.familyId,
deviceId
},
transaction: cache.transaction
})
cache.devicesWithModifiedInstalledApps.add(deviceId)
}
}
@@ -0,0 +1,50 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { UploadDevicePublicKeyAction } from '../../../../action'
import { Cache } from '../cache'
import { EventHandler } from '../../../../monitoring/eventhandler'
import { SourceDeviceNotFoundException } from '../exception/illegal-state'
export async function dispatchUploadDevicePublicKeyAction ({ deviceId, action, cache, eventHandler }: {
deviceId: string
action: UploadDevicePublicKeyAction
cache: Cache
eventHandler: EventHandler
}) {
const deviceEntry = await cache.database.device.findOne({
where: {
familyId: cache.familyId,
deviceId
},
transaction: cache.transaction
})
if (deviceEntry === null) {
throw new SourceDeviceNotFoundException()
} else if (deviceEntry.publicKey === null) {
deviceEntry.publicKey = action.key
await deviceEntry.save({ transaction: cache.transaction })
cache.invalidiateDeviceList = true
} else if (deviceEntry.publicKey.equals(action.key)) {
eventHandler.countEvent('dispatchUploadDevicePublicKeyAction:duplicate action')
} else {
eventHandler.countEvent('dispatchUploadDevicePublicKeyAction:got new public key for existing device')
}
}
@@ -0,0 +1,119 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import * as Sequelize from 'sequelize'
import { Database } from '../../../database'
import { ClientDataStatusDevicesExtended } from '../../../object/clientdatastatus'
import { ServerExtendedDeviceData, ServerCryptContainer } from '../../../object/serverdatastatus'
import { FamilyEntry } from './family-entry'
import { types } from '../../../database/encryptedapplist'
export async function getDeviceDetailList ({ database, transaction, familyEntry, devicesDetail }: {
database: Database
transaction: Sequelize.Transaction
familyEntry: FamilyEntry
devicesDetail: ClientDataStatusDevicesExtended
}): Promise<Array<ServerExtendedDeviceData> | null> {
const serverEncryptedAppsVersions = (await database.encryptedAppList.findAll({
where: {
familyId: familyEntry.familyId,
},
attributes: ['deviceId', 'type', 'version'],
transaction
})).map((item) => ({
deviceId: item.deviceId,
type: item.type,
version: item.version
}))
const devicesWithChangedBaseApps: Array<string> = []
const devicesWithChangedDiffApps: Array<string> = []
serverEncryptedAppsVersions.forEach((item) => {
if (item.type === types.base) {
if (!devicesDetail[item.deviceId] || devicesDetail[item.deviceId].appsB !== item.version) {
devicesWithChangedBaseApps.push(item.deviceId)
}
} else if (item.type === types.diff) {
if (!devicesDetail[item.deviceId] || devicesDetail[item.deviceId].appsD !== item.version) {
devicesWithChangedDiffApps.push(item.deviceId)
}
}
})
const updatedDeviceIds = Array.from(new Set([...devicesWithChangedBaseApps, ...devicesWithChangedDiffApps]))
if (updatedDeviceIds.length === 0) return null
const updatedBaseApps = devicesWithChangedBaseApps.length === 0 ? [] : (await database.encryptedAppList.findAll({
where: {
familyId: familyEntry.familyId,
deviceId: {
[Sequelize.Op.in]: devicesWithChangedBaseApps
},
type: types.base
},
attributes: [
'deviceId',
'version',
'data'
],
transaction
})).map((item) => ({
deviceId: item.deviceId,
version: item.version,
data: item.data
}))
const updatedDiffApps = devicesWithChangedDiffApps.length === 0 ? [] : (await database.encryptedAppList.findAll({
where: {
familyId: familyEntry.familyId,
deviceId: {
[Sequelize.Op.in]: devicesWithChangedDiffApps
},
type: types.diff
},
attributes: [
'deviceId',
'version',
'data'
],
transaction
})).map((item) => ({
deviceId: item.deviceId,
version: item.version,
data: item.data
}))
return updatedDeviceIds.map((deviceId) => {
const appsBase = updatedBaseApps.find((item) => item.deviceId === deviceId)
const appsDiff = updatedDiffApps.find((item) => item.deviceId === deviceId)
return {
deviceId,
appsBase: appsBase ? wrapServerCryptContainer(appsBase) : undefined,
appsDiff: appsDiff ? wrapServerCryptContainer(appsDiff) : undefined
}
})
}
function wrapServerCryptContainer({ version, data }: { version: string, data: Buffer }): ServerCryptContainer {
return {
version,
data: data.toString('base64')
}
}
@@ -65,7 +65,8 @@ export async function getDeviceList ({ database, transaction, familyEntry }: {
wasAsEnabled: item.wasAsEnabled,
activityLevelBlocking: item.activityLevelBlocking,
qOrLater: item.isQorLater,
mFlags: item.manipulationFlags
mFlags: item.manipulationFlags,
pk: item.publicKey ? item.publicKey.toString('base64') : undefined
}))
}
}
@@ -26,25 +26,32 @@ import {
getCategoryAssignedApps, getCategoryBaseDatas, getCategoryDataToSync,
getRules, getTasks, getUsedTimes
} from './category'
import { getDeviceDetailList } from './device-detail'
import { getDeviceList } from './device-list'
import { getFamilyEntry } from './family-entry'
import { getUserList } from './user-list'
import { getKeyRequests } from './key-requests'
import { getKeyResponses } from './key-responses'
export const generateServerDataStatus = async ({ database, clientStatus, familyId, transaction }: {
export const generateServerDataStatus = async ({
database, clientStatus, familyId, deviceId, transaction
}: {
database: Database
clientStatus: ClientDataStatus
familyId: string
deviceId: string
transaction: Sequelize.Transaction
}): Promise<ServerDataStatus> => {
const familyEntry = await getFamilyEntry({ database, familyId, transaction })
const doesClientSupportTasks = clientStatus.clientLevel !== undefined && clientStatus.clientLevel >= 3
const doesClientSupportCryptoApps = clientStatus.clientLevel !== undefined && clientStatus.clientLevel >= 4
const result: ServerDataStatus = {
fullVersion: config.alwaysPro ? 1 : (
familyEntry.hasFullVersion ? parseInt(familyEntry.fullVersionUntil, 10) : 0
),
message: await getStatusMessage({ database, transaction }) || undefined,
apiLevel: 3
apiLevel: 4
}
if (familyEntry.deviceListVersion !== clientStatus.devices) {
@@ -103,5 +110,30 @@ export const generateServerDataStatus = async ({ database, clientStatus, familyI
})
}
if (doesClientSupportCryptoApps) {
result.devices2 = await getDeviceDetailList({
database,
transaction,
familyEntry,
devicesDetail: clientStatus.devicesDetail || {}
}) || undefined
result.krq = await getKeyRequests({
database,
transaction,
familyEntry,
deviceId,
lastSeenRequestIndex: clientStatus.kri || null
}) || undefined
result.kr = await getKeyResponses({
database,
transaction,
familyEntry,
deviceId,
lastSeenRequestIndex: clientStatus.kr || null
}) || undefined
}
return result
}
@@ -0,0 +1,58 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import * as Sequelize from 'sequelize'
import { Database } from '../../../database'
import { ServerKeyRequest } from '../../../object/serverdatastatus'
import { FamilyEntry } from './family-entry'
export async function getKeyRequests ({ database, transaction, familyEntry, lastSeenRequestIndex, deviceId }: {
database: Database
transaction: Sequelize.Transaction
familyEntry: FamilyEntry
lastSeenRequestIndex: number | null
deviceId: string
}): Promise<Array<ServerKeyRequest> | null> {
const data = await database.keyRequest.findAll({
where: {
familyId: familyEntry.familyId,
senderDeviceId: {
[Sequelize.Op.ne]: deviceId
},
...(lastSeenRequestIndex === null ? {} : {
serverSequenceNumber: {
[Sequelize.Op.gt]: lastSeenRequestIndex
}
})
},
transaction,
limit: 32
})
if (data.length === 0) return null
return data.map((item) => ({
srvSeq: parseInt(item.serverSequenceNumber),
senId: item.senderDeviceId,
senSeq: parseInt(item.senderSequenceNumber),
deviceId: item.deviceId || undefined,
categoryId: item.categoryId || undefined,
type: item.type,
tempKey: item.tempKey.toString('base64'),
signature: item.signature.toString('base64')
}))
}
@@ -0,0 +1,63 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 - 2022 Jonas Lochmann
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import * as Sequelize from 'sequelize'
import { Database } from '../../../database'
import { ServerKeyResponse } from '../../../object/serverdatastatus'
import { FamilyEntry } from './family-entry'
export async function getKeyResponses ({ database, transaction, familyEntry, lastSeenRequestIndex, deviceId }: {
database: Database
transaction: Sequelize.Transaction
familyEntry: FamilyEntry
lastSeenRequestIndex: number | null
deviceId: string
}): Promise<Array<ServerKeyResponse> | null> {
if (lastSeenRequestIndex !== null) {
await database.keyResponse.destroy({
where: {
familyId: familyEntry.familyId,
receiverDeviceId: deviceId,
replyServerSequenceNumber: {
[Sequelize.Op.lte]: lastSeenRequestIndex.toString(10)
}
},
transaction
})
}
const data = await database.keyResponse.findAll({
where: {
familyId: familyEntry.familyId,
receiverDeviceId: deviceId,
},
order: [['replyServerSequenceNumber', 'ASC']],
transaction,
limit: 32
})
if (data.length === 0) return null
return data.map((item) => ({
srvSeq: parseInt(item.replyServerSequenceNumber),
sender: item.senderDeviceId,
rqSeq: parseInt(item.requestClientSequenceNumber),
tempKey: item.tempKey.toString('base64'),
cryptKey: item.encryptedKey.toString('base64'),
signature: item.signature.toString('base64')
}))
}