Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+192
@@ -0,0 +1,192 @@
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
|
||||
import { redirect } from "react-router";
|
||||
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
|
||||
import { safeSessionRedirectTarget } from "~/utils/app/SessionRedirectSafety.server";
|
||||
import { getHostRoutingContext, getRequestRoutingHost } from "~/utils/app/HostRouting.server";
|
||||
import { createUserSession, type UserSession } from "~/utils/session.server";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
|
||||
export const SESSION_HANDOFF_TTL_SECONDS = 60;
|
||||
export const SESSION_HANDOFF_PATH = "/auth/session-handoff";
|
||||
|
||||
const CONSUME_SCRIPT = `
|
||||
local value = redis.call('GET', KEYS[1])
|
||||
if value then
|
||||
redis.call('DEL', KEYS[1])
|
||||
end
|
||||
return value
|
||||
`;
|
||||
|
||||
MemoryAdapter.registerScript(CONSUME_SCRIPT, async (adapter, keys) => {
|
||||
const key = keys[0];
|
||||
if (!key) return null;
|
||||
const value = await adapter.get(key);
|
||||
if (value !== null) await adapter.del(key);
|
||||
return value;
|
||||
});
|
||||
|
||||
type SessionHandoffPayload = {
|
||||
createdAt: number;
|
||||
userAgentHash: string;
|
||||
redirectTo: string;
|
||||
session: UserSession;
|
||||
};
|
||||
|
||||
let storeFactory: () => SharedStore = () => getSharedStore();
|
||||
let memoryConsumeQueue: Promise<void> = Promise.resolve();
|
||||
|
||||
function codeKey(code: string) {
|
||||
return `auth:session-handoff:${createHash("sha256").update(code).digest("hex")}`;
|
||||
}
|
||||
|
||||
function signPayload(code: string, payload: string) {
|
||||
return createHmac("sha256", code).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
function safeSignatureMatch(actual: string, expected: string) {
|
||||
const actualBytes = Buffer.from(actual);
|
||||
const expectedBytes = Buffer.from(expected);
|
||||
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
|
||||
}
|
||||
|
||||
function userAgentHash(request: Request) {
|
||||
return createHash("sha256")
|
||||
.update(request.headers.get("user-agent") ?? "")
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
function transferableSession(session: UserSession): UserSession {
|
||||
return {
|
||||
userId: session.userId,
|
||||
lightOrDarkMode: session.lightOrDarkMode,
|
||||
lng: session.lng,
|
||||
// The destination host receives a fresh CSRF token from its root loader;
|
||||
// never carry the admin-host token across the trust boundary.
|
||||
csrf: undefined,
|
||||
cookies: session.cookies,
|
||||
metrics: session.metrics,
|
||||
impersonatingFromUserId: session.impersonatingFromUserId,
|
||||
impersonatingFromAdminUserId: session.impersonatingFromAdminUserId,
|
||||
impersonatingFromAdminEmail: session.impersonatingFromAdminEmail,
|
||||
impersonatingStartedAt: session.impersonatingStartedAt,
|
||||
theme: session.theme,
|
||||
passwordPolicyOutdated: session.passwordPolicyOutdated,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createSessionHandoffRedirect({
|
||||
request,
|
||||
session,
|
||||
redirectTo,
|
||||
}: {
|
||||
request: Request;
|
||||
session: UserSession;
|
||||
redirectTo: string;
|
||||
}): Promise<Response> {
|
||||
const routing = loadRequiredWebConfig().routing;
|
||||
const safeRedirectTo = safeSessionRedirectTarget(redirectTo, routing);
|
||||
const appOrigin = new URL(`${routing.protocol}://${routing.webAppHost}`).origin;
|
||||
if (!safeRedirectTo.startsWith(`${appOrigin}/`)) {
|
||||
throw new Error("Session handoff requires a canonical app-host redirect target");
|
||||
}
|
||||
|
||||
const code = randomBytes(32).toString("base64url");
|
||||
const payload: SessionHandoffPayload = {
|
||||
createdAt: Date.now(),
|
||||
userAgentHash: userAgentHash(request),
|
||||
redirectTo: safeRedirectTo,
|
||||
session: transferableSession(session),
|
||||
};
|
||||
const serializedPayload = JSON.stringify(payload);
|
||||
const stored = await storeFactory().set(codeKey(code), JSON.stringify({ payload: serializedPayload, signature: signPayload(code, serializedPayload) }), {
|
||||
ttlSeconds: SESSION_HANDOFF_TTL_SECONDS,
|
||||
nx: true,
|
||||
});
|
||||
if (!stored) {
|
||||
throw new Error("Could not reserve one-time session handoff code");
|
||||
}
|
||||
|
||||
const target = new URL(absolutePublicAppPath(routing, SESSION_HANDOFF_PATH));
|
||||
target.searchParams.set("code", code);
|
||||
return redirect(target.toString(), {
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function consumeSessionHandoff(request: Request, code: string | null | undefined): Promise<Response | null> {
|
||||
if (!code || !/^[A-Za-z0-9_-]{43}$/.test(code)) {
|
||||
return null;
|
||||
}
|
||||
const routing = loadRequiredWebConfig().routing;
|
||||
const requestUrl = new URL(request.url);
|
||||
if (getHostRoutingContext(getRequestRoutingHost(request, requestUrl, routing), routing) !== "app") {
|
||||
return null;
|
||||
}
|
||||
const store = storeFactory();
|
||||
const consume = () => store.adapter.eval(CONSUME_SCRIPT, [store.key(codeKey(code))], []);
|
||||
let raw: unknown;
|
||||
if (store.adapter instanceof MemoryAdapter) {
|
||||
// Redis runs the Lua script atomically. Serialize the development/test
|
||||
// adapter too so concurrent consumers observe the same single-use rule.
|
||||
const queued = memoryConsumeQueue.then(consume);
|
||||
memoryConsumeQueue = queued.then(
|
||||
() => undefined,
|
||||
() => undefined
|
||||
);
|
||||
raw = await queued;
|
||||
} else {
|
||||
raw = await consume();
|
||||
}
|
||||
if (typeof raw !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
let payload: SessionHandoffPayload;
|
||||
try {
|
||||
const envelope = JSON.parse(raw) as { payload?: unknown; signature?: unknown };
|
||||
if (
|
||||
typeof envelope.payload !== "string" ||
|
||||
typeof envelope.signature !== "string" ||
|
||||
!safeSignatureMatch(envelope.signature, signPayload(code, envelope.payload))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
payload = JSON.parse(envelope.payload) as SessionHandoffPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const ageMs = Date.now() - payload.createdAt;
|
||||
if (
|
||||
!Number.isFinite(payload.createdAt) ||
|
||||
ageMs < 0 ||
|
||||
ageMs >= SESSION_HANDOFF_TTL_SECONDS * 1000 ||
|
||||
payload.userAgentHash !== userAgentHash(request) ||
|
||||
typeof payload.redirectTo !== "string" ||
|
||||
!payload.session ||
|
||||
typeof payload.session.userId !== "string"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const response = await createUserSession(payload.session, payload.redirectTo, { request, rotate: true });
|
||||
const headers = new Headers(response.headers);
|
||||
headers.set("Cache-Control", "no-store");
|
||||
headers.set("Referrer-Policy", "no-referrer");
|
||||
return new Response(response.body, { status: response.status, headers });
|
||||
}
|
||||
|
||||
export function __setSessionHandoffStoreForTests(store: SharedStore): void {
|
||||
storeFactory = () => store;
|
||||
}
|
||||
|
||||
export function __resetSessionHandoffStoreForTests(): void {
|
||||
storeFactory = () => getSharedStore();
|
||||
memoryConsumeQueue = Promise.resolve();
|
||||
}
|
||||
Reference in new issue
Block a user