2022-05-17 04:43:40 +00:00
|
|
|
import * as admin from 'firebase-admin'
|
2022-06-06 19:34:58 +00:00
|
|
|
import { logger } from 'firebase-functions/v2'
|
2022-06-17 03:57:03 +00:00
|
|
|
import { HttpsOptions, onRequest, Request } from 'firebase-functions/v2/https'
|
|
|
|
import { log } from './utils'
|
2022-05-26 21:37:51 +00:00
|
|
|
import { z } from 'zod'
|
2022-05-17 04:43:40 +00:00
|
|
|
|
2022-06-11 00:51:55 +00:00
|
|
|
import { PrivateUser } from '../../common/user'
|
2022-05-21 02:34:26 +00:00
|
|
|
import {
|
|
|
|
CORS_ORIGIN_MANIFOLD,
|
|
|
|
CORS_ORIGIN_LOCALHOST,
|
|
|
|
} from '../../common/envs/constants'
|
2022-05-17 04:43:40 +00:00
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
type Output = Record<string, unknown>
|
2022-06-11 00:51:55 +00:00
|
|
|
type AuthedUser = {
|
|
|
|
uid: string
|
|
|
|
creds: JwtCredentials | (KeyCredentials & { privateUser: PrivateUser })
|
|
|
|
}
|
2022-05-26 21:37:51 +00:00
|
|
|
type Handler = (req: Request, user: AuthedUser) => Promise<Output>
|
2022-05-17 04:43:40 +00:00
|
|
|
type JwtCredentials = { kind: 'jwt'; data: admin.auth.DecodedIdToken }
|
|
|
|
type KeyCredentials = { kind: 'key'; data: string }
|
|
|
|
type Credentials = JwtCredentials | KeyCredentials
|
|
|
|
|
|
|
|
export class APIError {
|
|
|
|
code: number
|
|
|
|
msg: string
|
2022-05-26 21:37:51 +00:00
|
|
|
details: unknown
|
|
|
|
constructor(code: number, msg: string, details?: unknown) {
|
2022-05-17 04:43:40 +00:00
|
|
|
this.code = code
|
|
|
|
this.msg = msg
|
2022-05-26 21:37:51 +00:00
|
|
|
this.details = details
|
2022-05-17 04:43:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-17 03:57:03 +00:00
|
|
|
const auth = admin.auth()
|
|
|
|
const firestore = admin.firestore()
|
|
|
|
const privateUsers = firestore.collection(
|
|
|
|
'private-users'
|
|
|
|
) as admin.firestore.CollectionReference<PrivateUser>
|
|
|
|
|
2022-05-17 04:43:40 +00:00
|
|
|
export const parseCredentials = async (req: Request): Promise<Credentials> => {
|
|
|
|
const authHeader = req.get('Authorization')
|
|
|
|
if (!authHeader) {
|
|
|
|
throw new APIError(403, 'Missing Authorization header.')
|
|
|
|
}
|
|
|
|
const authParts = authHeader.split(' ')
|
|
|
|
if (authParts.length !== 2) {
|
|
|
|
throw new APIError(403, 'Invalid Authorization header.')
|
|
|
|
}
|
|
|
|
|
|
|
|
const [scheme, payload] = authParts
|
|
|
|
switch (scheme) {
|
|
|
|
case 'Bearer':
|
|
|
|
try {
|
2022-06-17 03:57:03 +00:00
|
|
|
return { kind: 'jwt', data: await auth.verifyIdToken(payload) }
|
2022-05-17 04:43:40 +00:00
|
|
|
} catch (err) {
|
|
|
|
// This is somewhat suspicious, so get it into the firebase console
|
2022-06-06 19:34:58 +00:00
|
|
|
logger.error('Error verifying Firebase JWT: ', err)
|
2022-05-26 21:37:51 +00:00
|
|
|
throw new APIError(403, 'Error validating token.')
|
2022-05-17 04:43:40 +00:00
|
|
|
}
|
|
|
|
case 'Key':
|
|
|
|
return { kind: 'key', data: payload }
|
|
|
|
default:
|
|
|
|
throw new APIError(403, 'Invalid auth scheme; must be "Key" or "Bearer".')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const lookupUser = async (creds: Credentials): Promise<AuthedUser> => {
|
|
|
|
switch (creds.kind) {
|
|
|
|
case 'jwt': {
|
2022-06-11 00:51:55 +00:00
|
|
|
if (typeof creds.data.user_id !== 'string') {
|
2022-05-26 21:37:51 +00:00
|
|
|
throw new APIError(403, 'JWT must contain Manifold user ID.')
|
|
|
|
}
|
2022-06-11 00:51:55 +00:00
|
|
|
return { uid: creds.data.user_id, creds }
|
2022-05-17 04:43:40 +00:00
|
|
|
}
|
|
|
|
case 'key': {
|
|
|
|
const key = creds.data
|
|
|
|
const privateUserQ = await privateUsers.where('apiKey', '==', key).get()
|
|
|
|
if (privateUserQ.empty) {
|
|
|
|
throw new APIError(403, `No private user exists with API key ${key}.`)
|
|
|
|
}
|
2022-06-17 03:57:03 +00:00
|
|
|
const privateUser = privateUserQ.docs[0].data()
|
2022-06-11 00:51:55 +00:00
|
|
|
return { uid: privateUser.id, creds: { privateUser, ...creds } }
|
2022-05-17 04:43:40 +00:00
|
|
|
}
|
|
|
|
default:
|
|
|
|
throw new APIError(500, 'Invalid credential type.')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
export const zTimestamp = () => {
|
|
|
|
return z.preprocess((arg) => {
|
|
|
|
return typeof arg == 'number' ? new Date(arg) : undefined
|
|
|
|
}, z.date())
|
|
|
|
}
|
|
|
|
|
|
|
|
export const validate = <T extends z.ZodTypeAny>(schema: T, val: unknown) => {
|
|
|
|
const result = schema.safeParse(val)
|
|
|
|
if (!result.success) {
|
|
|
|
const issues = result.error.issues.map((i) => {
|
2022-06-22 16:35:50 +00:00
|
|
|
// TODO: export this type for the front-end to parse
|
2022-05-26 21:37:51 +00:00
|
|
|
return {
|
|
|
|
field: i.path.join('.') || null,
|
|
|
|
error: i.message,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
throw new APIError(400, 'Error validating request.', issues)
|
|
|
|
} else {
|
|
|
|
return result.data as z.infer<T>
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-17 03:57:03 +00:00
|
|
|
const DEFAULT_OPTS: HttpsOptions = {
|
|
|
|
minInstances: 1,
|
|
|
|
cors: [CORS_ORIGIN_MANIFOLD, CORS_ORIGIN_LOCALHOST],
|
|
|
|
}
|
|
|
|
|
2022-05-17 04:43:40 +00:00
|
|
|
export const newEndpoint = (methods: [string], fn: Handler) =>
|
2022-06-17 03:57:03 +00:00
|
|
|
onRequest(DEFAULT_OPTS, async (req, res) => {
|
|
|
|
log('Request processing started.')
|
2022-05-17 04:43:40 +00:00
|
|
|
try {
|
|
|
|
if (!methods.includes(req.method)) {
|
|
|
|
const allowed = methods.join(', ')
|
|
|
|
throw new APIError(405, `This endpoint supports only ${allowed}.`)
|
|
|
|
}
|
2022-05-26 21:37:51 +00:00
|
|
|
const authedUser = await lookupUser(await parseCredentials(req))
|
2022-06-17 03:57:03 +00:00
|
|
|
log('User credentials processed.')
|
2022-05-26 21:37:51 +00:00
|
|
|
res.status(200).json(await fn(req, authedUser))
|
2022-05-17 04:43:40 +00:00
|
|
|
} catch (e) {
|
|
|
|
if (e instanceof APIError) {
|
2022-05-26 21:37:51 +00:00
|
|
|
const output: { [k: string]: unknown } = { message: e.msg }
|
|
|
|
if (e.details != null) {
|
|
|
|
output.details = e.details
|
|
|
|
}
|
|
|
|
res.status(e.code).json(output)
|
2022-05-17 04:43:40 +00:00
|
|
|
} else {
|
2022-06-06 19:34:58 +00:00
|
|
|
logger.error(e)
|
2022-05-20 21:58:14 +00:00
|
|
|
res.status(500).json({ message: 'An unknown error occurred.' })
|
2022-05-17 04:43:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|