All files / apps / api/src / app session-routes.ts

100% Statements 18/18
100% Branches 2/2
100% Functions 5/5
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46                  29x   29x     29x   29x         37x 37x   36x   36x       29x 1x   1x     29x 1x     29x 2x   1x    
import { ERROR_CODE, HTTP_STATUS, SESSION_API } from '@chattra/shared'
import { Hono } from 'hono'
import { getActor, requestContext } from '../server/auth/middleware'
import { bootstrap, endMySession, listMySessions, signOutEverywhere } from '../server/auth/service'
import { readBearer } from '../server/auth/tokens'
import { proxyAuthHelper } from '../server/firebase/client'
import { ApiHttpError, validate, type AppEnv } from '../server/http'
 
// Sign-in and sessions (design 4.1, 4.2, 5.1). Origin, rate limit and token run in routes.ts.
export const sessionRoutes = new Hono<AppEnv>()
 
const { bootstrap: bootstrapEndpoint, signOutEverywhere: signOutEndpoint, list, end } = SESSION_API
 
// Firebase's redirect helper, on our own domain (4.1); outside /api/*, so no token check.
sessionRoutes.all('/__/auth/*', (c) => proxyAuthHelper(c.env, c.req.raw))
 
sessionRoutes.on(
  bootstrapEndpoint.method,
  bootstrapEndpoint.path,
  validate('json', bootstrapEndpoint.body),
  async (c) => {
    const firebase = readBearer(c.req.header('authorization'))
    if (!firebase) throw new ApiHttpError(ERROR_CODE.unauthenticated, 'Sign in first')
 
    const { googleIdToken } = c.req.valid('json')
 
    return c.json(await bootstrap(c.env, { firebase, google: googleIdToken }, requestContext(c)))
  },
)
 
sessionRoutes.on(signOutEndpoint.method, signOutEndpoint.path, async (c) => {
  await signOutEverywhere(c.env, getActor(c), requestContext(c))
 
  return c.body(null, HTTP_STATUS.noContent)
})
 
sessionRoutes.on(list.method, list.path, validate('query', list.query), async (c) =>
  c.json(await listMySessions(c.env, getActor(c), c.req.valid('query'))),
)
 
sessionRoutes.on(end.method, end.path, validate('param', end.params), async (c) => {
  await endMySession(c.env, getActor(c), c.req.valid('param').id)
 
  return c.body(null, HTTP_STATUS.noContent)
})