Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Enforce org email restrictions in policy
Richie McIlroy5de97a9c3fea
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/AccessEmailDomain.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/AccessEmailDomain.tsxindex 725c3cddf..d12feffd8 100644--- a/apps/web/app/(org)/dashboard/settings/organization/components/AccessEmailDomain.tsx+++ b/apps/web/app/(org)/dashboard/settings/organization/components/AccessEmailDomain.tsx@@ -1,4 +1,4 @@-import { Button, Input, Label } from "@cap/ui";+import { Button, Label } from "@cap/ui";import type { Organisation } from "@cap/web-domain";import { useRouter } from "next/navigation";import { useState } from "react";@@ -35,19 +35,31 @@ export const AccessEmailDomain = () => {return (<div className="flex-1 space-y-4"><div className="space-y-1">- <Label htmlFor="allowedEmailDomain">Access email domain</Label>+ <Label htmlFor="allowedEmailDomain">Email access restriction</Label><p className="text-sm text-gray-10">- Only emails from this domain can access shared videos.{" "}- <span className="font-medium text-sm text-gray-11 leading-[0px]">- Leave blank to allow everyone.+ Restrict who can access public "anyone with the link" videos. Add+ email domains (e.g.{" "}+ <code className="text-xs bg-gray-3 px-1 py-0.5 rounded">+ company.com+ </code>+ ) or specific email addresses (e.g.{" "}+ <code className="text-xs bg-gray-3 px-1 py-0.5 rounded">+ </code>+ ), separated by commas.+ </p>+ <p className="text-sm text-gray-10">+ Members of your organization and spaces can always access videos+ shared with them, regardless of this setting.{" "}+ <span className="font-medium text-gray-11">+ Leave blank to allow anyone with the link.</span></p></div>- <div className="flex flex-col gap-3 w-full md:items-center md:flex-row h-fit">- <Input- type="text"- className="bg-gray-2"- placeholder="e.g. company.com"+ <div className="flex flex-col gap-3 w-full h-fit">+ <textarea+ className="flex px-4 py-3 w-full font-thin transition-all duration-200 text-[16px] md:text-[13px] text-gray-12 bg-gray-1 border-gray-4 outline-0 focus:bg-gray-2 rounded-xl hover:bg-gray-2 border-[1px] focus:border-gray-5 placeholder:text-gray-8 ring-0 ring-gray-2 focus:ring-1 focus:ring-gray-12 focus:ring-offset-2 ring-offset-gray-3 hover:placeholder:text-gray-12 placeholder:duration-200 min-h-[72px] resize-y"+ placeholder="e.g. company.com, partner.org, [email protected]"value={emailDomain || ""}id="allowedEmailDomain"name="allowedEmailDomain"@@ -55,20 +67,23 @@ export const AccessEmailDomain = () => {setEmailDomain(e.target.value);}}/>- <Button- className="min-w-fit"- type="submit"- spinner={saveLoading}- size="sm"- variant="dark"- disabled={- saveLoading ||- emailDomain === activeOrganization?.organization.allowedEmailDomain- }- onClick={handleEmailDomainSave}- >- {saveLoading ? null : "Save"}- </Button>+ <div>+ <Button+ className="min-w-fit"+ type="submit"+ spinner={saveLoading}+ size="sm"+ variant="dark"+ disabled={+ saveLoading ||+ emailDomain ===+ activeOrganization?.organization.allowedEmailDomain+ }+ onClick={handleEmailDomainSave}+ >+ {saveLoading ? null : "Save"}+ </Button>+ </div></div></div>);diff --git a/apps/web/app/embed/[videoId]/page.tsx b/apps/web/app/embed/[videoId]/page.tsxindex 42b825388..3b1940099 100644--- a/apps/web/app/embed/[videoId]/page.tsx+++ b/apps/web/app/embed/[videoId]/page.tsx@@ -153,7 +153,6 @@ export default async function EmbedVideoPage(hasActiveUpload: sql`${videoUploads.videoId} IS NOT NULL`.mapWith(Boolean,),- orgAllowedEmailDomain: organizations.allowedEmailDomain,}).from(videos).leftJoin(sharedVideos, eq(videos.id, sharedVideos.videoId))@@ -202,7 +201,6 @@ async function EmbedContent({video: Omit<typeof videos.$inferSelect, "password"> & {sharedOrganization: { organizationId: Organisation.OrganisationId } | null;hasActiveUpload: boolean | undefined;- orgAllowedEmailDomain?: string | null;};autoplay: boolean;}) {@@ -224,37 +222,6 @@ async function EmbedContent({aiGenerationEnabled = await isAiGenerationEnabled(videoOwner);}- const domainToCheck =- video.orgAllowedEmailDomain ??- (video.sharedOrganization?.organizationId- ? (- await db()- .select({ allowedEmailDomain: organizations.allowedEmailDomain })- .from(organizations)- .where(- eq(organizations.id, video.sharedOrganization.organizationId),- )- .limit(1)- )?.[0]?.allowedEmailDomain- : null);-- if (domainToCheck) {- if (!user?.email || !user.email.endsWith(`@${domainToCheck}`)) {- return (- <div className="flex flex-col justify-center items-center min-h-screen text-center text-white bg-black">- <h1 className="mb-4 text-2xl font-bold">Access Restricted</h1>- <p className="mb-2 text-gray-300">- This video is only accessible to members of this organization.- </p>- <p className="text-gray-400">- Please sign in with your organization email address to access this- content.- </p>- </div>- );- }- }-if (video.transcriptionStatus !== "COMPLETE" &&video.transcriptionStatus !== "PROCESSING" &&diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsxindex 63891cd18..0ca9e5930 100644--- a/apps/web/app/s/[videoId]/page.tsx+++ b/apps/web/app/s/[videoId]/page.tsx@@ -313,7 +313,6 @@ export default async function ShareVideoPage(props: PageProps<"/s/[videoId]">) {organizationId: sharedVideos.organizationId,},orgSettings: organizations.settings,- orgAllowedEmailDomain: organizations.allowedEmailDomain,hasActiveUpload: sql`${videoUploads.videoId} IS NOT NULL`.mapWith(Boolean,),@@ -361,7 +360,6 @@ async function AuthorizedContent({hasPassword: boolean;hasActiveUpload: boolean;orgSettings?: OrganizationSettings | null;- orgAllowedEmailDomain?: string | null;videoSettings?: OrganizationSettings | null;};searchParams: { [key: string]: string | string[] | undefined };@@ -421,37 +419,6 @@ async function AuthorizedContent({aiGenerationEnabled = await isAiGenerationEnabled(videoOwner);}- const domainToCheck =- video.orgAllowedEmailDomain ??- (video.sharedOrganization?.organizationId- ? (- await db()- .select({ allowedEmailDomain: organizations.allowedEmailDomain })- .from(organizations)- .where(- eq(organizations.id, video.sharedOrganization.organizationId),- )- .limit(1)- )?.[0]?.allowedEmailDomain- : null);-- if (domainToCheck) {- if (!user?.email || !user.email.endsWith(`@${domainToCheck}`)) {- return (- <div className="flex flex-col justify-center items-center p-4 min-h-screen text-center">- <h1 className="mb-4 text-2xl font-bold">Access Restricted</h1>- <p className="mb-2 text-gray-10">- This video is only accessible to members of this organization.- </p>- <p className="text-gray-600">- Please sign in with your organization email address to access this- content.- </p>- </div>- );- }- }-if (!video.hasActiveUpload &&video.transcriptionStatus !== "COMPLETE" &&diff --git a/packages/utils/src/helpers.ts b/packages/utils/src/helpers.tsindex 4ea505db7..d847bc276 100644--- a/packages/utils/src/helpers.ts+++ b/packages/utils/src/helpers.ts@@ -80,3 +80,24 @@ export const getDisplayProgress = () => {return uploadProgress !== undefined ? uploadProgress : processingProgress;};++export function isEmailAllowedByRestriction(+ email: string,+ restriction: string,+): boolean {+ const entries = restriction+ .split(",")+ .map((e) => e.trim().toLowerCase())+ .filter(Boolean);++ if (entries.length === 0) return true;++ const lowerEmail = email.toLowerCase();++ return entries.some((entry) => {+ if (entry.includes("@")) {+ return lowerEmail === entry;+ }+ return lowerEmail.endsWith(`@${entry}`);+ });+}diff --git a/packages/web-backend/src/Organisations/OrganisationsRepo.ts b/packages/web-backend/src/Organisations/OrganisationsRepo.tsindex 332eb753b..b35bac4ef 100644--- a/packages/web-backend/src/Organisations/OrganisationsRepo.ts+++ b/packages/web-backend/src/Organisations/OrganisationsRepo.ts@@ -1,7 +1,7 @@import * as Db from "@cap/database/schema";import type { Organisation, User, Video } from "@cap/web-domain";import * as Dz from "drizzle-orm";-import { Array, Effect } from "effect";+import { Array, Effect, Option } from "effect";import { Database } from "../Database.ts";@@ -48,6 +48,25 @@ export class OrganisationsRepo extends Effect.Service<OrganisationsRepo>()(),).pipe(Effect.map(Array.get(0))),+ allowedEmailDomain: (orgId: Organisation.OrganisationId) =>+ db+ .use((db) =>+ db+ .select({+ allowedEmailDomain: Db.organizations.allowedEmailDomain,+ })+ .from(Db.organizations)+ .where(Dz.eq(Db.organizations.id, orgId))+ .limit(1),+ )+ .pipe(+ Effect.map(Array.get(0)),+ Effect.map(+ Option.flatMap((row) =>+ Option.fromNullable(row.allowedEmailDomain),+ ),+ ),+ ),};}),dependencies: [Database.Default],diff --git a/packages/web-backend/src/Videos/VideosPolicy.ts b/packages/web-backend/src/Videos/VideosPolicy.tsindex 17bf7886f..2ba7ecb31 100644--- a/packages/web-backend/src/Videos/VideosPolicy.ts+++ b/packages/web-backend/src/Videos/VideosPolicy.ts@@ -1,3 +1,4 @@+import { isEmailAllowedByRestriction } from "@cap/utils";import { Policy, Video } from "@cap/web-domain";import { Array, Effect, Option } from "effect";@@ -6,6 +7,101 @@ import { OrganisationsRepo } from "../Organisations/OrganisationsRepo.ts";import { SpacesRepo } from "../Spaces/SpacesRepo.ts";import { VideosRepo } from "./VideosRepo.ts";+export type VideosPolicyDeps = {+ repo: {+ getById: (+ id: Video.VideoId,+ ) => Effect.Effect<+ Option.Option<readonly [Video.Video, Option.Option<string>]>,+ any+ >;+ };+ orgsRepo: {+ membershipForVideo: (+ userId: any,+ videoId: Video.VideoId,+ ) => Effect.Effect<readonly { membershipId: string }[], any>;+ allowedEmailDomain: (+ orgId: any,+ ) => Effect.Effect<Option.Option<string>, any>;+ };+ spacesRepo: {+ membershipForVideo: (+ userId: any,+ videoId: Video.VideoId,+ ) => Effect.Effect<Option.Option<{ membershipId: string }>, any>;+ };+};++export function buildCanView(+ { repo, orgsRepo, spacesRepo }: VideosPolicyDeps,+ videoId: Video.VideoId,+) {+ return Policy.publicPolicy(+ Effect.fn(function* (user) {+ const res = yield* repo.getById(videoId);++ if (Option.isNone(res)) {+ yield* Effect.log("Video not found. Access granted.");+ return true;+ }++ const [video, password] = res.value;++ if (Option.isSome(user)) {+ const userId = user.value.id;+ if (userId === video.ownerId) return true;++ const [videoOrgShareMembership, videoSpaceShareMembership] =+ yield* Effect.all([+ orgsRepo+ .membershipForVideo(userId, video.id)+ .pipe(Effect.map(Array.get(0))),+ spacesRepo.membershipForVideo(userId, video.id),+ ]);++ if (+ Option.isSome(videoOrgShareMembership) ||+ Option.isSome(videoSpaceShareMembership)+ ) {+ yield* Effect.log(+ "Explicit org/space membership found. Access granted.",+ );+ yield* Video.verifyPassword(video, password);+ return true;+ }+ }++ if (!video.public) {+ yield* Effect.log(+ "Video is private and user has no explicit access. Access denied.",+ );+ return false;+ }++ const allowedEmails = yield* orgsRepo.allowedEmailDomain(video.orgId);++ if (Option.isSome(allowedEmails)) {+ const restriction = allowedEmails.value;+ if (Option.isNone(user)) {+ yield* Effect.log(+ "Email access restriction active and user not logged in. Access denied.",+ );+ return false;+ }+ if (!isEmailAllowedByRestriction(user.value.email, restriction)) {+ yield* Effect.log("Email access restriction active. Access denied.");+ return false;+ }+ }++ yield* Video.verifyPassword(video, password);++ return true;+ }),+ );+}+export class VideosPolicy extends Effect.Service<VideosPolicy>()("VideosPolicy",{@@ -14,63 +110,9 @@ export class VideosPolicy extends Effect.Service<VideosPolicy>()(const orgsRepo = yield* OrganisationsRepo;const spacesRepo = yield* SpacesRepo;- const canView = (videoId: Video.VideoId) =>- Policy.publicPolicy(- Effect.fn(function* (user) {- const res = yield* repo.getById(videoId);-- if (Option.isNone(res)) {- yield* Effect.log("Video not found. Access granted.");- return true;- }-- const [video, password] = res.value;-- if (Option.isSome(user)) {- const userId = user.value.id;- if (userId === video.ownerId) return true;-- if (!video.public) {- const [videoOrgShareMembership, videoSpaceShareMembership] =- yield* Effect.all([- orgsRepo- .membershipForVideo(userId, video.id)- .pipe(Effect.map(Array.get(0))),- spacesRepo.membershipForVideo(userId, video.id),- ]);-- if (- Option.isNone(videoOrgShareMembership) &&- Option.isNone(videoSpaceShareMembership)- ) {- yield* Effect.log(- "Neither org nor space sharing found. Access denied.",- );- return false;- }-- if (Option.isSome(videoOrgShareMembership)) {- yield* Effect.log("Org sharing found.");- }-- if (Option.isSome(videoSpaceShareMembership)) {- yield* Effect.log("Space sharing found.");- }- }- } else {- if (!video.public) {- yield* Effect.log(- "Video is private and user is not logged in. Access denied.",- );- return false;- }- }-- yield* Video.verifyPassword(video, password);-- return true;- }),- );+ const deps: VideosPolicyDeps = { repo, orgsRepo, spacesRepo };++ const canView = (videoId: Video.VideoId) => buildCanView(deps, videoId);const isOwner = (videoId: Video.VideoId) =>Policy.policy((user) =>diff --git a/packages/web-backend/src/index.ts b/packages/web-backend/src/index.tsindex 011fca9ce..92c6282c5 100644--- a/packages/web-backend/src/index.ts+++ b/packages/web-backend/src/index.ts@@ -14,6 +14,10 @@ export { SpacesPolicy } from "./Spaces/SpacesPolicy.ts";export { Tinybird } from "./Tinybird/index.ts";export { Users } from "./Users/index.ts";export { Videos } from "./Videos/index.ts";-export { VideosPolicy } from "./Videos/VideosPolicy.ts";+export {+ buildCanView,+ VideosPolicy,+ type VideosPolicyDeps,+} from "./Videos/VideosPolicy.ts";export { VideosRepo } from "./Videos/VideosRepo.ts";export * as Workflows from "./Workflows.ts";