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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | 29x 9x 9x 8x 2x 8x 1x 115x 5x 1x 4x 4x 4x 4x 3x 3x 2x 2x 45x 45x 45x 4x 4x 41x 41x 41x 41x 41x 41x 41x 41x 3x 3x 2x 1x 1x 38x 38x 53x 52x 1x 51x 51x 1x 50x 49x 49x 70x 70x 70x 70x 68x 1x 67x 6x 61x 61x 61x 1x 1x 61x 5x 5x 5x 4x 5x 5x 3x 3x 3x 3x 3x 3x | import {
AUTH_ERROR_CODE,
ERROR_CODE,
fold,
type BootstrapResponse,
type Me,
type SessionListQuery,
type SessionPage,
} from '@chattra/shared'
import { mainDb } from '../../db/client'
import { newId } from '../../lib/id'
import { log } from '../../lib/log'
import { deleteFirebaseAccount, revokeFirebaseTokens } from '../firebase/client'
import { ApiHttpError, type ApiErrorCode } from '../http'
import type { Actor } from '../permission/service'
import { isWithinBootstrapLimit } from '../ratelimit/client'
import {
createPerson,
endAllSessions,
endSession,
findActor,
findSignInTarget,
findUserByGoogleSub,
isEmailTaken,
listOpenSessions,
touchSession,
updateSignIn,
upsertSession,
type UserRow,
} from './repository'
import {
verifyFirebaseToken,
verifyGoogleToken,
type FirebaseIdentity,
type GoogleIdentity,
} from './tokens'
// Sign-in and the token check (design 4.1, 4.2). Every refusal is one structured log line.
/** last_seen_at moves at most this often (design 4.2). */
export const SESSION_TOUCH_MS = 10 * 60 * 1000
export interface RequestContext {
requestId: string
device: string | null
ip: string | null
/** c.executionCtx.waitUntil, for work that follows the response. */
waitUntil: (promise: Promise<unknown>) => void
}
function refuse(context: RequestContext, code: ApiErrorCode, uid: string): ApiHttpError {
// The IP is logged on purpose: a refused sign-in is a security event (design #17).
log('warn', { event: 'sign_in_refused', requestId: context.requestId, code, uid, ip: context.ip })
return new ApiHttpError(code, 'Sign-in refused')
}
function sessionEnded(): ApiHttpError {
return new ApiHttpError(AUTH_ERROR_CODE.sessionEnded, 'Session ended, sign in again')
}
function toMe(user: UserRow): Me {
return {
id: user.id,
workspaceId: user.workspaceId,
email: user.email,
displayName: user.displayName,
avatarUrl: user.avatarUrl,
role: user.role,
}
}
function inBackground(context: RequestContext, event: string, work: () => Promise<void>): void {
context.waitUntil(
work().catch((error: unknown) => {
log('error', { event, requestId: context.requestId, message: String(error) })
}),
)
}
/** Session times are ms; Firebase's auth_time is seconds. */
const toMs = (seconds: number): number => seconds * 1000
async function signInExisting(
env: Env,
user: UserRow,
firebase: FirebaseIdentity,
context: RequestContext,
): Promise<BootstrapResponse> {
if (user.status === 'deactivated') {
throw refuse(context, AUTH_ERROR_CODE.accountDeactivated, firebase.uid)
}
const db = mainDb(env)
const now = Date.now()
const authTime = toMs(firebase.authTime)
// An ended session or one before the cut-off is never revived by signing in with the same token.
if (authTime < user.tokensValidAfter) throw sessionEnded()
const session = await upsertSession(db, {
id: newId(now),
userId: user.id,
authTime,
device: context.device,
ip: context.ip,
createdAt: now,
lastSeenAt: now,
})
if (!session || session.endedAt !== null) throw sessionEnded()
await updateSignIn(db, user.id, { firebaseUid: firebase.uid, at: now })
return {
user: toMe({ ...user, firebaseUid: firebase.uid, lastSignInAt: now }),
sessionId: session.id,
}
}
async function signInNew(
env: Env,
firebase: FirebaseIdentity,
google: GoogleIdentity,
context: RequestContext,
): Promise<BootstrapResponse> {
const db = mainDb(env)
// hd, not the email's domain: only Google Workspace accounts carry it (design 4.1).
const target = google.hd ? await findSignInTarget(db, google.hd) : undefined
if (!target) {
inBackground(context, 'firebase_delete_failed', () => deleteFirebaseAccount(env, firebase.uid))
throw refuse(context, AUTH_ERROR_CODE.domainNotAllowed, firebase.uid)
}
const now = Date.now()
const id = newId(now)
const isOwner =
target.ownerId === null && google.email.toLowerCase() === env.OWNER_EMAIL?.toLowerCase()
const displayName = google.name ?? google.email
const user = {
id,
workspaceId: target.workspaceId,
email: google.email,
firebaseUid: firebase.uid,
googleSub: google.sub,
displayName,
displayNameFolded: fold(displayName),
avatarUrl: google.picture ?? null,
role: isOwner ? ('owner' as const) : ('member' as const),
lastSignInAt: now,
createdAt: now,
}
const session = {
id: newId(now),
userId: id,
authTime: toMs(firebase.authTime),
device: context.device,
ip: context.ip,
createdAt: now,
lastSeenAt: now,
}
try {
await createPerson(db, { user, session, generalId: target.generalId })
} catch (error) {
// Two first sign-ins at once: the other one created the person, so this becomes a return visit.
const created = await findUserByGoogleSub(db, google.sub)
if (created) return signInExisting(env, created, firebase, context)
// A Google account recreated with its old email has a new sub (someone who left and came
// back). Relinking is an admin's call, not automatic: the email alone must not hand over a
// person's history. Until then the answer is a code the web can explain, not a 500.
if (await isEmailTaken(db, google.email)) {
throw refuse(context, AUTH_ERROR_CODE.emailInUse, firebase.uid)
}
throw error
}
log('info', {
event: 'person_created',
requestId: context.requestId,
userId: id,
role: user.role,
})
return {
user: {
id,
workspaceId: user.workspaceId,
email: user.email,
displayName,
avatarUrl: user.avatarUrl,
role: user.role,
},
sessionId: session.id,
}
}
/** POST /api/session/bootstrap (design 4.1, B3). */
export async function bootstrap(
env: Env,
tokens: { firebase: string; google: string },
context: RequestContext,
): Promise<BootstrapResponse> {
const firebase = await verifyFirebaseToken(env, tokens.firebase)
if (!(await isWithinBootstrapLimit(env, firebase.uid))) {
throw refuse(context, ERROR_CODE.rateLimited, firebase.uid)
}
const google = await verifyGoogleToken(env, tokens.google)
// Both tokens must be the same Google account, or someone could pair theirs with another's.
if (google.sub !== firebase.googleSub) {
throw refuse(context, AUTH_ERROR_CODE.invalidToken, firebase.uid)
}
if (!google.emailVerified) throw refuse(context, AUTH_ERROR_CODE.emailNotVerified, firebase.uid)
// Removing a domain later leaves its people active (5.1), so a known person skips the domain check.
const existing = await findUserByGoogleSub(mainDb(env), google.sub)
return existing
? signInExisting(env, existing, firebase, context)
: signInNew(env, firebase, google, context)
}
/** The token check on every data request: one verify, one D1 read (design 4.2, B5). */
export async function authenticate(
env: Env,
token: string,
context: RequestContext,
): Promise<Actor> {
const firebase = await verifyFirebaseToken(env, token)
const authTime = toMs(firebase.authTime)
const row = await findActor(mainDb(env), firebase.uid, authTime)
if (!row) throw new ApiHttpError(AUTH_ERROR_CODE.notRegistered, 'Not signed up')
if (row.status === 'deactivated') {
throw new ApiHttpError(AUTH_ERROR_CODE.accountDeactivated, 'Account deactivated')
}
if (authTime < row.tokensValidAfter || row.sessionId === null || row.sessionEndedAt !== null) {
throw sessionEnded()
}
const { sessionId, userId } = row
const now = Date.now()
if (now - (row.sessionLastSeenAt ?? 0) > SESSION_TOUCH_MS) {
inBackground(context, 'session_touch_failed', () =>
touchSession(mainDb(env), { userId, sessionId, at: now }),
)
}
return {
userId,
workspaceId: row.workspaceId,
role: row.role,
sessionId,
firebaseUid: firebase.uid,
}
}
/** GET /api/sessions (AUTH-3, B4). */
export async function listMySessions(
env: Env,
actor: Actor,
query: SessionListQuery,
): Promise<SessionPage> {
const rows = await listOpenSessions(mainDb(env), actor.userId, {
limit: query.limit + 1,
cursor: query.cursor,
})
const page = rows.slice(0, query.limit)
return {
sessions: page.map((row) => ({
id: row.id,
device: row.device,
createdAt: row.createdAt,
lastSeenAt: row.lastSeenAt,
current: row.id === actor.sessionId,
})),
nextCursor: rows.length > query.limit ? (page.at(-1)?.id ?? null) : null,
}
}
/** DELETE /api/sessions/:id: another person's id answers the same 404 as a missing one. */
export async function endMySession(env: Env, actor: Actor, sessionId: string): Promise<void> {
const isMine = await endSession(mainDb(env), actor.userId, sessionId, Date.now())
if (!isMine) throw new ApiHttpError(ERROR_CODE.notFound, 'Session not found')
}
/** POST /api/session/sign-out-everywhere (AUTH-3, B5). */
export async function signOutEverywhere(
env: Env,
actor: Actor,
context: RequestContext,
): Promise<void> {
const now = Date.now()
// auth_time has second precision, so the cut-off is a whole second: a sign-in in the same second
// as this call is ended by its session row, and one after it is allowed.
const validAfter = now - (now % 1000)
await endAllSessions(mainDb(env), actor.userId, { at: now, validAfter })
log('info', {
event: 'signed_out_everywhere',
requestId: context.requestId,
userId: actor.userId,
})
inBackground(context, 'firebase_revoke_failed', () =>
revokeFirebaseTokens(env, actor.firebaseUid, validAfter),
)
}
|