mirror of
https://github.com/fosrl/pangolin.git
synced 2025-07-25 21:25:06 +02:00
set resource session cookie in proxy via param
This commit is contained in:
parent
34c9093469
commit
d7c4bc43a4
12 changed files with 143 additions and 81 deletions
|
@ -2,6 +2,7 @@ app:
|
|||
base_url: http://localhost:3000
|
||||
log_level: warning
|
||||
save_logs: false
|
||||
sessionCookieName: session
|
||||
|
||||
server:
|
||||
external_port: 3000
|
||||
|
@ -14,6 +15,10 @@ traefik:
|
|||
http_entrypoint: web
|
||||
https_entrypoint: websecure
|
||||
|
||||
badger:
|
||||
session_query_parameter: __pang_sess
|
||||
resource_session_cookie_name: resource_session
|
||||
|
||||
gerbil:
|
||||
start_port: 51820
|
||||
base_endpoint: localhost
|
||||
|
|
|
@ -13,7 +13,7 @@ import config from "@server/config";
|
|||
import type { RandomReader } from "@oslojs/crypto/random";
|
||||
import { generateRandomString } from "@oslojs/crypto/random";
|
||||
|
||||
export const SESSION_COOKIE_NAME = "session";
|
||||
export const SESSION_COOKIE_NAME = config.server.session_cookie_name;
|
||||
export const SESSION_COOKIE_EXPIRES = 1000 * 60 * 60 * 24 * 30;
|
||||
export const SECURE_COOKIES = config.server.secure_cookies;
|
||||
export const COOKIE_DOMAIN =
|
||||
|
@ -63,7 +63,7 @@ export async function validateSessionToken(
|
|||
.where(eq(sessions.sessionId, session.sessionId));
|
||||
return { session: null, user: null };
|
||||
}
|
||||
if (Date.now() >= session.expiresAt - (SESSION_COOKIE_EXPIRES / 2)) {
|
||||
if (Date.now() >= session.expiresAt - SESSION_COOKIE_EXPIRES / 2) {
|
||||
session.expiresAt = new Date(
|
||||
Date.now() + SESSION_COOKIE_EXPIRES,
|
||||
).getTime();
|
||||
|
|
|
@ -15,12 +15,12 @@ export async function createResourceSession(opts: {
|
|||
}): Promise<ResourceSession> {
|
||||
if (!opts.passwordId && !opts.pincodeId) {
|
||||
throw new Error(
|
||||
"At least one of passwordId or pincodeId must be provided"
|
||||
"At least one of passwordId or pincodeId must be provided",
|
||||
);
|
||||
}
|
||||
|
||||
const sessionId = encodeHexLowerCase(
|
||||
sha256(new TextEncoder().encode(opts.token))
|
||||
sha256(new TextEncoder().encode(opts.token)),
|
||||
);
|
||||
|
||||
const session: ResourceSession = {
|
||||
|
@ -38,10 +38,10 @@ export async function createResourceSession(opts: {
|
|||
|
||||
export async function validateResourceSessionToken(
|
||||
token: string,
|
||||
resourceId: number
|
||||
resourceId: number,
|
||||
): Promise<ResourceSessionValidationResult> {
|
||||
const sessionId = encodeHexLowerCase(
|
||||
sha256(new TextEncoder().encode(token))
|
||||
sha256(new TextEncoder().encode(token)),
|
||||
);
|
||||
const result = await db
|
||||
.select()
|
||||
|
@ -49,8 +49,8 @@ export async function validateResourceSessionToken(
|
|||
.where(
|
||||
and(
|
||||
eq(resourceSessions.sessionId, sessionId),
|
||||
eq(resourceSessions.resourceId, resourceId)
|
||||
)
|
||||
eq(resourceSessions.resourceId, resourceId),
|
||||
),
|
||||
);
|
||||
|
||||
if (result.length < 1) {
|
||||
|
@ -61,7 +61,7 @@ export async function validateResourceSessionToken(
|
|||
|
||||
if (Date.now() >= resourceSession.expiresAt - SESSION_COOKIE_EXPIRES / 2) {
|
||||
resourceSession.expiresAt = new Date(
|
||||
Date.now() + SESSION_COOKIE_EXPIRES
|
||||
Date.now() + SESSION_COOKIE_EXPIRES,
|
||||
).getTime();
|
||||
await db
|
||||
.update(resourceSessions)
|
||||
|
@ -75,7 +75,7 @@ export async function validateResourceSessionToken(
|
|||
}
|
||||
|
||||
export async function invalidateResourceSession(
|
||||
sessionId: string
|
||||
sessionId: string,
|
||||
): Promise<void> {
|
||||
await db
|
||||
.delete(resourceSessions)
|
||||
|
@ -87,7 +87,7 @@ export async function invalidateAllSessions(
|
|||
method?: {
|
||||
passwordId?: number;
|
||||
pincodeId?: number;
|
||||
}
|
||||
},
|
||||
): Promise<void> {
|
||||
if (method?.passwordId) {
|
||||
await db
|
||||
|
@ -95,8 +95,8 @@ export async function invalidateAllSessions(
|
|||
.where(
|
||||
and(
|
||||
eq(resourceSessions.resourceId, resourceId),
|
||||
eq(resourceSessions.passwordId, method.passwordId)
|
||||
)
|
||||
eq(resourceSessions.passwordId, method.passwordId),
|
||||
),
|
||||
);
|
||||
} else if (method?.pincodeId) {
|
||||
await db
|
||||
|
@ -104,8 +104,8 @@ export async function invalidateAllSessions(
|
|||
.where(
|
||||
and(
|
||||
eq(resourceSessions.resourceId, resourceId),
|
||||
eq(resourceSessions.pincodeId, method.pincodeId)
|
||||
)
|
||||
eq(resourceSessions.pincodeId, method.pincodeId),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
await db
|
||||
|
@ -117,18 +117,18 @@ export async function invalidateAllSessions(
|
|||
export function serializeResourceSessionCookie(
|
||||
token: string,
|
||||
fqdn: string,
|
||||
secure: boolean
|
||||
secure: boolean,
|
||||
): string {
|
||||
if (secure) {
|
||||
return `${SESSION_COOKIE_NAME}=${token}; HttpOnly; SameSite=Lax; Max-Age=${SESSION_COOKIE_EXPIRES}; Path=/; Secure; Domain=${fqdn}`;
|
||||
return `${SESSION_COOKIE_NAME}=${token}; HttpOnly; SameSite=Lax; Max-Age=${SESSION_COOKIE_EXPIRES}; Path=/; Secure; Domain=.localhost`;
|
||||
} else {
|
||||
return `${SESSION_COOKIE_NAME}=${token}; HttpOnly; SameSite=Lax; Max-Age=${SESSION_COOKIE_EXPIRES}; Path=/; Domain=${fqdn}`;
|
||||
return `${SESSION_COOKIE_NAME}=${token}; HttpOnly; SameSite=Lax; Max-Age=${SESSION_COOKIE_EXPIRES}; Path=/; Domain=.localhost`;
|
||||
}
|
||||
}
|
||||
|
||||
export function createBlankResourceSessionTokenCookie(
|
||||
fqdn: string,
|
||||
secure: boolean
|
||||
secure: boolean,
|
||||
): string {
|
||||
if (secure) {
|
||||
return `${SESSION_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Max-Age=0; Path=/; Secure; Domain=${fqdn}`;
|
||||
|
|
|
@ -24,6 +24,11 @@ const environmentSchema = z.object({
|
|||
internal_hostname: z.string(),
|
||||
secure_cookies: z.boolean(),
|
||||
signup_secret: z.string().optional(),
|
||||
session_cookie_name: z.string(),
|
||||
}),
|
||||
badger: z.object({
|
||||
session_query_parameter: z.string(),
|
||||
resource_session_cookie_name: z.string(),
|
||||
}),
|
||||
traefik: z.object({
|
||||
http_entrypoint: z.string(),
|
||||
|
@ -68,7 +73,7 @@ const loadConfig = (configPath: string) => {
|
|||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw new Error(
|
||||
`Error loading configuration file: ${error.message}`
|
||||
`Error loading configuration file: ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
|
@ -90,21 +95,21 @@ if (!environment) {
|
|||
try {
|
||||
const exampleConfigContent = fs.readFileSync(
|
||||
exampleConfigPath,
|
||||
"utf8"
|
||||
"utf8",
|
||||
);
|
||||
fs.writeFileSync(configFilePath1, exampleConfigContent, "utf8");
|
||||
environment = loadConfig(configFilePath1);
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
throw new Error(
|
||||
`Error creating configuration file from example: ${error.message}`
|
||||
`Error creating configuration file from example: ${error.message}`,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} else {
|
||||
throw new Error(
|
||||
"No configuration file found and no example configuration available"
|
||||
"No configuration file found and no example configuration available",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -126,5 +131,8 @@ process.env.FLAGS_EMAIL_VERIFICATION_REQUIRED = parsedConfig.data.flags
|
|||
?.require_email_verification
|
||||
? "true"
|
||||
: "false";
|
||||
process.env.SESSION_COOKIE_NAME = parsedConfig.data.server.session_cookie_name;
|
||||
process.env.RESOURCE_SESSION_QUERY_PARAM_NAME =
|
||||
parsedConfig.data.badger.session_query_parameter;
|
||||
|
||||
export default parsedConfig.data;
|
||||
|
|
|
@ -16,6 +16,7 @@ import { z } from "zod";
|
|||
import { fromError } from "zod-validation-error";
|
||||
import { verifyTotpCode } from "@server/auth/2fa";
|
||||
import config from "@server/config";
|
||||
import logger from "@server/logger";
|
||||
|
||||
export const loginBodySchema = z.object({
|
||||
email: z.string().email(),
|
||||
|
@ -125,6 +126,8 @@ export async function login(
|
|||
await createSession(token, existingUser.userId);
|
||||
const cookie = serializeSessionCookie(token);
|
||||
|
||||
logger.debug(cookie);
|
||||
|
||||
res.appendHeader("Set-Cookie", cookie);
|
||||
|
||||
if (
|
||||
|
|
|
@ -93,7 +93,7 @@ export async function verifyResourceSession(
|
|||
return allowed(res);
|
||||
}
|
||||
|
||||
const redirectUrl = `${config.app.base_url}/${resource.orgId}/auth/resource/${resource.resourceId}?r=${originalRequestURL}`;
|
||||
const redirectUrl = `${config.app.base_url}/auth/resource/${resource.resourceId}?redirect=${originalRequestURL}`;
|
||||
|
||||
if (sso && sessions.session) {
|
||||
const { session, user } = await validateSessionToken(
|
||||
|
|
|
@ -27,12 +27,13 @@ export const authWithPasswordParamsSchema = z.object({
|
|||
|
||||
export type AuthWithPasswordResponse = {
|
||||
codeRequested?: boolean;
|
||||
session?: string;
|
||||
};
|
||||
|
||||
export async function authWithPassword(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
next: NextFunction,
|
||||
): Promise<any> {
|
||||
const parsedBody = authWithPasswordBodySchema.safeParse(req.body);
|
||||
|
||||
|
@ -40,8 +41,8 @@ export async function authWithPassword(
|
|||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedBody.error).toString()
|
||||
)
|
||||
fromError(parsedBody.error).toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -51,8 +52,8 @@ export async function authWithPassword(
|
|||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
fromError(parsedParams.error).toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -65,7 +66,7 @@ export async function authWithPassword(
|
|||
.from(resources)
|
||||
.leftJoin(
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
eq(resourcePassword.resourceId, resources.resourceId),
|
||||
)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
@ -75,7 +76,10 @@ export async function authWithPassword(
|
|||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Resource does not exist")
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Resource does not exist",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -85,9 +89,9 @@ export async function authWithPassword(
|
|||
HttpCode.UNAUTHORIZED,
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Resource has no password protection"
|
||||
)
|
||||
)
|
||||
"Resource has no password protection",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -99,11 +103,11 @@ export async function authWithPassword(
|
|||
timeCost: 2,
|
||||
outputLen: 32,
|
||||
parallelism: 1,
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!validPassword) {
|
||||
return next(
|
||||
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect password")
|
||||
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect password"),
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -127,18 +131,20 @@ export async function authWithPassword(
|
|||
token,
|
||||
passwordId: definedPassword.passwordId,
|
||||
});
|
||||
const secureCookie = resource.ssl;
|
||||
const cookie = serializeResourceSessionCookie(
|
||||
token,
|
||||
resource.fullDomain,
|
||||
secureCookie
|
||||
);
|
||||
res.appendHeader("Set-Cookie", cookie);
|
||||
// const secureCookie = resource.ssl;
|
||||
// const cookie = serializeResourceSessionCookie(
|
||||
// token,
|
||||
// resource.fullDomain,
|
||||
// secureCookie,
|
||||
// );
|
||||
// res.appendHeader("Set-Cookie", cookie);
|
||||
|
||||
logger.debug(cookie); // remove after testing
|
||||
// logger.debug(cookie); // remove after testing
|
||||
|
||||
return response<null>(res, {
|
||||
data: null,
|
||||
return response<AuthWithPasswordResponse>(res, {
|
||||
data: {
|
||||
session: token,
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Authenticated with resource successfully",
|
||||
|
@ -148,8 +154,8 @@ export async function authWithPassword(
|
|||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Failed to authenticate with resource"
|
||||
)
|
||||
"Failed to authenticate with resource",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -27,6 +27,7 @@ export const authWithPincodeParamsSchema = z.object({
|
|||
|
||||
export type AuthWithPincodeResponse = {
|
||||
codeRequested?: boolean;
|
||||
session?: string;
|
||||
};
|
||||
|
||||
export async function authWithPincode(
|
||||
|
@ -126,18 +127,20 @@ export async function authWithPincode(
|
|||
token,
|
||||
pincodeId: definedPincode.pincodeId,
|
||||
});
|
||||
const secureCookie = resource.ssl;
|
||||
const cookie = serializeResourceSessionCookie(
|
||||
token,
|
||||
resource.fullDomain,
|
||||
secureCookie,
|
||||
);
|
||||
res.appendHeader("Set-Cookie", cookie);
|
||||
// const secureCookie = resource.ssl;
|
||||
// const cookie = serializeResourceSessionCookie(
|
||||
// token,
|
||||
// resource.fullDomain,
|
||||
// secureCookie,
|
||||
// );
|
||||
// res.appendHeader("Set-Cookie", cookie);
|
||||
|
||||
logger.debug(cookie); // remove after testing
|
||||
// logger.debug(cookie); // remove after testing
|
||||
|
||||
return response<null>(res, {
|
||||
data: null,
|
||||
return response<AuthWithPincodeResponse>(res, {
|
||||
data: {
|
||||
session: token,
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Authenticated with resource successfully",
|
||||
|
|
|
@ -8,7 +8,7 @@ import config from "@server/config";
|
|||
|
||||
export async function traefikConfigProvider(
|
||||
_: Request,
|
||||
res: Response
|
||||
res: Response,
|
||||
): Promise<any> {
|
||||
try {
|
||||
const all = await db
|
||||
|
@ -16,18 +16,18 @@ export async function traefikConfigProvider(
|
|||
.from(schema.targets)
|
||||
.innerJoin(
|
||||
schema.resources,
|
||||
eq(schema.targets.resourceId, schema.resources.resourceId)
|
||||
eq(schema.targets.resourceId, schema.resources.resourceId),
|
||||
)
|
||||
.innerJoin(
|
||||
schema.orgs,
|
||||
eq(schema.resources.orgId, schema.orgs.orgId)
|
||||
eq(schema.resources.orgId, schema.orgs.orgId),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(schema.targets.enabled, true),
|
||||
isNotNull(schema.resources.subdomain),
|
||||
isNotNull(schema.orgs.domain)
|
||||
)
|
||||
isNotNull(schema.orgs.domain),
|
||||
),
|
||||
);
|
||||
|
||||
if (!all.length) {
|
||||
|
@ -48,9 +48,14 @@ export async function traefikConfigProvider(
|
|||
[badgerMiddlewareName]: {
|
||||
apiBaseUrl: new URL(
|
||||
"/api/v1",
|
||||
`http://${config.server.internal_hostname}:${config.server.internal_port}`
|
||||
`http://${config.server.internal_hostname}:${config.server.internal_port}`,
|
||||
).href,
|
||||
appBaseUrl: config.app.base_url,
|
||||
resourceSessionCookieName:
|
||||
config.badger.resource_session_cookie_name,
|
||||
userSessionCookieName:
|
||||
config.server.session_cookie_name,
|
||||
sessionQueryParameter:
|
||||
config.badger.session_query_parameter,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
|
@ -2,10 +2,11 @@ import { cookies } from "next/headers";
|
|||
|
||||
export async function authCookieHeader() {
|
||||
const allCookies = await cookies();
|
||||
const sessionId = allCookies.get("session")?.value ?? null;
|
||||
const cookieName = process.env.SESSION_COOKIE_NAME!;
|
||||
const sessionId = allCookies.get(cookieName)?.value ?? null;
|
||||
return {
|
||||
headers: {
|
||||
Cookie: `session=${sessionId}`
|
||||
}
|
||||
}
|
||||
Cookie: `${cookieName}=${sessionId}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
@ -37,6 +37,7 @@ import { AxiosResponse } from "axios";
|
|||
import { LoginResponse } from "@server/routers/auth";
|
||||
import ResourceAccessDenied from "./ResourceAccessDenied";
|
||||
import LoginForm from "@app/components/LoginForm";
|
||||
import { AuthWithPasswordResponse } from "@server/routers/resource";
|
||||
|
||||
const pinSchema = z.object({
|
||||
pin: z
|
||||
|
@ -62,6 +63,7 @@ type ResourceAuthPortalProps = {
|
|||
id: number;
|
||||
};
|
||||
redirect: string;
|
||||
queryParamName: string;
|
||||
};
|
||||
|
||||
export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
|
||||
|
@ -112,13 +114,29 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
|
|||
},
|
||||
});
|
||||
|
||||
function constructRedirect(redirect: string, token: string): string {
|
||||
const redirectUrl = new URL(redirect);
|
||||
redirectUrl.searchParams.delete(props.queryParamName);
|
||||
redirectUrl.searchParams.append(props.queryParamName, token);
|
||||
return redirectUrl.toString();
|
||||
}
|
||||
|
||||
const onPinSubmit = (values: z.infer<typeof pinSchema>) => {
|
||||
setLoadingLogin(true);
|
||||
api.post(`/resource/${props.resource.id}/auth/pincode`, {
|
||||
api.post<AxiosResponse<AuthWithPasswordResponse>>(
|
||||
`/resource/${props.resource.id}/auth/pincode`,
|
||||
{
|
||||
pincode: values.pin,
|
||||
})
|
||||
},
|
||||
)
|
||||
.then((res) => {
|
||||
window.location.href = props.redirect;
|
||||
const session = res.data.data.session;
|
||||
if (session) {
|
||||
window.location.href = constructRedirect(
|
||||
props.redirect,
|
||||
session,
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
|
@ -131,11 +149,20 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
|
|||
|
||||
const onPasswordSubmit = (values: z.infer<typeof passwordSchema>) => {
|
||||
setLoadingLogin(true);
|
||||
api.post(`/resource/${props.resource.id}/auth/password`, {
|
||||
api.post<AxiosResponse<AuthWithPasswordResponse>>(
|
||||
`/resource/${props.resource.id}/auth/password`,
|
||||
{
|
||||
password: values.password,
|
||||
})
|
||||
},
|
||||
)
|
||||
.then((res) => {
|
||||
window.location.href = props.redirect;
|
||||
const session = res.data.data.session;
|
||||
if (session) {
|
||||
window.location.href = constructRedirect(
|
||||
props.redirect,
|
||||
session,
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
|
|
|
@ -14,7 +14,7 @@ import ResourceAccessDenied from "./components/ResourceAccessDenied";
|
|||
|
||||
export default async function ResourceAuthPage(props: {
|
||||
params: Promise<{ resourceId: number }>;
|
||||
searchParams: Promise<{ r: string }>;
|
||||
searchParams: Promise<{ redirect: string }>;
|
||||
}) {
|
||||
const params = await props.params;
|
||||
const searchParams = await props.searchParams;
|
||||
|
@ -44,9 +44,10 @@ export default async function ResourceAuthPage(props: {
|
|||
const hasAuth = authInfo.password || authInfo.pincode || authInfo.sso;
|
||||
const isSSOOnly = authInfo.sso && !authInfo.password && !authInfo.pincode;
|
||||
|
||||
const redirectUrl = searchParams.r || authInfo.url;
|
||||
const redirectUrl = searchParams.redirect || authInfo.url;
|
||||
|
||||
if (!hasAuth) {
|
||||
// no authentication so always go straight to the resource
|
||||
redirect(redirectUrl);
|
||||
}
|
||||
|
||||
|
@ -93,6 +94,9 @@ export default async function ResourceAuthPage(props: {
|
|||
id: authInfo.resourceId,
|
||||
}}
|
||||
redirect={redirectUrl}
|
||||
queryParamName={
|
||||
process.env.RESOURCE_SESSION_QUERY_PARAM_NAME!
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue