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 | 70x 12x 12x 70x 70x 746x 746x 746x 746x 746x 328x 418x 746x 70x 1296x 70x 548x 548x 544x 4x 4x 70x 548x 618x 548x 548x 548x 548x 548x 618x 617x 618x 1x 617x 617x 1x 616x 548x 548x 547x 548x 1x 547x 547x 546x 1x 548x 548x 1x 1x 548x 618x 70x 678x 678x 57x 621x 621x 3x 618x 617x 70x 3x 1x 2x | import { TRPCError, initTRPC } from "@trpc/server";
import { performance } from "node:perf_hooks";
import { isNonNullish, unique } from "remeda";
import { AUTH_COOKIE } from "~app/utils/auth";
import {
PRETEND_USER_STORE_NAME,
pretendUserSchema,
} from "~app/utils/store/pretend-user";
import type { UserId } from "~db/ids";
import { transformer } from "~utils/transformer";
import {
SESSION_REFRESH_DURATION,
getExpirationDate,
} from "~web/handlers/auth/utils";
import { queueCallFactory } from "~web/handlers/batch";
import type {
HandlerMeta,
NetContext,
UnauthorizedContext,
} from "~web/handlers/context";
import { formatErrorMessage } from "~web/handlers/errors";
import { sessionIdSchema } from "~web/handlers/validation";
import { getCookie, setCookie } from "~web/utils/cookies";
export const t = initTRPC
.context<UnauthorizedContext>()
.meta<HandlerMeta>()
.create({
transformer,
errorFormatter: (opts) => {
const { shape, error, input } = opts;
return {
...shape,
message: formatErrorMessage(error, shape.message),
input,
};
},
defaultMeta: {
versions: [],
title:
"This is title stub, please add a `.meta()` to a handler emitting this",
description:
"This is a description stub, please add a `.meta()` to a handler emitting this",
},
});
const versionMiddleware = t.middleware(
async ({ meta, next, ctx, getRawInput }) => {
/* c8 ignore next */
if (meta?.versions) {
const appVersionHeader = ctx.reqHeaders.get("x-app-version");
const appVersion =
appVersionHeader === null ? undefined : Number(appVersionHeader);
if (appVersion === undefined || Number.isNaN(appVersion)) {
return next();
}
const appliedVersions = meta.versions.filter(
([maxVersion]) => appVersion < maxVersion,
);
if (appliedVersions.length === 0) {
return next();
}
let nextInput: unknown = await getRawInput();
for (const [maxVersion, schema] of appliedVersions) {
const result = await schema["~standard"].validate(nextInput);
if (result.issues) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Unable to migrate input to version ${maxVersion}`,
cause: result.issues,
});
}
nextInput = result.value;
}
return next({ getRawInput: () => Promise.resolve(nextInput) });
}
/* c8 ignore start */
return next();
/* c8 ignore stop */
},
);
export const unauthProcedure = t.procedure
.use(versionMiddleware)
.use(async ({ ctx, type, path, next }) => {
const start = performance.now();
const result = await next();
const duration = performance.now() - start;
const options = {
path,
type,
durationMs: duration,
};
if (result.ok) {
ctx.logger.trace(options, "OK request timing:");
} else {
ctx.logger.trace(options, "Non-OK request timing:");
}
return result;
});
const getAuthToken = (ctx: UnauthorizedContext) =>
getCookie(ctx.reqHeaders.get("cookie"), AUTH_COOKIE);
const getPretendUserEmail = (ctx: NetContext): string | undefined => {
const pretendUserString = getCookie(
ctx.reqHeaders.get("cookie"),
PRETEND_USER_STORE_NAME,
);
if (!pretendUserString) {
return;
}
const peer = pretendUserSchema.parse(JSON.parse(pretendUserString));
return peer.email;
};
const queueSession = queueCallFactory<
UnauthorizedContext,
{ authToken: string },
{
realAuth: {
userId: UserId;
email: string;
};
auth: {
userId: UserId;
email: string;
};
role: string | undefined;
}
>(
(ctx) => async (inputs) => {
const authTokens = unique(inputs.map(({ authToken }) => authToken));
const pretendUserEmail = getPretendUserEmail(ctx);
const [sessions, pretendUser] = await Promise.all([
ctx.database
.selectFrom("sessions")
.innerJoin("users", (qb) =>
qb.onRef("users.id", "=", "sessions.userId"),
)
.select([
"sessions.userId",
"users.email",
"users.role",
"sessions.expirationTimestamp",
"sessions.sessionId",
])
.where((eb) =>
eb("sessions.sessionId", "in", authTokens).and(
"sessions.expirationTimestamp",
">",
Temporal.Now.zonedDateTimeISO(),
),
)
.execute(),
pretendUserEmail
? ctx.database
.selectFrom("users")
.where("users.email", "=", pretendUserEmail)
.select(["users.id", "users.email"])
.limit(1)
.executeTakeFirst()
: undefined,
]);
const sessionsOrErrors = inputs.map((input) => {
const matchedSession = sessions.find(
(session) => session.sessionId === input.authToken,
);
if (!matchedSession) {
return new TRPCError({
code: "UNAUTHORIZED",
message: "Session id mismatch",
});
}
const auth = {
userId: matchedSession.userId,
email: matchedSession.email,
};
if (
pretendUser &&
matchedSession.role === "admin" &&
!ctx.reqHeaders.get("x-keep-real-auth")
) {
return {
realAuth: auth,
auth: {
userId: pretendUser.id,
email: pretendUser.email,
},
role: matchedSession.role,
};
}
return {
realAuth: auth,
auth,
role: matchedSession.role ?? undefined,
};
});
const updateableSessions = authTokens
.map((authToken) => {
const matchedSession = sessions.find(
(session) => session.sessionId === authToken,
);
if (!matchedSession) {
return undefined;
}
const refreshSessionTimestamp =
matchedSession.expirationTimestamp.subtract(SESSION_REFRESH_DURATION);
if (
Temporal.ZonedDateTime.compare(
Temporal.Now.zonedDateTimeISO(),
refreshSessionTimestamp,
) < 0
) {
return undefined;
}
return {
authToken,
nextExpirationTimestamp: getExpirationDate(),
};
})
.filter(isNonNullish);
await ctx.database.transaction().execute(async (tx) => {
await Promise.all(
updateableSessions.map(
async ({ authToken, nextExpirationTimestamp }) => {
await tx
.updateTable("sessions")
.set({ expirationTimestamp: nextExpirationTimestamp })
.where("sessionId", "=", authToken)
.executeTakeFirst();
setCookie(ctx, AUTH_COOKIE, authToken, {
expires: nextExpirationTimestamp,
});
},
),
);
});
return sessionsOrErrors;
},
{
getKey: (ctx) =>
[
// If we've got here, auth token surely exists
// oxlint-disable-next-line typescript/no-non-null-assertion
getAuthToken(ctx)!,
ctx.reqHeaders.get("x-keep-real-auth") ?? "",
]
.filter(Boolean)
.join("/"),
},
);
export const authProcedure = unauthProcedure.use(
async ({ ctx, next, path }) => {
const authToken = getAuthToken(ctx);
if (typeof authToken !== "string" || !authToken) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "No token provided",
});
}
const uuidVerification = sessionIdSchema.safeParse(authToken);
if (!uuidVerification.success) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Session id mismatch",
});
}
const { realAuth, auth, role } = await queueSession({
path,
ctx,
input: { authToken },
signal: new AbortController().signal,
});
return next({
ctx: {
...ctx,
logger: ctx.logger.child({ userId: auth.userId }),
realAuth,
auth,
authToken,
role,
},
});
},
);
export const adminProcedure = authProcedure.use(async ({ ctx, next }) => {
if (ctx.role !== "admin") {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Admin procedure is available only if you're an admin",
});
}
return next({ ctx: { ...ctx, auth: ctx.realAuth } });
});
|