Initial commit

This commit is contained in:
Jonas L
2019-02-25 00:00:00 +00:00
commit 22c372e246
200 changed files with 27781 additions and 0 deletions
+130
View File
@@ -0,0 +1,130 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 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 { json } from 'body-parser'
import { Router } from 'express'
import { OAuth2Client } from 'google-auth-library'
import { BadRequest } from 'http-errors'
import { Database } from '../database'
import { createAuthTokenByMailAddress } from '../function/authentication'
import { sendLoginCode, signInByMailCode } from '../function/authentication/login-by-mail'
import {
isSendMailLoginCodeRequest,
isSignInByMailCodeRequest,
isSignInWithGoogleRequest
} from './validator'
const CLIENT_ID = process.env.GOOGLE_SIGN_IN_CLIENT_ID || ''
const client = new OAuth2Client(CLIENT_ID)
const getMailByGoogleAuthToken = async (idToken: string) => {
const ticket = await client.verifyIdToken({
idToken,
audience: CLIENT_ID
})
if (!ticket) {
throw new BadRequest()
}
const payload = ticket.getPayload()
if (!payload) {
throw new BadRequest()
}
if (!payload.email_verified) {
throw new BadRequest()
}
const mail = payload.email
if (!mail) {
throw new BadRequest()
}
if (!(
mail.endsWith('@gmail.com') ||
mail.endsWith('@googlemail.com')
)) {
throw new BadRequest()
}
return mail
}
export const createAuthRouter = (database: Database) => {
const router = Router()
router.post('/sign-in-with-google', json(), async (req, res, next) => {
try {
if (!isSignInWithGoogleRequest(req.body)) {
res.sendStatus(400)
return
}
const { googleAuthToken } = req.body
const mail = await getMailByGoogleAuthToken(googleAuthToken)
const mailAuthToken = await createAuthTokenByMailAddress({ mail, database })
res.json({
mailAuthToken
})
} catch (ex) {
next(ex)
}
})
router.post('/send-mail-login-code', json(), async (req, res, next) => {
try {
if (!isSendMailLoginCodeRequest(req.body)) {
throw new BadRequest()
}
const { mailLoginToken } = await sendLoginCode({
mail: req.body.mail,
locale: req.body.locale,
database
})
res.json({ mailLoginToken })
} catch (ex) {
next(ex)
}
})
router.post('/sign-in-by-mail-code', json(), async (req, res, next) => {
try {
if (!isSignInByMailCodeRequest(req.body)) {
throw new BadRequest()
}
const { mailAuthToken } = await signInByMailCode({
receivedCode: req.body.receivedCode,
mailLoginToken: req.body.mailLoginToken,
database
})
res.json({ mailAuthToken })
} catch (ex) {
next(ex)
}
})
return router
}
+98
View File
@@ -0,0 +1,98 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 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 { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest } from 'http-errors'
import { Database } from '../database'
import { addChildDevice } from '../function/child/add-device'
import { logoutAtPrimaryDevice } from '../function/child/logout-at-primary-device'
import { setPrimaryDevice } from '../function/child/set-primary-device'
import { WebsocketApi } from '../websocket'
import { isRegisterChildDeviceRequest, isRequestWithAuthToken, isUpdatePrimaryDeviceRequest } from './validator'
export const createChildRouter = ({ database, websocket }: {
database: Database,
websocket: WebsocketApi
}) => {
const router = Router()
router.post('/add-device', json(), async (req, res, next) => {
try {
if (!isRegisterChildDeviceRequest(req.body)) {
throw new BadRequest()
}
const { deviceAuthToken, deviceId } = await addChildDevice({
request: req.body,
database,
websocket
})
res.json({
deviceAuthToken,
ownDeviceId: deviceId
})
} catch (ex) {
next(ex)
}
})
router.post('/update-primary-device', json(), async (req, res, next) => {
try {
if (!isUpdatePrimaryDeviceRequest(req.body)) {
throw new BadRequest()
}
const response = await setPrimaryDevice({
database,
deviceAuthToken: req.body.authToken,
currentUserId: req.body.currentUserId,
websocket,
action: req.body.action
})
res.json({
status: response
})
} catch (ex) {
next(ex)
}
})
router.post('/logout-at-primary-device', json(), async (req, res, next) => {
try {
if (!isRequestWithAuthToken(req.body)) {
throw new BadRequest()
}
await logoutAtPrimaryDevice({
deviceAuthToken: req.body.deviceAuthToken,
database,
websocket
})
res.json({
ok: true
})
} catch (ex) {
next(ex)
}
})
return router
}
+50
View File
@@ -0,0 +1,50 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 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 express from 'express'
import { VisibleConnectedDevicesManager } from '../connected-devices'
import { Database } from '../database'
import { WebsocketApi } from '../websocket'
import { createAuthRouter } from './auth'
import { createChildRouter } from './child'
import { createParentRouter } from './parent'
import { createPurchaseRouter } from './purchase'
import { createSyncRouter } from './sync'
export const createApi = ({ database, websocket, connectedDevicesManager }: {
database: Database
websocket: WebsocketApi
connectedDevicesManager: VisibleConnectedDevicesManager
}) => {
const app = express()
app.disable('x-powered-by')
app.get('/time', (req, res) => {
res.json({
ms: Date.now()
})
})
app.use('/auth', createAuthRouter(database))
app.use('/child', createChildRouter({ database, websocket }))
app.use('/parent', createParentRouter({ database, websocket }))
app.use('/purchase', createPurchaseRouter({ database, websocket }))
app.use('/sync', createSyncRouter({ database, websocket, connectedDevicesManager }))
return app
}
+257
View File
@@ -0,0 +1,257 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 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 { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest, Unauthorized } from 'http-errors'
import { Database } from '../database'
import { removeDevice } from '../function/device/remove-device'
import { canRecoverPassword } from '../function/parent/can-recover-password'
import { createAddDeviceToken } from '../function/parent/create-add-device-token'
import { createFamily } from '../function/parent/create-family'
import { getStatusByMailToken } from '../function/parent/get-status-by-mail-address'
import { linkMailAddress } from '../function/parent/link-mail-address'
import { recoverParentPassword } from '../function/parent/recover-parent-password'
import { signInIntoFamily } from '../function/parent/sign-in-into-family'
import { WebsocketApi } from '../websocket'
import {
isCanRecoverPasswordRequest, isCreateFamilyByMailTokenRequest,
isCreateRegisterDeviceTokenRequest, isLinkParentMailAddressRequest,
isMailAuthTokenRequestBody, isRecoverParentPasswordRequest,
isRemoveDeviceRequest, isSignIntoFamilyRequest
} from './validator'
export const createParentRouter = ({ database, websocket }: {database: Database, websocket: WebsocketApi}) => {
const router = Router()
router.post('/get-status-by-mail-address', json(), async (req, res, next) => {
try {
if (!isMailAuthTokenRequestBody(req.body)) {
throw new BadRequest()
}
const { mailAuthToken } = req.body
const { status, mail } = await getStatusByMailToken({ database, mailAuthToken })
res.json({ status, mail })
} catch (ex) {
next(ex)
}
})
router.post('/create-family', json(), async (req, res, next) => {
try {
if (!isCreateFamilyByMailTokenRequest(req.body)) {
throw new BadRequest()
}
const result = await createFamily({
database,
firstParentDevice: req.body.parentDevice,
mailAuthToken: req.body.mailAuthToken,
password: req.body.parentPassword,
deviceName: req.body.deviceName,
parentName: req.body.parentName,
timeZone: req.body.timeZone
})
res.json({
deviceAuthToken: result.deviceAuthToken,
ownDeviceId: result.deviceId
})
} catch (ex) {
next(ex)
}
})
router.post('/sign-in-into-family', json(), async (req, res, next) => {
try {
if (!isSignIntoFamilyRequest(req.body)) {
throw new BadRequest()
}
const result = await signInIntoFamily({
database,
newDeviceInfo: req.body.parentDevice,
mailAuthToken: req.body.mailAuthToken,
deviceName: req.body.deviceName,
websocket
})
res.json({
deviceAuthToken: result.deviceAuthToken,
ownDeviceId: result.deviceId
})
} catch (ex) {
next(ex)
}
})
router.post('/can-recover-password', json(), async (req, res, next) => {
try {
if (!isCanRecoverPasswordRequest(req.body)) {
throw new BadRequest()
}
const canRecover = await canRecoverPassword({
database,
parentUserId: req.body.parentUserId,
mailAuthToken: req.body.mailAuthToken
})
res.json({ canRecover })
} catch (ex) {
next(ex)
}
})
router.post('/recover-parent-password', json(), async (req, res, next) => {
try {
if (!isRecoverParentPasswordRequest(req.body)) {
throw new BadRequest()
}
await recoverParentPassword({
database,
websocket,
password: req.body.password,
mailAuthToken: req.body.mailAuthToken
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
async function assertAuthValidAndReturnDeviceEntry ({ deviceAuthToken, parentId, secondPasswordHash }: {
deviceAuthToken: string
parentId: string
secondPasswordHash: string
}) {
const deviceEntry = await database.device.findOne({
where: {
deviceAuthToken: deviceAuthToken
}
})
if (!deviceEntry) {
throw new Unauthorized()
}
if (secondPasswordHash === 'device') {
if (!deviceEntry.isUserKeptSignedIn) {
throw new Unauthorized()
}
const parentEntry = await database.user.findOne({
where: {
familyId: deviceEntry.familyId,
type: 'parent',
userId: deviceEntry.currentUserId
}
})
if (!parentEntry) {
throw new Unauthorized()
}
} else {
const parentEntry = await database.user.findOne({
where: {
familyId: deviceEntry.familyId,
type: 'parent',
userId: parentId,
secondPasswordHash: secondPasswordHash
}
})
if (!parentEntry) {
throw new Unauthorized()
}
}
return deviceEntry
}
router.post('/create-add-device-token', json(), async (req, res, next) => {
try {
if (!isCreateRegisterDeviceTokenRequest(req.body)) {
throw new BadRequest()
}
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentId,
secondPasswordHash: req.body.parentPasswordSecondHash
})
const { token, deviceId } = await createAddDeviceToken({ familyId: deviceEntry.familyId, database })
res.json({ token, deviceId })
} catch (ex) {
next(ex)
}
})
router.post('/link-mail-address', json(), async (req, res, next) => {
try {
if (!isLinkParentMailAddressRequest(req.body)) {
throw new BadRequest()
}
await linkMailAddress({
mailAuthToken: req.body.mailAuthToken,
deviceAuthToken: req.body.deviceAuthToken,
parentPasswordSecondHash: req.body.parentPasswordSecondHash,
parentUserId: req.body.parentUserId,
websocket,
database
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
router.post('/remove-device', json(), async (req, res, next) => {
try {
if (!isRemoveDeviceRequest(req.body)) {
throw new BadRequest()
}
const deviceEntry = await assertAuthValidAndReturnDeviceEntry({
deviceAuthToken: req.body.deviceAuthToken,
parentId: req.body.parentUserId,
secondPasswordHash: req.body.parentPasswordSecondHash
})
await removeDevice({
database,
familyId: deviceEntry.familyId,
deviceId: req.body.deviceId,
websocket
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
return router
}
+129
View File
@@ -0,0 +1,129 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 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 { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest, Conflict, Unauthorized } from 'http-errors'
import { Database } from '../database'
import {
addPurchase,
areGooglePlayPaymentsPossible,
canDoNextPurchase,
isGooglePlayPurchaseSignatureValid,
requireFamilyEntry
} from '../function/purchase'
import { WebsocketApi } from '../websocket'
import { isCanDoPurchaseRequest, isFinishPurchaseByGooglePlayRequest } from './validator'
export const createPurchaseRouter = ({ database, websocket }: {
database: Database
websocket: WebsocketApi
}) => {
const router = Router()
router.post('/can-do-purchase', json(), async (req, res, next) => {
if (!areGooglePlayPaymentsPossible) {
res.json({ canDoPurchase: 'no because not supported by the server' })
return
}
try {
if (!isCanDoPurchaseRequest(req.body)) {
throw new BadRequest()
}
const familyEntry = await requireFamilyEntry({
database,
deviceAuthToken: req.body.deviceAuthToken
})
const result = canDoNextPurchase({ fullVersionUntil: parseInt(familyEntry.fullVersionUntil, 10) })
res.json({
canDoPurchase: result ? 'yes' : 'no due to old purchase'
})
} catch (ex) {
next(ex)
}
})
router.post('/finish-purchase-by-google-play', json(), async (req, res, next) => {
try {
if (!isFinishPurchaseByGooglePlayRequest(req.body)) {
throw new BadRequest()
}
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
},
attributes: ['familyId']
})
if (!deviceEntryUnsafe) {
throw new Unauthorized()
}
const deviceEntry = {
familyId: deviceEntryUnsafe.familyId
}
if (!isGooglePlayPurchaseSignatureValid({
receipt: req.body.receipt,
signature: req.body.signature
})) {
throw new Conflict()
}
const receipt = JSON.parse(req.body.receipt)
if (typeof receipt !== 'object') {
throw new Conflict()
}
let type: 'month' | 'year'
if (receipt.productId === 'premium_year_2018') {
type = 'year'
} else if (receipt.productId === 'premium_month_2018') {
type = 'month'
} else {
throw new Conflict()
}
const orderId = receipt.orderId
if (typeof orderId !== 'string') {
throw new Conflict()
}
await addPurchase({
database,
familyId: deviceEntry.familyId,
type,
transactionId: orderId,
websocket
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
return router
}
+147
View File
@@ -0,0 +1,147 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 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 { ClientDataStatus } from '../object/clientdatastatus'
import { optionalPasswordRegex, optionalSaltRegex } from '../util/password'
export interface ClientPushChangesRequest {
deviceAuthToken: string
actions: Array<{
encodedAction: string
sequenceNumber: number
integrity: string
type: 'appLogic' | 'parent' | 'child'
userId: string
}>
}
export interface ClientPullChangesRequest {
deviceAuthToken: string
status: ClientDataStatus
}
export interface SignInWithGoogleRequest {
googleAuthToken: string
}
export interface MailAuthTokenRequestBody {
mailAuthToken: string
}
export interface NewDeviceInfo {
model: string
}
export interface ParentPassword {
hash: string
secondHash: string
secondSalt: string
}
export const assertParentPasswordValid = (password: ParentPassword) => {
if (password.hash === '' || password.secondHash === '' || password.secondSalt === '') {
throw new Error('missing fields at parent password')
}
if (!(optionalPasswordRegex.test(password.hash) && optionalPasswordRegex.test(password.secondHash) && optionalSaltRegex.test(password.secondSalt))) {
throw new Error('invalid parent password')
}
}
export interface CreateFamilyByMailTokenRequest {
mailAuthToken: string
parentPassword: ParentPassword
parentDevice: NewDeviceInfo
deviceName: string
timeZone: string
parentName: string
}
export interface SignIntoFamilyRequest {
mailAuthToken: string
parentDevice: NewDeviceInfo
deviceName: string
}
export interface RecoverParentPasswordRequest {
mailAuthToken: string
password: ParentPassword
}
export interface CanRecoverPasswordRequest {
mailAuthToken: string
parentUserId: string
}
export interface RegisterChildDeviceRequest {
registerToken: string
childDevice: NewDeviceInfo
deviceName: string
}
export interface CreateRegisterDeviceTokenRequest {
deviceAuthToken: string
parentId: string
parentPasswordSecondHash: string
}
export interface CanDoPurchaseRequest {
type: 'googleplay' | 'any'
deviceAuthToken: string
}
export interface FinishPurchaseByGooglePlayRequest {
deviceAuthToken: string
receipt: string
signature: string
}
export interface LinkParentMailAddressRequest {
mailAuthToken: string
deviceAuthToken: string
parentUserId: string
parentPasswordSecondHash: string
}
export interface UpdatePrimaryDeviceRequest {
action: 'set this device' | 'unset this device'
currentUserId: string
authToken: string
}
export interface RemoveDeviceRequest {
deviceAuthToken: string
parentUserId: string
parentPasswordSecondHash: string
deviceId: string
}
export interface RequestWithAuthToken {
deviceAuthToken: string
}
export interface SendMailLoginCodeRequest {
mail: string
locale: string
}
export interface SignInByMailCodeRequest {
mailLoginToken: string
receivedCode: string
}
export { SerializedParentAction, SerializedChildAction, SerializedAppLogicAction } from '../action/serialization'
+151
View File
@@ -0,0 +1,151 @@
/*
* server component for the TimeLimit App
* Copyright (C) 2019 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 { json } from 'body-parser'
import { Router } from 'express'
import { BadRequest, Unauthorized } from 'http-errors'
import { VisibleConnectedDevicesManager } from '../connected-devices'
import { Database } from '../database'
import { reportDeviceRemoved } from '../function/device/report-device-removed'
import { applyActionsFromDevice } from '../function/sync/apply-actions'
import { generateServerDataStatus } from '../function/sync/get-server-data-status'
import { WebsocketApi } from '../websocket'
import { isClientPullChangesRequest, isClientPushChangesRequest, isRequestWithAuthToken } from './validator'
const getRoundedTimestampForLastConnectivity = () => {
const now = Date.now()
return now - (now % (1000 * 60 * 60 * 12 /* 12 hours */))
}
export const createSyncRouter = ({ database, websocket, connectedDevicesManager }: {
database: Database
websocket: WebsocketApi
connectedDevicesManager: VisibleConnectedDevicesManager
}) => {
const router = Router()
router.post('/push-actions', json(), async (req, res, next) => {
try {
if (!isClientPushChangesRequest(req.body)) {
throw new BadRequest()
}
const { shouldDoFullSync } = await applyActionsFromDevice({
request: req.body,
database,
websocket,
connectedDevicesManager
})
res.json({
shouldDoFullSync
})
} catch (ex) {
next(ex)
}
})
router.post('/pull-status', json(), async (req, res, next) => {
try {
const { body } = req
if (!isClientPullChangesRequest(body)) {
throw new BadRequest()
}
await database.transaction(async (transaction) => {
const deviceEntryUnsafe = await database.device.findOne({
where: {
deviceAuthToken: body.deviceAuthToken
},
attributes: ['familyId', 'lastConnectivity'],
transaction
})
if (!deviceEntryUnsafe) {
throw new Unauthorized()
}
const { familyId, lastConnectivity } = deviceEntryUnsafe
const now = getRoundedTimestampForLastConnectivity()
if (parseInt(lastConnectivity, 10) !== now) {
await database.device.update({
lastConnectivity: now.toString(10)
}, {
where: {
deviceAuthToken: body.deviceAuthToken
},
transaction
})
}
const serverStatus = await generateServerDataStatus({
database,
familyId,
clientStatus: body.status,
transaction
})
res.json(serverStatus)
})
} catch (ex) {
next(ex)
}
})
router.post('/report-removed', json(), async (req, res, next) => {
try {
if (!isRequestWithAuthToken(req.body)) {
throw new BadRequest()
}
await reportDeviceRemoved({
database,
deviceAuthToken: req.body.deviceAuthToken,
websocket
})
res.json({ ok: true })
} catch (ex) {
next(ex)
}
})
router.post('/is-device-removed', json(), async (req, res, next) => {
try {
if (!isRequestWithAuthToken(req.body)) {
throw new BadRequest()
}
const removedEntry = await database.oldDevice.findOne({
where: {
deviceAuthToken: req.body.deviceAuthToken
}
})
res.json({
isDeviceRemoved: !!removedEntry
})
} catch (ex) {
next(ex)
}
})
return router
}
+1681
View File
File diff suppressed because it is too large Load Diff