mirror of
https://github.com/fosrl/pangolin.git
synced 2026-08-13 16:00:02 +02:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d374b4f66e |
+2
-2
@@ -1,5 +1,5 @@
|
||||
# FROM node:24-slim AS base
|
||||
FROM public.ecr.aws/docker/library/node:26-slim AS base
|
||||
FROM public.ecr.aws/docker/library/node:24-slim AS base
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -33,7 +33,7 @@ FROM base AS builder
|
||||
RUN npm ci --omit=dev
|
||||
|
||||
# FROM node:24-slim AS runner
|
||||
FROM public.ecr.aws/docker/library/node:26-slim AS runner
|
||||
FROM public.ecr.aws/docker/library/node:24-slim AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM node:26-alpine
|
||||
FROM node:24-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
@@ -43,8 +43,6 @@
|
||||
"inviteLoginUser": "Please make sure you're logged in as the correct user.",
|
||||
"inviteErrorNoUser": "We're sorry, but it looks like the invite you're trying to access is not for a user that exists.",
|
||||
"inviteCreateUser": "Please create an account first.",
|
||||
"inviteErrorOidcNotAllowed": "Invites can only be accepted by internal accounts. Sign out and log in with your password for this email.",
|
||||
"inviteLoginInternalOnly": "Invites require an internal account with a password. Create an account or sign in with your password.",
|
||||
"goHome": "Go Home",
|
||||
"inviteLogInOtherUser": "Log In as a Different User",
|
||||
"createAnAccount": "Create an Account",
|
||||
@@ -1451,11 +1449,8 @@
|
||||
"actionSetResourcePincode": "Set Resource Pincode",
|
||||
"actionSetResourceEmailWhitelist": "Set Resource Email Whitelist",
|
||||
"actionGetResourceEmailWhitelist": "Get Resource Email Whitelist",
|
||||
"actionListResourcePolicies": "List Resource Policies",
|
||||
"actionCreateResourcePolicy": "Create Resource Policy",
|
||||
"actionGetResourcePolicy": "Get Resource Policy",
|
||||
"actionUpdateResourcePolicy": "Update Resource Policy",
|
||||
"actionDeleteResourcePolicy": "Delete Resource Policy",
|
||||
"actionSetResourcePolicyUsers": "Set Resource Policy Users",
|
||||
"actionSetResourcePolicyRoles": "Set Resource Policy Roles",
|
||||
"actionSetResourcePolicyPassword": "Set Resource Policy Password",
|
||||
|
||||
Generated
+3
-3
@@ -13111,9 +13111,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ip-address": {
|
||||
"version": "10.2.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
|
||||
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
|
||||
"version": "10.4.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.4.0.tgz",
|
||||
"integrity": "sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
|
||||
@@ -95,8 +95,7 @@ export const subscriptions = pgTable("subscriptions", {
|
||||
billingCycleAnchor: bigint("billingCycleAnchor", { mode: "number" }),
|
||||
expiresAt: bigint("expiresAt", { mode: "number" }),
|
||||
trial: boolean("trial").default(false),
|
||||
type: varchar("type", { length: 50 }), // tier1, tier2, tier3, or license
|
||||
override: boolean("override").default(false)
|
||||
type: varchar("type", { length: 50 }) // tier1, tier2, tier3, or license
|
||||
});
|
||||
|
||||
export const subscriptionItems = pgTable("subscriptionItems", {
|
||||
|
||||
@@ -89,8 +89,7 @@ export const subscriptions = sqliteTable("subscriptions", {
|
||||
expiresAt: integer("expiresAt"),
|
||||
trial: integer("trial", { mode: "boolean" }).default(false),
|
||||
billingCycleAnchor: integer("billingCycleAnchor"),
|
||||
type: text("type"), // tier1, tier2, tier3, or license
|
||||
override: integer("override", { mode: "boolean" }).default(false)
|
||||
type: text("type") // tier1, tier2, tier3, or license
|
||||
});
|
||||
|
||||
export const subscriptionItems = sqliteTable("subscriptionItems", {
|
||||
|
||||
@@ -632,6 +632,7 @@ export const ResourcePolicySchema = z.object({
|
||||
})
|
||||
)
|
||||
)
|
||||
.max(50)
|
||||
.transform((v) => v.map((e) => e.toLowerCase()))
|
||||
.optional()
|
||||
.default([]),
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { db, idp, idpOrg, Transaction } from "@server/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { build } from "@server/build";
|
||||
|
||||
export function isOrgIdentityProviderMode(): boolean {
|
||||
return build === "saas" || process.env.IDENTITY_PROVIDER_MODE === "org";
|
||||
return process.env.IDENTITY_PROVIDER_MODE === "org";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -266,13 +266,13 @@ export const configSchema = z
|
||||
.positive()
|
||||
.gt(0)
|
||||
.optional()
|
||||
.default(30),
|
||||
.default(10),
|
||||
burst: z
|
||||
.number()
|
||||
.positive()
|
||||
.gt(0)
|
||||
.optional()
|
||||
.default(50)
|
||||
.default(16)
|
||||
})
|
||||
.optional()
|
||||
.prefault({})
|
||||
|
||||
@@ -53,15 +53,6 @@ export async function handleSubscriptionDeleted(
|
||||
return;
|
||||
}
|
||||
|
||||
// If the subscription has been manually overridden, we lock it down
|
||||
// so Stripe can no longer change (or delete) its status locally.
|
||||
if (existingSubscription.override === true) {
|
||||
logger.info(
|
||||
`Subscription ${subscription.id} is locked (override=true). Ignoring deletion event from Stripe.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(subscriptions)
|
||||
.where(eq(subscriptions.subscriptionId, subscription.id));
|
||||
|
||||
@@ -68,27 +68,13 @@ export async function handleSubscriptionUpdated(
|
||||
const type = getSubType(fullSubscription);
|
||||
const previousType = existingSubscription.type as SubscriptionType | null;
|
||||
|
||||
// If the subscription has been manually overridden, we lock the
|
||||
// status down so Stripe webhooks can no longer change it.
|
||||
const isLocked = existingSubscription.override === true;
|
||||
if (isLocked) {
|
||||
logger.info(
|
||||
`Subscription ${subscription.id} is locked (override=true). Ignoring status change from Stripe (would have been ${subscription.status}).`
|
||||
);
|
||||
}
|
||||
const effectiveStatus = isLocked
|
||||
? existingSubscription.status
|
||||
: subscription.status;
|
||||
|
||||
await db
|
||||
.update(subscriptions)
|
||||
.set({
|
||||
status: effectiveStatus,
|
||||
canceledAt: isLocked
|
||||
? existingSubscription.canceledAt
|
||||
: subscription.canceled_at
|
||||
? subscription.canceled_at
|
||||
: null,
|
||||
status: subscription.status,
|
||||
canceledAt: subscription.canceled_at
|
||||
? subscription.canceled_at
|
||||
: null,
|
||||
updatedAt: Math.floor(Date.now() / 1000),
|
||||
billingCycleAnchor: subscription.billing_cycle_anchor,
|
||||
type: type
|
||||
@@ -289,23 +275,23 @@ export async function handleSubscriptionUpdated(
|
||||
// we only need to handle the limit lifecycle for saas subscriptions not for the licenses
|
||||
await handleSubscriptionLifesycle(
|
||||
customer.orgId,
|
||||
effectiveStatus,
|
||||
subscription.status,
|
||||
type
|
||||
);
|
||||
|
||||
// Handle feature lifecycle when subscription is canceled or becomes unpaid
|
||||
if (
|
||||
effectiveStatus === "canceled" ||
|
||||
effectiveStatus === "unpaid" ||
|
||||
effectiveStatus === "incomplete_expired"
|
||||
subscription.status === "canceled" ||
|
||||
subscription.status === "unpaid" ||
|
||||
subscription.status === "incomplete_expired"
|
||||
) {
|
||||
logger.info(
|
||||
`Subscription ${subscription.id} for org ${customer.orgId} is ${effectiveStatus}, disabling paid features`
|
||||
`Subscription ${subscription.id} for org ${customer.orgId} is ${subscription.status}, disabling paid features`
|
||||
);
|
||||
await handleTierChange(customer.orgId, null, previousType ?? undefined);
|
||||
}
|
||||
} else if (type === "license") {
|
||||
if (effectiveStatus === "canceled" || effectiveStatus == "unpaid" || effectiveStatus == "incomplete_expired") {
|
||||
if (subscription.status === "canceled" || subscription.status == "unpaid" || subscription.status == "incomplete_expired") {
|
||||
try {
|
||||
// WARNING:
|
||||
// this invalidates ALL OF THE ENTERPRISE LICENSES for this orgId
|
||||
|
||||
@@ -10,12 +10,12 @@
|
||||
*
|
||||
* This file is not licensed under the AGPLv3.
|
||||
*/
|
||||
import { certificates, db, domainNamespaces, domains, orgDomains } from "@server/db";
|
||||
import { certificates, db, domains, orgDomains } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import logger from "@server/logger";
|
||||
import { type GetBatchedCertificateResponse } from "@server/routers/certificates/types";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { and, eq, inArray, isNotNull, or } from "drizzle-orm";
|
||||
import { and, eq, inArray, or } from "drizzle-orm";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import createHttpError from "http-errors";
|
||||
import { z } from "zod";
|
||||
@@ -63,28 +63,14 @@ async function query(orgId: string, domainList: string[]) {
|
||||
})
|
||||
.from(certificates)
|
||||
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
|
||||
.leftJoin(
|
||||
.innerJoin(
|
||||
orgDomains,
|
||||
and(
|
||||
eq(domains.domainId, orgDomains.domainId),
|
||||
eq(orgDomains.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
domainNamespaces,
|
||||
eq(domains.domainId, domainNamespaces.domainId)
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
inArray(certificates.domain, domainList),
|
||||
// Namespace domains are shared across all orgs, so they skip
|
||||
// the org-ownership check (mirrors verifyCertificateAccess).
|
||||
or(
|
||||
isNotNull(orgDomains.orgId),
|
||||
isNotNull(domainNamespaces.domainNamespaceId)
|
||||
)
|
||||
)
|
||||
);
|
||||
.where(and(inArray(certificates.domain, domainList)));
|
||||
|
||||
// All non resolved domain certificates might be `ns` or `wildcard`,
|
||||
// which means exact domain certificates do not exist
|
||||
@@ -124,27 +110,19 @@ async function query(orgId: string, domainList: string[]) {
|
||||
})
|
||||
.from(certificates)
|
||||
.innerJoin(domains, eq(certificates.domainId, domains.domainId))
|
||||
.leftJoin(
|
||||
.innerJoin(
|
||||
orgDomains,
|
||||
and(
|
||||
eq(domains.domainId, orgDomains.domainId),
|
||||
eq(orgDomains.orgId, orgId)
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
domainNamespaces,
|
||||
eq(domains.domainId, domainNamespaces.domainId)
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(certificates.wildcard, true),
|
||||
or(
|
||||
inArray(certificates.domain, [...domainLevelDownSet]),
|
||||
inArray(certificates.domain, [...wildcardDomainSet])
|
||||
),
|
||||
or(
|
||||
isNotNull(orgDomains.orgId),
|
||||
isNotNull(domainNamespaces.domainNamespaceId)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -107,6 +107,7 @@ const createResourcePolicyBodySchema = z.strictObject({
|
||||
})
|
||||
)
|
||||
)
|
||||
.max(50)
|
||||
.transform((v) => v.map((e) => e.toLowerCase()))
|
||||
.optional()
|
||||
.default([]),
|
||||
|
||||
@@ -127,9 +127,6 @@ export async function verifyResourceSession(
|
||||
// Extract HTTP Basic Auth credentials if present
|
||||
const clientHeaderAuth = extractBasicAuth(headers);
|
||||
|
||||
const clientUserAgent = headers?.["user-agent"] || headers?.["User-Agent"];
|
||||
const clientIsBrowser = isBrowserUserAgent(clientUserAgent);
|
||||
|
||||
const clientIp = requestIp
|
||||
? stripPortFromHost(requestIp, badgerVersion)
|
||||
: undefined;
|
||||
@@ -316,14 +313,9 @@ export async function verifyResourceSession(
|
||||
return allowed(res, undefined, dontStripSession);
|
||||
}
|
||||
|
||||
// Only offer a browser redirect to clients that can actually follow one and log in
|
||||
// (an interactive browser). Non-browser clients (curl, scripts, bots, etc.) just get
|
||||
// an unauthorized response from Badger instead of a login redirect URL.
|
||||
const redirectPath = clientIsBrowser
|
||||
? `/auth/resource/${encodeURIComponent(
|
||||
resource.resourceGuid
|
||||
)}?redirect=${encodeURIComponent(originalRequestURL)}`
|
||||
: undefined;
|
||||
const redirectPath = `/auth/resource/${encodeURIComponent(
|
||||
resource.resourceGuid
|
||||
)}?redirect=${encodeURIComponent(originalRequestURL)}`;
|
||||
|
||||
// check for access token in headers
|
||||
if (
|
||||
@@ -1484,46 +1476,6 @@ async function getCountryCodeFromIp(ip: string): Promise<string | undefined> {
|
||||
return cachedCountryCode;
|
||||
}
|
||||
|
||||
// Permissive by default: only reject known non-browser clients or a missing
|
||||
// User-Agent (real browsers always send one). This avoids blocking real
|
||||
// browsers whose UA string doesn't match a hardcoded allow-list.
|
||||
const NON_BROWSER_USER_AGENT_PATTERNS = [
|
||||
/curl/,
|
||||
/wget/,
|
||||
/python-requests/,
|
||||
/python-urllib/,
|
||||
/go-http-client/,
|
||||
/okhttp/,
|
||||
/axios/,
|
||||
/node-fetch/,
|
||||
/postmanruntime/,
|
||||
/insomnia/,
|
||||
/libwww-perl/,
|
||||
/java\//,
|
||||
/ruby/,
|
||||
/php/,
|
||||
/bot/,
|
||||
/spider/,
|
||||
/crawler/,
|
||||
/headlesschrome/,
|
||||
/phantomjs/,
|
||||
/httpclient/,
|
||||
/prometheus/,
|
||||
/go-resty/,
|
||||
/apache-httpclient/,
|
||||
/scrapy/
|
||||
];
|
||||
|
||||
function isBrowserUserAgent(userAgent: string | undefined): boolean {
|
||||
if (!userAgent) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const ua = userAgent.toLowerCase();
|
||||
|
||||
return !NON_BROWSER_USER_AGENT_PATTERNS.some((pattern) => pattern.test(ua));
|
||||
}
|
||||
|
||||
function extractBasicAuth(
|
||||
headers: Record<string, string> | undefined
|
||||
): string | undefined {
|
||||
|
||||
@@ -726,8 +726,8 @@ authenticated.post(
|
||||
verifyApiKeyResourcePolicyAccess,
|
||||
verifyApiKeyRoleAccess,
|
||||
verifyLimits,
|
||||
verifyApiKeyHasAction(ActionsEnum.setResourcePolicyUsers),
|
||||
verifyApiKeyHasAction(ActionsEnum.setResourcePolicyRoles),
|
||||
verifyUserHasAction(ActionsEnum.setResourcePolicyUsers),
|
||||
verifyUserHasAction(ActionsEnum.setResourcePolicyRoles),
|
||||
logActionAudit(ActionsEnum.setResourcePolicyUsers),
|
||||
logActionAudit(ActionsEnum.setResourcePolicyRoles),
|
||||
policy.setResourcePolicyAccessControl
|
||||
@@ -742,8 +742,8 @@ authenticated.put(
|
||||
verifyApiKeyResourcePolicyAccess,
|
||||
verifyApiKeyRoleAccess,
|
||||
verifyLimits,
|
||||
verifyApiKeyHasAction(ActionsEnum.setResourcePolicyUsers),
|
||||
verifyApiKeyHasAction(ActionsEnum.setResourcePolicyRoles),
|
||||
verifyUserHasAction(ActionsEnum.setResourcePolicyUsers),
|
||||
verifyUserHasAction(ActionsEnum.setResourcePolicyRoles),
|
||||
logActionAudit(ActionsEnum.setResourcePolicyUsers),
|
||||
logActionAudit(ActionsEnum.setResourcePolicyRoles),
|
||||
policy.setResourcePolicyAccessControl
|
||||
|
||||
@@ -19,6 +19,7 @@ const setResourcePolicyWhitelistBodySchema = z.strictObject({
|
||||
})
|
||||
)
|
||||
)
|
||||
.max(50)
|
||||
.transform((v) => v.map((e) => e.toLowerCase()))
|
||||
});
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ const setResourceWhitelistBodySchema = z.strictObject({
|
||||
})
|
||||
)
|
||||
)
|
||||
.max(50)
|
||||
.transform((v) => v.map((e) => e.toLowerCase()))
|
||||
});
|
||||
|
||||
|
||||
@@ -34,9 +34,7 @@ const createRoleSchema = z.strictObject({
|
||||
export const defaultRoleAllowedActions: ActionsEnum[] = [
|
||||
ActionsEnum.getOrg,
|
||||
ActionsEnum.getResource,
|
||||
ActionsEnum.listResources,
|
||||
ActionsEnum.getSiteResource,
|
||||
ActionsEnum.listSiteResources
|
||||
ActionsEnum.listResources
|
||||
];
|
||||
|
||||
export type CreateRoleBody = z.infer<typeof createRoleSchema>;
|
||||
|
||||
@@ -3,13 +3,11 @@ import {
|
||||
DB_TYPE,
|
||||
Label,
|
||||
SiteResource,
|
||||
roleSiteResources,
|
||||
siteNetworks,
|
||||
siteResourceLabels,
|
||||
siteResources,
|
||||
sites,
|
||||
labels,
|
||||
userSiteResources
|
||||
labels
|
||||
} from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import logger from "@server/logger";
|
||||
@@ -325,48 +323,7 @@ export async function listAllSiteResourcesByOrg(
|
||||
labels: labelFilter
|
||||
} = parsedQuery.data;
|
||||
|
||||
let accessibleSiteResourceIds: number[];
|
||||
if (req.user) {
|
||||
const accessibleSiteResources = await db
|
||||
.select({
|
||||
siteResourceId: sql<number>`COALESCE(${userSiteResources.siteResourceId}, ${roleSiteResources.siteResourceId})`
|
||||
})
|
||||
.from(userSiteResources)
|
||||
.fullJoin(
|
||||
roleSiteResources,
|
||||
eq(
|
||||
userSiteResources.siteResourceId,
|
||||
roleSiteResources.siteResourceId
|
||||
)
|
||||
)
|
||||
.where(
|
||||
or(
|
||||
eq(userSiteResources.userId, req.user.userId),
|
||||
inArray(
|
||||
roleSiteResources.roleId,
|
||||
req.userOrgRoleIds ?? []
|
||||
)
|
||||
)
|
||||
);
|
||||
accessibleSiteResourceIds = accessibleSiteResources.map(
|
||||
(row) => row.siteResourceId
|
||||
);
|
||||
} else {
|
||||
const allOrgSiteResources = await db
|
||||
.select({ siteResourceId: siteResources.siteResourceId })
|
||||
.from(siteResources)
|
||||
.where(eq(siteResources.orgId, orgId));
|
||||
accessibleSiteResourceIds = allOrgSiteResources.map(
|
||||
(row) => row.siteResourceId
|
||||
);
|
||||
}
|
||||
|
||||
const conditions = [
|
||||
and(
|
||||
eq(siteResources.orgId, orgId),
|
||||
inArray(siteResources.siteResourceId, accessibleSiteResourceIds)
|
||||
)
|
||||
];
|
||||
const conditions = [and(eq(siteResources.orgId, orgId))];
|
||||
|
||||
if (siteId != null) {
|
||||
// Keep inner joins here: filtering by a specific site implies the
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
networks,
|
||||
roleSiteResources,
|
||||
siteNetworks,
|
||||
userSiteResources
|
||||
} from "@server/db";
|
||||
import { db, networks, siteNetworks } from "@server/db";
|
||||
import { siteResources, sites, SiteResource } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
|
||||
import { and, asc, desc, eq } from "drizzle-orm";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import logger from "@server/logger";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
@@ -165,47 +159,10 @@ export async function listSiteResources(
|
||||
return next(createHttpError(HttpCode.NOT_FOUND, "Site not found"));
|
||||
}
|
||||
|
||||
let accessibleSiteResourceIds: number[];
|
||||
if (req.user) {
|
||||
const accessibleSiteResources = await db
|
||||
.select({
|
||||
siteResourceId: sql<number>`COALESCE(${userSiteResources.siteResourceId}, ${roleSiteResources.siteResourceId})`
|
||||
})
|
||||
.from(userSiteResources)
|
||||
.fullJoin(
|
||||
roleSiteResources,
|
||||
eq(
|
||||
userSiteResources.siteResourceId,
|
||||
roleSiteResources.siteResourceId
|
||||
)
|
||||
)
|
||||
.where(
|
||||
or(
|
||||
eq(userSiteResources.userId, req.user.userId),
|
||||
inArray(
|
||||
roleSiteResources.roleId,
|
||||
req.userOrgRoleIds ?? []
|
||||
)
|
||||
)
|
||||
);
|
||||
accessibleSiteResourceIds = accessibleSiteResources.map(
|
||||
(row) => row.siteResourceId
|
||||
);
|
||||
} else {
|
||||
const allOrgSiteResources = await db
|
||||
.select({ siteResourceId: siteResources.siteResourceId })
|
||||
.from(siteResources)
|
||||
.where(eq(siteResources.orgId, orgId));
|
||||
accessibleSiteResourceIds = allOrgSiteResources.map(
|
||||
(row) => row.siteResourceId
|
||||
);
|
||||
}
|
||||
|
||||
// Get site resources by joining networks to siteResources via siteNetworks
|
||||
const conditions = [
|
||||
eq(siteNetworks.siteId, siteId),
|
||||
eq(siteResources.orgId, orgId),
|
||||
inArray(siteResources.siteResourceId, accessibleSiteResourceIds)
|
||||
eq(siteResources.orgId, orgId)
|
||||
];
|
||||
|
||||
if (typeof status !== "undefined") {
|
||||
|
||||
@@ -22,7 +22,6 @@ import { calculateUserClientsForOrgs } from "@server/lib/calculateUserClientsFor
|
||||
import { build } from "@server/build";
|
||||
import { assignUserToOrg } from "@server/lib/userOrg";
|
||||
import { isOrgRebuildRateLimited } from "@server/lib/rebuildClientAssociations";
|
||||
import { UserType } from "@server/types/UserTypes";
|
||||
|
||||
const acceptInviteBodySchema = z.strictObject({
|
||||
token: z.string(),
|
||||
@@ -67,17 +66,12 @@ export async function acceptInvite(
|
||||
);
|
||||
}
|
||||
|
||||
const [existingInternalUser] = await db
|
||||
const existingUser = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(
|
||||
and(
|
||||
eq(users.email, existingInvite.email),
|
||||
eq(users.type, UserType.Internal)
|
||||
)
|
||||
)
|
||||
.where(eq(users.email, existingInvite.email))
|
||||
.limit(1);
|
||||
if (!existingInternalUser) {
|
||||
if (!existingUser.length) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
@@ -86,8 +80,9 @@ export async function acceptInvite(
|
||||
);
|
||||
}
|
||||
|
||||
const { user } = await verifySession(req);
|
||||
const { user, session } = await verifySession(req);
|
||||
|
||||
// at this point we know the user exists
|
||||
if (!user) {
|
||||
return next(
|
||||
createHttpError(
|
||||
@@ -97,7 +92,7 @@ export async function acceptInvite(
|
||||
);
|
||||
}
|
||||
|
||||
if (user.email !== existingInvite.email) {
|
||||
if (user && user.email !== existingInvite.email) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
@@ -106,15 +101,6 @@ export async function acceptInvite(
|
||||
);
|
||||
}
|
||||
|
||||
if (user.type !== UserType.Internal) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Invites can only be accepted by internal users."
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (build == "saas") {
|
||||
const usage = await usageService.getUsage(
|
||||
existingInvite.orgId,
|
||||
@@ -209,7 +195,7 @@ export async function acceptInvite(
|
||||
await assignUserToOrg(
|
||||
org,
|
||||
{
|
||||
userId: user.userId,
|
||||
userId: existingUser[0].userId,
|
||||
orgId: existingInvite.orgId
|
||||
},
|
||||
inviteRoleIds,
|
||||
@@ -222,13 +208,13 @@ export async function acceptInvite(
|
||||
.where(eq(userInvites.inviteId, inviteId));
|
||||
|
||||
logger.debug(
|
||||
`User ${user.userId} accepted invite to org ${existingInvite.orgId}`
|
||||
`User ${existingUser[0].userId} accepted invite to org ${existingInvite.orgId}`
|
||||
);
|
||||
});
|
||||
|
||||
calculateUserClientsForOrgs(user.userId).catch((e) => {
|
||||
calculateUserClientsForOrgs(existingUser[0].userId).catch((e) => {
|
||||
logger.error(
|
||||
`Failed to calculate user clients after accepting invite for user ${user.userId}: ${e}`
|
||||
`Failed to calculate user clients after accepting invite for user ${existingUser[0].userId}: ${e}`
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { assignUserToOrg } from "@server/lib/userOrg";
|
||||
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
|
||||
import { isOrgRebuildRateLimited } from "@server/lib/rebuildClientAssociations";
|
||||
import { idpExistsForOrg } from "@server/lib/idp/idpExistsForOrg";
|
||||
|
||||
const paramsSchema = z.strictObject({
|
||||
orgId: z.string().nonempty()
|
||||
@@ -240,16 +239,6 @@ export async function createOrgUser(
|
||||
);
|
||||
}
|
||||
|
||||
const providerExists = await idpExistsForOrg(idpId, orgId);
|
||||
if (!providerExists) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Identity provider not found in this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const [idpRes] = await db
|
||||
.select()
|
||||
.from(idp)
|
||||
|
||||
@@ -107,7 +107,7 @@ const listUsersSchema = z.strictObject({
|
||||
.filter((n) => Number.isInteger(n) && n > 0);
|
||||
const unique = [...new Set(nums)];
|
||||
return unique.length ? unique : undefined;
|
||||
}, z.array(z.number().int().positive()).optional())
|
||||
}, z.array(z.number().int().positive()).max(50).optional())
|
||||
.openapi({
|
||||
description:
|
||||
"Filter users who have any of these role ids in the organization (repeat query param)"
|
||||
|
||||
@@ -28,7 +28,6 @@ import m19 from "./scriptsPg/1.18.4";
|
||||
import m20 from "./scriptsPg/1.19.0";
|
||||
import m21 from "./scriptsPg/1.20.0";
|
||||
import m22 from "./scriptsPg/1.21.0";
|
||||
import m23 from "./scriptsPg/1.21.1";
|
||||
|
||||
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER
|
||||
// EXCEPT FOR THE DATABASE AND THE SCHEMA
|
||||
@@ -56,8 +55,7 @@ const migrations = [
|
||||
{ version: "1.18.4", run: m19 },
|
||||
{ version: "1.19.0", run: m20 },
|
||||
{ version: "1.20.0", run: m21 },
|
||||
{ version: "1.21.0", run: m22 },
|
||||
{ version: "1.21.1", run: m23 }
|
||||
{ version: "1.21.0", run: m22 }
|
||||
// Add new migrations here as they are created
|
||||
] as {
|
||||
version: string;
|
||||
|
||||
@@ -47,7 +47,6 @@ import m41 from "./scriptsSqlite/1.19.0";
|
||||
import m42 from "./scriptsSqlite/1.19.1";
|
||||
import m43 from "./scriptsSqlite/1.20.0";
|
||||
import m44 from "./scriptsSqlite/1.21.0";
|
||||
import m45 from "./scriptsSqlite/1.21.1";
|
||||
|
||||
// THIS CANNOT IMPORT ANYTHING FROM THE SERVER
|
||||
// EXCEPT FOR THE DATABASE AND THE SCHEMA
|
||||
@@ -92,8 +91,7 @@ const migrations = [
|
||||
{ version: "1.19.0", run: m41 },
|
||||
{ version: "1.19.1", run: m42 },
|
||||
{ version: "1.20.0", run: m43 },
|
||||
{ version: "1.21.0", run: m44 },
|
||||
{ version: "1.21.1", run: m45 }
|
||||
{ version: "1.21.0", run: m44 }
|
||||
// Add new migrations here as they are created
|
||||
] as const;
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { db } from "@server/db/pg/driver";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
const version = "1.21.1";
|
||||
|
||||
const actionsToGrant = ["getSiteResource", "listSiteResources"] as const;
|
||||
|
||||
export default async function migration() {
|
||||
console.log(`Running setup script ${version}...`);
|
||||
|
||||
try {
|
||||
await db.execute(sql`BEGIN`);
|
||||
|
||||
for (const actionId of actionsToGrant) {
|
||||
await db.execute(sql`
|
||||
INSERT INTO "roleActions" ("roleId", "actionId", "orgId")
|
||||
SELECT r."roleId", ${actionId}, r."orgId"
|
||||
FROM "roles" r
|
||||
WHERE COALESCE(r."isAdmin", false) = false
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM "roleActions" ra
|
||||
WHERE ra."roleId" = r."roleId"
|
||||
AND ra."actionId" = ${actionId}
|
||||
AND ra."orgId" = r."orgId"
|
||||
);
|
||||
`);
|
||||
}
|
||||
|
||||
await db.execute(sql`COMMIT`);
|
||||
console.log(`Finished setup script ${version}`);
|
||||
} catch (e) {
|
||||
await db.execute(sql`ROLLBACK`);
|
||||
console.log("Unable to migrate database");
|
||||
console.log(e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { APP_PATH } from "@server/lib/consts";
|
||||
import Database from "better-sqlite3";
|
||||
import path from "path";
|
||||
|
||||
const version = "1.21.1";
|
||||
|
||||
const actionsToGrant = ["getSiteResource", "listSiteResources"] as const;
|
||||
|
||||
export default async function migration() {
|
||||
console.log(`Running setup script ${version}...`);
|
||||
|
||||
const location = path.join(APP_PATH, "db", "db.sqlite");
|
||||
const db = new Database(location);
|
||||
|
||||
try {
|
||||
db.transaction(() => {
|
||||
const insertRoleAction = db.prepare(`
|
||||
INSERT INTO 'roleActions' ("roleId", "actionId", "orgId")
|
||||
SELECT r."roleId", ?, r."orgId"
|
||||
FROM 'roles' r
|
||||
WHERE COALESCE(r."isAdmin", 0) = 0
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM 'roleActions' ra
|
||||
WHERE ra."roleId" = r."roleId"
|
||||
AND ra."actionId" = ?
|
||||
AND ra."orgId" = r."orgId"
|
||||
);
|
||||
`);
|
||||
|
||||
for (const actionId of actionsToGrant) {
|
||||
insertRoleAction.run(actionId, actionId);
|
||||
}
|
||||
})();
|
||||
|
||||
console.log(`Finished setup script ${version}`);
|
||||
} catch (e) {
|
||||
console.log("Unable to migrate database");
|
||||
console.log(e);
|
||||
throw e;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -181,7 +181,7 @@ export default function NetworkingPage() {
|
||||
<SettingsSectionDescription>
|
||||
{t("remoteExitNodeNetworkingDescription")}
|
||||
<a
|
||||
href="https://docs.pangolin.net/manage/remote-node/backhaul"
|
||||
href="https://docs.pangolin.net/placeholder"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary hover:underline inline-flex items-center gap-1"
|
||||
|
||||
@@ -38,6 +38,18 @@ import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
|
||||
const accessControlsFormSchema = z.object({
|
||||
username: z.string(),
|
||||
autoProvisioned: z.boolean(),
|
||||
roles: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
text: z.string(),
|
||||
isAdmin: z.boolean().optional()
|
||||
})
|
||||
)
|
||||
});
|
||||
|
||||
export default function AccessControlsPage() {
|
||||
const { orgUser: user, updateOrgUser } = userOrgUserContext();
|
||||
const { user: sessionUser } = useUserContext();
|
||||
@@ -57,20 +69,6 @@ export default function AccessControlsPage() {
|
||||
(build === "enterprise" && !isPaid) ||
|
||||
(build === "oss" && !isPaid));
|
||||
|
||||
const accessControlsFormSchema = z.object({
|
||||
username: z.string(),
|
||||
autoProvisioned: z.boolean(),
|
||||
roles: z
|
||||
.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
text: z.string(),
|
||||
isAdmin: z.boolean().optional()
|
||||
})
|
||||
)
|
||||
.min(1, { message: t("accessRoleSelectPlease") })
|
||||
});
|
||||
|
||||
const form = useForm({
|
||||
resolver: zodResolver(accessControlsFormSchema),
|
||||
defaultValues: {
|
||||
@@ -110,6 +108,15 @@ export default function AccessControlsPage() {
|
||||
async function executeSave() {
|
||||
const values = form.getValues();
|
||||
|
||||
if (values.roles.length === 0) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("accessRoleRequired"),
|
||||
description: t("accessRoleSelectPlease")
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const roleIds = values.roles.map((r) => parseInt(r.id, 10));
|
||||
@@ -163,6 +170,15 @@ export default function AccessControlsPage() {
|
||||
|
||||
const values = form.getValues();
|
||||
|
||||
if (values.roles.length === 0) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("accessRoleRequired"),
|
||||
description: t("accessRoleSelectPlease")
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const willHaveAdminRole = values.roles.some((r) => r.isAdmin === true);
|
||||
|
||||
const isRemovingOwnAdmin =
|
||||
|
||||
@@ -237,13 +237,10 @@ export default function Page() {
|
||||
return;
|
||||
}
|
||||
|
||||
const useOrgIdps =
|
||||
build === "saas" || env.app.identityProviderMode === "org";
|
||||
|
||||
const res = await api
|
||||
.get<
|
||||
AxiosResponse<ListIdpsResponse>
|
||||
>(useOrgIdps ? `/org/${orgId}/idp` : "/idp")
|
||||
>(build === "saas" ? `/org/${orgId}/idp` : "/idp")
|
||||
.catch((e) => {
|
||||
console.error(e);
|
||||
toast({
|
||||
@@ -304,7 +301,8 @@ export default function Page() {
|
||||
);
|
||||
const [isSubmittingExternal, setIsSubmittingExternal] = useState(false);
|
||||
|
||||
const loading = isSubmittingInternal || isSubmittingExternal;
|
||||
const loading =
|
||||
isSubmittingInternal || isSubmittingExternal;
|
||||
|
||||
async function onSubmitInternal() {
|
||||
const isValid = await internalForm.trigger();
|
||||
|
||||
@@ -193,10 +193,7 @@ export default async function Page(props: {
|
||||
redirect={redirectUrl}
|
||||
forceLogin={forceLogin}
|
||||
defaultUser={defaultUser}
|
||||
inviteMode={isInvite}
|
||||
lastUsedIdp={
|
||||
isInvite ? null : lastUsedIdpForSmartLogin
|
||||
}
|
||||
lastUsedIdp={lastUsedIdpForSmartLogin}
|
||||
orgSignIn={
|
||||
!isInvite &&
|
||||
(build === "saas" ||
|
||||
@@ -216,7 +213,7 @@ export default async function Page(props: {
|
||||
) : (
|
||||
<DashboardLoginForm
|
||||
redirect={redirectUrl}
|
||||
idps={isInvite ? [] : loginIdps}
|
||||
idps={loginIdps}
|
||||
forceLogin={forceLogin}
|
||||
showOrgLogin={
|
||||
!isInvite &&
|
||||
|
||||
@@ -24,21 +24,19 @@ export function ContactSalesBanner() {
|
||||
<ExternalLink className="size-3.5 shrink-0" />
|
||||
</Link>
|
||||
{" " + t("contactSalesOr") + " "}
|
||||
<span className="whitespace-nowrap">
|
||||
<Link
|
||||
href="https://pangolin.net/contact"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 font-medium text-black-600 underline"
|
||||
>
|
||||
{t("contactSalesContactUs")}
|
||||
<ExternalLink className="size-3.5 shrink-0" />
|
||||
</Link>
|
||||
.
|
||||
</span>
|
||||
<Link
|
||||
href="https://pangolin.net/contact"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 font-medium text-black-600 underline"
|
||||
>
|
||||
{t("contactSalesContactUs")}
|
||||
<ExternalLink className="size-3.5 shrink-0" />
|
||||
</Link>
|
||||
.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@ import { PaidFeaturesAlert } from "@app/components/PaidFeaturesAlert";
|
||||
import { usePaidStatus } from "@/hooks/usePaidStatus";
|
||||
import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { toUnicode } from "punycode";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useUserContext } from "@app/hooks/useUserContext";
|
||||
|
||||
type AvailableOption = {
|
||||
@@ -166,19 +166,8 @@ export default function DomainPicker({
|
||||
const [selectedProvidedDomain, setSelectedProvidedDomain] =
|
||||
useState<AvailableOption | null>(null);
|
||||
|
||||
// Only run the initial base-domain selection once the domains have
|
||||
// loaded. This must not re-run on later `defaultDomainId`/`defaultSubdomain`
|
||||
// changes, because selecting a provided (namespace) domain calls
|
||||
// onDomainChange(null), which the parent form echoes back as
|
||||
// defaultDomainId/defaultSubdomain becoming undefined — re-running this
|
||||
// effect on that change would immediately snap the selector back to the
|
||||
// organization domain, making provided domains unselectable whenever one
|
||||
// was already set.
|
||||
const didSelectInitialDomainRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loadingDomains && !didSelectInitialDomainRef.current) {
|
||||
didSelectInitialDomainRef.current = true;
|
||||
if (!loadingDomains) {
|
||||
let domainOptionToSelect: DomainOption | null = null;
|
||||
if (organizationDomains.length > 0) {
|
||||
// Select the first organization domain or the one provided from props
|
||||
|
||||
@@ -44,7 +44,6 @@ export default function InviteStatusCard({
|
||||
| "user_does_not_exist"
|
||||
| "not_logged_in"
|
||||
| "user_limit_exceeded"
|
||||
| "oidc_not_allowed"
|
||||
>("rejected");
|
||||
|
||||
useEffect(() => {
|
||||
@@ -70,12 +69,6 @@ export default function InviteStatusCard({
|
||||
function cardType() {
|
||||
if (error.includes("Invite is not for this user")) {
|
||||
return "wrong_user";
|
||||
} else if (
|
||||
error.includes(
|
||||
"Invites can only be accepted by internal users."
|
||||
)
|
||||
) {
|
||||
return "oidc_not_allowed";
|
||||
} else if (
|
||||
error.includes(
|
||||
"User does not exist. Please create an account first."
|
||||
@@ -173,14 +166,6 @@ export default function InviteStatusCard({
|
||||
<p className="text-center">{t("inviteCreateUser")}</p>
|
||||
</div>
|
||||
);
|
||||
} else if (type === "oidc_not_allowed") {
|
||||
return (
|
||||
<div>
|
||||
<p className="text-center mb-4">
|
||||
{t("inviteErrorOidcNotAllowed")}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
} else if (type === "user_limit_exceeded") {
|
||||
return (
|
||||
<div>
|
||||
@@ -214,10 +199,6 @@ export default function InviteStatusCard({
|
||||
);
|
||||
} else if (type === "user_does_not_exist") {
|
||||
return <Button onClick={goToSignup}>{t("createAnAccount")}</Button>;
|
||||
} else if (type === "oidc_not_allowed") {
|
||||
return (
|
||||
<Button onClick={goToLogin}>{t("inviteLogInOtherUser")}</Button>
|
||||
);
|
||||
} else if (type === "user_limit_exceeded") {
|
||||
return (
|
||||
<Button
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
import { InputOTP, InputOTPGroup, InputOTPSlot } from "./ui/input-otp";
|
||||
import { Alert, AlertDescription } from "@app/components/ui/alert";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { REGEXP_ONLY_DIGITS_AND_CHARS } from "input-otp";
|
||||
import { REGEXP_ONLY_DIGITS } from "input-otp";
|
||||
|
||||
const MFA_OTP_INPUT_ID = "mfa-otp-code";
|
||||
|
||||
@@ -82,11 +82,9 @@ export default function MfaInputForm({
|
||||
maxLength={6}
|
||||
{...field}
|
||||
autoComplete="one-time-code"
|
||||
inputMode="text"
|
||||
inputMode="numeric"
|
||||
autoFocus
|
||||
pattern={
|
||||
REGEXP_ONLY_DIGITS_AND_CHARS
|
||||
}
|
||||
pattern={REGEXP_ONLY_DIGITS}
|
||||
onChange={(value: string) => {
|
||||
field.onChange(value);
|
||||
if (value.length === 6) {
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
InfoSections,
|
||||
InfoSectionTitle
|
||||
} from "@app/components/InfoSection";
|
||||
import CopyToClipboard from "@app/components/CopyToClipboard";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
type OrgInfoCardProps = {};
|
||||
@@ -27,9 +26,7 @@ export default function OrgInfoCard({}: OrgInfoCardProps) {
|
||||
</InfoSection>
|
||||
<InfoSection>
|
||||
<InfoSectionTitle>{t("orgId")}</InfoSectionTitle>
|
||||
<InfoSectionContent>
|
||||
<CopyToClipboard text={org.org.orgId} />
|
||||
</InfoSectionContent>
|
||||
<InfoSectionContent>{org.org.orgId}</InfoSectionContent>
|
||||
</InfoSection>
|
||||
<InfoSection>
|
||||
<InfoSectionTitle>{t("subnet")}</InfoSectionTitle>
|
||||
|
||||
@@ -9,15 +9,17 @@ import {
|
||||
FormMessage
|
||||
} from "@app/components/ui/form";
|
||||
|
||||
import { toast } from "@app/hooks/useToast";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
import { useRef } from "react";
|
||||
import type { FieldValues, Path, UseFormReturn } from "react-hook-form";
|
||||
import { RolesSelector, type SelectedRole } from "./roles-selector";
|
||||
|
||||
type OrgRolesTagFieldProps<TFieldValues extends FieldValues> = {
|
||||
form: Pick<
|
||||
UseFormReturn<TFieldValues>,
|
||||
"control" | "getValues" | "setValue" | "clearErrors"
|
||||
"control" | "getValues" | "setValue"
|
||||
>;
|
||||
orgId: string;
|
||||
/** Field in the form that holds Tag[] (role tags). Default: `"roles"`. */
|
||||
@@ -40,6 +42,46 @@ export default function OrgRolesTagField<TFieldValues extends FieldValues>({
|
||||
disabled
|
||||
}: OrgRolesTagFieldProps<TFieldValues>) {
|
||||
const t = useTranslations();
|
||||
const isPopoverOpenRef = useRef(false);
|
||||
const lastValidRolesRef = useRef<SelectedRole[]>(
|
||||
(form.getValues(name) as SelectedRole[]) ?? []
|
||||
);
|
||||
|
||||
function validateRolesSelection() {
|
||||
const current = form.getValues(name) as SelectedRole[];
|
||||
|
||||
if (current.length === 0 && lastValidRolesRef.current.length > 0) {
|
||||
form.setValue(name, lastValidRolesRef.current as never, {
|
||||
shouldDirty: true
|
||||
});
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: t("accessRoleRequired"),
|
||||
description: t("accessRoleSelectPlease")
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (current.length > 0) {
|
||||
lastValidRolesRef.current = current;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function handlePopoverOpenChange(open: boolean) {
|
||||
isPopoverOpenRef.current = open;
|
||||
|
||||
if (open) {
|
||||
const current = form.getValues(name) as SelectedRole[];
|
||||
if (current.length > 0) {
|
||||
lastValidRolesRef.current = current;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
validateRolesSelection();
|
||||
}
|
||||
|
||||
function setRoleTags(nextValue: SelectedRole[]) {
|
||||
const prev = form.getValues(name) as SelectedRole[];
|
||||
@@ -57,14 +99,15 @@ export default function OrgRolesTagField<TFieldValues extends FieldValues>({
|
||||
form.setValue(name, [prev[prev.length - 1]] as never, {
|
||||
shouldDirty: true
|
||||
});
|
||||
form.clearErrors(name);
|
||||
return;
|
||||
}
|
||||
|
||||
form.setValue(name, next as never, { shouldDirty: true });
|
||||
|
||||
if (next.length > 0) {
|
||||
form.clearErrors(name);
|
||||
if (next.length > 0 && !isPopoverOpenRef.current) {
|
||||
lastValidRolesRef.current = next;
|
||||
} else if (!isPopoverOpenRef.current) {
|
||||
validateRolesSelection();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,6 +117,9 @@ export default function OrgRolesTagField<TFieldValues extends FieldValues>({
|
||||
name={name}
|
||||
render={({ field }) => {
|
||||
const selectedRoles = (field.value ?? []) as SelectedRole[];
|
||||
if (!isPopoverOpenRef.current && selectedRoles.length > 0) {
|
||||
lastValidRolesRef.current = selectedRoles;
|
||||
}
|
||||
|
||||
return (
|
||||
<FormItem className="flex flex-col items-start">
|
||||
@@ -83,6 +129,7 @@ export default function OrgRolesTagField<TFieldValues extends FieldValues>({
|
||||
orgId={orgId}
|
||||
selectedRoles={selectedRoles}
|
||||
onSelectRoles={setRoleTags}
|
||||
onPopoverOpenChange={handlePopoverOpenChange}
|
||||
disabled={disabled}
|
||||
/>
|
||||
</FormControl>
|
||||
|
||||
@@ -115,11 +115,8 @@ function getActionsCategories(root: boolean) {
|
||||
},
|
||||
|
||||
"Resource Policy": {
|
||||
[t("actionListResourcePolicies")]: "listResourcePolicies",
|
||||
[t("actionCreateResourcePolicy")]: "createResourcePolicy",
|
||||
[t("actionGetResourcePolicy")]: "getResourcePolicy",
|
||||
[t("actionUpdateResourcePolicy")]: "updateResourcePolicy",
|
||||
[t("actionDeleteResourcePolicy")]: "deleteResourcePolicy",
|
||||
[t("actionSetResourcePolicyUsers")]: "setResourcePolicyUsers",
|
||||
[t("actionSetResourcePolicyRoles")]: "setResourcePolicyRoles",
|
||||
[t("actionSetResourcePolicyPassword")]: "setResourcePolicyPassword",
|
||||
|
||||
@@ -56,7 +56,6 @@ type SmartLoginFormProps = {
|
||||
defaultUser?: string;
|
||||
orgSignIn?: OrgSignInConfig;
|
||||
lastUsedIdp?: (LoginFormIDP & { orgId?: string }) | null;
|
||||
inviteMode?: boolean;
|
||||
};
|
||||
|
||||
type ViewState =
|
||||
@@ -94,8 +93,7 @@ export default function SmartLoginForm({
|
||||
forceLogin,
|
||||
defaultUser,
|
||||
orgSignIn,
|
||||
lastUsedIdp,
|
||||
inviteMode = false
|
||||
lastUsedIdp
|
||||
}: SmartLoginFormProps) {
|
||||
const router = useRouter();
|
||||
const { env } = useEnvContext();
|
||||
@@ -138,10 +136,6 @@ export default function SmartLoginForm({
|
||||
return;
|
||||
}
|
||||
|
||||
const signupUrl = redirect
|
||||
? `/auth/signup?email=${encodeURIComponent(identifier)}&redirect=${encodeURIComponent(redirect)}&fromSmartLogin=true`
|
||||
: `/auth/signup?email=${encodeURIComponent(identifier)}&fromSmartLogin=true`;
|
||||
|
||||
if (!result.found || result.accounts.length === 0) {
|
||||
// No accounts found
|
||||
if (!isEmail || forceLogin) {
|
||||
@@ -153,36 +147,13 @@ export default function SmartLoginForm({
|
||||
return;
|
||||
}
|
||||
// Valid email but no accounts and not forceLogin - redirect to signup
|
||||
const signupUrl = redirect
|
||||
? `/auth/signup?email=${encodeURIComponent(identifier)}&redirect=${encodeURIComponent(redirect)}&fromSmartLogin=true`
|
||||
: `/auth/signup?email=${encodeURIComponent(identifier)}&fromSmartLogin=true`;
|
||||
router.push(signupUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
// Invite accept only supports internal (password) accounts
|
||||
if (inviteMode) {
|
||||
const internalAccount = result.accounts.find(
|
||||
(acc) => acc.hasInternalAuth
|
||||
);
|
||||
if (internalAccount) {
|
||||
setViewState({
|
||||
type: "password",
|
||||
identifier,
|
||||
account: internalAccount
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isEmail && !forceLogin) {
|
||||
router.push(signupUrl);
|
||||
return;
|
||||
}
|
||||
|
||||
form.setError("identifier", {
|
||||
type: "manual",
|
||||
message: t("inviteLoginInternalOnly")
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine which view to show
|
||||
const account = result.accounts[0]; // Use first account for now
|
||||
|
||||
|
||||
@@ -15,14 +15,11 @@ import {
|
||||
} from "@app/components/ui/popover";
|
||||
import { cn } from "@app/lib/cn";
|
||||
import { ListUserOrgsResponse } from "@server/routers/org";
|
||||
import { Check, ChevronDown, Plus } from "lucide-react";
|
||||
import { Check, ChevronDown, ChevronsUpDown } from "lucide-react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Button } from "@app/components/ui/button";
|
||||
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||
import { useUserContext } from "@app/hooks/useUserContext";
|
||||
import { build } from "@server/build";
|
||||
|
||||
type LauncherOrgSelectorProps = {
|
||||
orgId?: string;
|
||||
@@ -34,16 +31,9 @@ export function LauncherOrgSelector({ orgId, orgs }: LauncherOrgSelectorProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const t = useTranslations();
|
||||
const { env } = useEnvContext();
|
||||
const { user } = useUserContext();
|
||||
|
||||
const selectedOrg = orgs?.find((org) => org.orgId === orgId);
|
||||
|
||||
let canCreateOrg = !env.flags.disableUserCreateOrg || user.serverAdmin;
|
||||
if (build === "saas" && user.type !== "internal") {
|
||||
canCreateOrg = false;
|
||||
}
|
||||
|
||||
const sortedOrgs = useMemo(() => {
|
||||
if (!orgs?.length) {
|
||||
return orgs ?? [];
|
||||
@@ -118,22 +108,6 @@ export function LauncherOrgSelector({ orgId, orgs }: LauncherOrgSelectorProps) {
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
{canCreateOrg && (
|
||||
<div className="p-2 border-t border-border">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full justify-start h-8 font-normal text-muted-foreground"
|
||||
onClick={() => {
|
||||
setOpen(false);
|
||||
router.push("/setup");
|
||||
}}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5 mr-2" />
|
||||
{t("setupNewOrg")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
|
||||
@@ -111,7 +111,7 @@ export function useCertificate({
|
||||
let certError: string | null = null;
|
||||
if (restartCert.isError) {
|
||||
certError = "Failed to restart";
|
||||
} else if (isError || (!isLoading && data === null)) {
|
||||
} else if (isError || initialCertValue === null) {
|
||||
// Null value means failed to get the certificate
|
||||
certError = "Failed";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user