Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(web): address review feedback on public collection pages

Richie McIlroy6ed2a6ea399a
diff --git a/apps/web/__tests__/unit/public-collections-policy.test.ts b/apps/web/__tests__/unit/public-collections-policy.test.ts
index c05dc14a2..70e1c86a5 100644
--- a/apps/web/__tests__/unit/public-collections-policy.test.ts
+++ b/apps/web/__tests__/unit/public-collections-policy.test.ts
@@ -76,7 +76,7 @@ describe("public collections policy", () => {
allowedEmailDomain: "company.com",
viewerEmail: null,
passwordHash: "hash",
- verifiedPasswordHash: null,
+ verifiedPasswordHashes: [],
}),
).toEqual({ state: "email_restriction_login_required" });
@@ -85,7 +85,7 @@ describe("public collections policy", () => {
allowedEmailDomain: "company.com",
viewerEmail: "[email protected]",
passwordHash: "hash",
- verifiedPasswordHash: null,
+ verifiedPasswordHashes: [],
}),
).toEqual({ state: "email_restriction_denied" });
});
@@ -95,7 +95,7 @@ describe("public collections policy", () => {
resolvePublicCollectionAccess({
viewerEmail: "[email protected]",
passwordHash: "space-hash",
- verifiedPasswordHash: null,
+ verifiedPasswordHashes: [],
}),
).toEqual({ state: "password_required" });
@@ -103,8 +103,26 @@ describe("public collections policy", () => {
resolvePublicCollectionAccess({
viewerEmail: "[email protected]",
passwordHash: "space-hash",
- verifiedPasswordHash: "space-hash",
+ verifiedPasswordHashes: ["space-hash"],
}),
).toEqual({ state: "allowed" });
});
+
+ it("matches the collection password against any verified hash", () => {
+ expect(
+ resolvePublicCollectionAccess({
+ viewerEmail: "[email protected]",
+ passwordHash: "space-hash",
+ verifiedPasswordHashes: ["video-hash", "space-hash"],
+ }),
+ ).toEqual({ state: "allowed" });
+
+ expect(
+ resolvePublicCollectionAccess({
+ viewerEmail: "[email protected]",
+ passwordHash: "space-hash",
+ verifiedPasswordHashes: ["video-hash"],
+ }),
+ ).toEqual({ state: "password_required" });
+ });
});
diff --git a/apps/web/__tests__/unit/videos-policy.test.ts b/apps/web/__tests__/unit/videos-policy.test.ts
index 35e1147b0..8929c3ab5 100644
--- a/apps/web/__tests__/unit/videos-policy.test.ts
+++ b/apps/web/__tests__/unit/videos-policy.test.ts
@@ -85,7 +85,7 @@ function makeDeps(config: {
function runCanView(
deps: VideosPolicyDeps,
user: Option.Option<CurrentUser["Type"]>,
- attachedPassword: Option.Option<string> = Option.none(),
+ attachedPasswords: ReadonlyArray<string> = [],
): Promise<"allowed" | "denied" | "password"> {
const policy = buildCanView(deps, TEST_VIDEO_ID);
@@ -99,13 +99,12 @@ function runCanView(
),
);
- const withPassword = Option.match(attachedPassword, {
- onNone: () => program,
- onSome: (password) =>
- Effect.provideService(program, Video.VideoPasswordAttachment, {
- password: Option.some(password),
- }),
- });
+ const withPassword =
+ attachedPasswords.length === 0
+ ? program
+ : Effect.provideService(program, Video.VideoPasswordAttachment, {
+ passwords: attachedPasswords,
+ });
const withUser = user.pipe(
Option.match({
@@ -272,9 +271,9 @@ describe("VideosPolicy.canView", () => {
spacePasswords: ["space-one-hash", "space-two-hash"],
});
- expect(
- await runCanView(deps, noUser, Option.some("space-two-hash")),
- ).toBe("allowed");
+ expect(await runCanView(deps, noUser, ["space-two-hash"])).toBe(
+ "allowed",
+ );
});
it("allows access with either video or space password hash", async () => {
@@ -284,11 +283,29 @@ describe("VideosPolicy.canView", () => {
spacePasswords: ["space-hash"],
});
- expect(await runCanView(deps, noUser, Option.some("video-hash"))).toBe(
- "allowed",
- );
- expect(await runCanView(deps, noUser, Option.some("space-hash"))).toBe(
- "allowed",
+ expect(await runCanView(deps, noUser, ["video-hash"])).toBe("allowed");
+ expect(await runCanView(deps, noUser, ["space-hash"])).toBe("allowed");
+ });
+
+ it("allows access when the matching hash sits alongside other verified hashes", async () => {
+ const deps = makeDeps({
+ video: makeVideo({ public: true }),
+ password: Option.some("video-hash"),
+ });
+
+ expect(
+ await runCanView(deps, noUser, ["collection-hash", "video-hash"]),
+ ).toBe("allowed");
+ });
+
+ it("requires a password when no verified hash matches", async () => {
+ const deps = makeDeps({
+ video: makeVideo({ public: true }),
+ password: Option.some("video-hash"),
+ });
+
+ expect(await runCanView(deps, noUser, ["collection-hash"])).toBe(
+ "password",
);
});
});
diff --git a/apps/web/actions/collections/logo.ts b/apps/web/actions/collections/logo.ts
index 0ee0a7fad..721d090bd 100644
--- a/apps/web/actions/collections/logo.ts
+++ b/apps/web/actions/collections/logo.ts
@@ -102,7 +102,9 @@ async function setSpaceLogo(
if (!space) return { success: false, error: "Space not found" };
- const access = await getSpaceAccess(userId, id).catch(() => null);
+ // getSpaceAccess returns null for expected denials; genuine failures must
+ // propagate instead of being misreported as "Unauthorized".
+ const access = await getSpaceAccess(userId, id);
if (!access?.canManage) return { success: false, error: "Unauthorized" };
if (!(await isOrganizationOwnerPro(space.organizationId))) {
@@ -170,14 +172,11 @@ async function setFolderLogo(
: folder.spaceId === folder.organizationId
? canManageSpace({
organizationRole: (
- await getOrganizationAccess(userId, folder.organizationId).catch(
- () => null,
- )
+ await getOrganizationAccess(userId, folder.organizationId)
)?.role,
spaceRole: null,
})
- : ((await getSpaceAccess(userId, folder.spaceId).catch(() => null))
- ?.canManage ?? false);
+ : ((await getSpaceAccess(userId, folder.spaceId))?.canManage ?? false);
if (!canManage) return { success: false, error: "Unauthorized" };
if (!(await isOrganizationOwnerPro(folder.organizationId))) {
diff --git a/apps/web/actions/collections/password.ts b/apps/web/actions/collections/password.ts
index 2443a9813..7a77f82b3 100644
--- a/apps/web/actions/collections/password.ts
+++ b/apps/web/actions/collections/password.ts
@@ -41,7 +41,7 @@ export async function verifyCollectionPassword(
) {
try {
if (!collectionId || typeof password !== "string") {
- throw new Error("Missing data");
+ return { success: false, error: "Failed to verify password" };
}
if (await isRateLimited()) {
@@ -51,11 +51,16 @@ export async function verifyCollectionPassword(
};
}
+ // Missing hash and wrong password are expected outcomes (typos, links to
+ // collections whose password was since removed) — return without logging
+ // so console.error stays reserved for genuine failures.
const passwordHash = await getPublicCollectionPasswordHash(collectionId);
- if (!passwordHash) throw new Error("No password set");
-
- const valid = await verifyPlainPassword(passwordHash, password);
- if (!valid) throw new Error("Invalid password");
+ const valid = passwordHash
+ ? await verifyPlainPassword(passwordHash, password)
+ : false;
+ if (!passwordHash || !valid) {
+ return { success: false, error: "Failed to verify password" };
+ }
await setVerifiedPasswordCookie(passwordHash);
revalidatePath(`/c/${encodeURIComponent(collectionId)}`);
diff --git a/apps/web/actions/collections/visibility.ts b/apps/web/actions/collections/visibility.ts
index b5871c6bc..ba80376d2 100644
--- a/apps/web/actions/collections/visibility.ts
+++ b/apps/web/actions/collections/visibility.ts
@@ -8,7 +8,7 @@ import { eq, type SQL, sql } from "drizzle-orm";
import { Either, Schema } from "effect";
import { revalidatePath } from "next/cache";
import { isOrganizationOwnerPro } from "@/lib/org-pro";
-import { requireSpaceManager } from "../organization/space-authorization";
+import { getSpaceAccess } from "../organization/space-authorization";
const decodeSettingsPatch = Schema.decodeUnknownEither(
PublicCollection.PublicPageSettingsUpdate,
@@ -50,6 +50,9 @@ export async function setSpaceCollectionVisibility(input: {
const id = Space.SpaceId.make(input.spaceId);
+ // getSpaceAccess returns null for the expected denials (missing space, no
+ // membership) and only throws on genuine failures, which must propagate
+ // instead of being misreported as "Unauthorized".
const [[space], access] = await Promise.all([
db()
.select({
@@ -59,11 +62,11 @@ export async function setSpaceCollectionVisibility(input: {
.from(spaces)
.where(eq(spaces.id, id))
.limit(1),
- requireSpaceManager(user.id, id).catch(() => null),
+ getSpaceAccess(user.id, id),
]);
if (!space) return { success: false, error: "Space not found" };
- if (!access) return { success: false, error: "Unauthorized" };
+ if (!access?.canManage) return { success: false, error: "Unauthorized" };
const enablingPublic = input.public === true && !space.public;
const changingSettings = settingsPatch !== undefined;
diff --git a/apps/web/actions/organization/update-space.ts b/apps/web/actions/organization/update-space.ts
index b1caba2a6..aefaa2d54 100644
--- a/apps/web/actions/organization/update-space.ts
+++ b/apps/web/actions/organization/update-space.ts
@@ -19,7 +19,7 @@ import { revalidatePath } from "next/cache";
import { isOrganizationOwnerPro } from "@/lib/org-pro";
import { normalizeSpaceRole } from "@/lib/permissions/roles";
import { runPromise } from "@/lib/server";
-import { requireSpaceManager } from "./space-authorization";
+import { getSpaceAccess } from "./space-authorization";
import {
getSpaceSettingsFromFormData,
preserveProSpaceSettings,
@@ -60,8 +60,10 @@ export async function updateSpace(formData: FormData) {
return { success: false, error: "Space not found" };
}
- const access = await requireSpaceManager(user.id, id).catch(() => null);
- if (!access) {
+ // getSpaceAccess returns null for expected denials; genuine failures must
+ // propagate instead of being misreported as "Unauthorized".
+ const access = await getSpaceAccess(user.id, id);
+ if (!access?.canManage) {
return { success: false, error: "Unauthorized" };
}
diff --git a/apps/web/actions/videos/password.ts b/apps/web/actions/videos/password.ts
index ec199d2e4..f8c8dc81d 100644
--- a/apps/web/actions/videos/password.ts
+++ b/apps/web/actions/videos/password.ts
@@ -89,14 +89,14 @@ export async function verifyVideoPassword(
) {
try {
if (!videoId || typeof password !== "string")
- throw new Error("Missing data");
+ return { success: false, error: "Failed to verify password" };
const [video] = await db()
.select()
.from(videos)
.where(eq(videos.id, videoId));
- if (!video) throw new Error("No password set");
+ if (!video) return { success: false, error: "Failed to verify password" };
const spacePasswords = await db()
.select({ password: spaces.password })
@@ -109,8 +109,6 @@ export async function verifyVideoPassword(
spacePasswords,
});
- if (passwordHashes.length === 0) throw new Error("No password set");
-
for (const passwordHash of passwordHashes) {
const valid = await verifyPlainPassword(passwordHash, password);
if (valid) {
@@ -119,7 +117,9 @@ export async function verifyVideoPassword(
}
}
- throw new Error("Invalid password");
+ // Wrong passwords and links whose password was since removed are expected
+ // outcomes — return without logging so console.error stays signal.
+ return { success: false, error: "Failed to verify password" };
} catch (error) {
console.error("Error verifying video password:", error);
return { success: false, error: "Failed to verify password" };
diff --git a/apps/web/lib/password-cookie.ts b/apps/web/lib/password-cookie.ts
index 138371047..9a213702f 100644
--- a/apps/web/lib/password-cookie.ts
+++ b/apps/web/lib/password-cookie.ts
@@ -1,18 +1,68 @@
import "server-only";
-import { encrypt } from "@cap/database/crypto";
+import { decrypt, encrypt } from "@cap/database/crypto";
import { cookies } from "next/headers";
+const COOKIE_NAME = "x-cap-password";
+
+// A verified hash is ~64 base64 chars, so 10 entries encrypt to well under
+// the 4KB cookie limit while covering any realistic number of concurrently
+// open password-protected shares.
+const MAX_VERIFIED_HASHES = 10;
+
+/**
+ * Every share password (video or collection) this browser has verified. The
+ * cookie holds an encrypted JSON array of password hashes so unlocking one
+ * resource never evicts another; pre-array cookies that hold a single bare
+ * hash are still accepted.
+ */
+export async function getVerifiedPasswordHashes(): Promise<string[]> {
+ const cookieValue = (await cookies()).get(COOKIE_NAME)?.value;
+ if (!cookieValue) return [];
+
+ let decrypted: string;
+ try {
+ // decrypt is async — without the await its rejection (corrupt or stale
+ // cookie, rotated encryption key) would escape this catch and crash the
+ // page instead of falling back to the password prompt.
+ decrypted = await decrypt(cookieValue);
+ } catch {
+ return [];
+ }
+
+ try {
+ const parsed: unknown = JSON.parse(decrypted);
+ if (
+ Array.isArray(parsed) &&
+ parsed.every((hash) => typeof hash === "string")
+ ) {
+ return parsed;
+ }
+ } catch {
+ // Legacy cookie: the decrypted value is the hash itself.
+ }
+ return [decrypted];
+}
+
/**
* Marks a share password (video or collection) as verified for this browser
- * session. The cookie is shared by the `/s/` and `/c/` flows, holds only the
- * encrypted hash, and is never read client-side — so it can be locked down.
+ * session. The cookie is shared by the `/s/` and `/c/` flows and is never
+ * read client-side — so it can be locked down.
*/
export async function setVerifiedPasswordCookie(passwordHash: string) {
- (await cookies()).set("x-cap-password", await encrypt(passwordHash), {
- httpOnly: true,
- secure: process.env.NODE_ENV === "production",
- sameSite: "lax",
- path: "/",
- });
+ const hashes = (await getVerifiedPasswordHashes()).filter(
+ (hash) => hash !== passwordHash,
+ );
+ hashes.push(passwordHash);
+
+ (await cookies()).set(
+ COOKIE_NAME,
+ await encrypt(JSON.stringify(hashes.slice(-MAX_VERIFIED_HASHES))),
+ {
+ httpOnly: true,
+ secure: process.env.NODE_ENV === "production",
+ sameSite: "lax",
+ path: "/",
+ },
+ );
}
diff --git a/apps/web/lib/public-collections-policy.ts b/apps/web/lib/public-collections-policy.ts
index 0dd617289..5d42e5f04 100644
--- a/apps/web/lib/public-collections-policy.ts
+++ b/apps/web/lib/public-collections-policy.ts
@@ -55,12 +55,12 @@ export function resolvePublicCollectionAccess({
allowedEmailDomain,
viewerEmail,
passwordHash,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
}: {
allowedEmailDomain?: string | null;
viewerEmail?: string | null;
passwordHash?: string | null;
- verifiedPasswordHash?: string | null;
+ verifiedPasswordHashes?: readonly string[];
}): PublicCollectionAccess {
const restriction = allowedEmailDomain?.trim() ?? "";
@@ -72,7 +72,7 @@ export function resolvePublicCollectionAccess({
}
}
- if (passwordHash && passwordHash !== verifiedPasswordHash) {
+ if (passwordHash && !verifiedPasswordHashes?.includes(passwordHash)) {
return { state: "password_required" };
}
diff --git a/apps/web/lib/public-collections.ts b/apps/web/lib/public-collections.ts
index fbe48d8b2..263f2bb0c 100644
--- a/apps/web/lib/public-collections.ts
+++ b/apps/web/lib/public-collections.ts
@@ -2,7 +2,6 @@ import "server-only";
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
-import { decrypt } from "@cap/database/crypto";
import {
comments,
folders,
@@ -27,8 +26,8 @@ import {
} from "@cap/web-domain";
import { and, desc, eq, inArray, isNull, type SQL, sql } from "drizzle-orm";
import { Effect } from "effect";
-import { cookies } from "next/headers";
import { cache } from "react";
+import { getVerifiedPasswordHashes } from "@/lib/password-cookie";
import {
PUBLIC_COLLECTION_PAGE_SIZE,
type PublicCollectionAccess,
@@ -109,7 +108,7 @@ export type PublicCollectionPageData = {
function videoPasswordPredicate(
videoId: SQL,
videoPassword: SQL,
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
const noPassword = sql`(${videoPassword} IS NULL AND NOT EXISTS (
SELECT 1 FROM space_videos sv_password
@@ -118,15 +117,20 @@ function videoPasswordPredicate(
AND s_password.password IS NOT NULL
))`;
- if (!verifiedPasswordHash) return noPassword;
+ if (verifiedPasswordHashes.length === 0) return noPassword;
+
+ const verifiedHashes = sql.join(
+ verifiedPasswordHashes.map((hash) => sql`${hash}`),
+ sql`, `,
+ );
return sql`(${noPassword}
- OR ${videoPassword} = ${verifiedPasswordHash}
+ OR ${videoPassword} IN (${verifiedHashes})
OR EXISTS (
SELECT 1 FROM space_videos sv_password
INNER JOIN spaces s_password ON sv_password.spaceId = s_password.id
WHERE sv_password.videoId = ${videoId}
- AND s_password.password = ${verifiedPasswordHash}
+ AND s_password.password IN (${verifiedHashes})
)
)`;
}
@@ -140,20 +144,6 @@ function hasPasswordExpression(videoId: SQL, videoPassword: SQL) {
)`;
}
-async function getVerifiedPasswordHash() {
- const cookieValue = (await cookies()).get("x-cap-password")?.value;
- if (!cookieValue) return null;
-
- try {
- // decrypt is async — without the await its rejection (corrupt or stale
- // cookie, rotated encryption key) would escape this catch and crash the
- // page instead of falling back to the password prompt.
- return await decrypt(cookieValue);
- } catch {
- return null;
- }
-}
-
export async function getPublicCollectionMetadata(collectionId: string) {
return resolvePublicCollection(collectionId);
}
@@ -162,10 +152,10 @@ export async function getPublicCollectionPageData(
collectionId: string,
page: number,
): Promise<PublicCollectionPageData | null> {
- const [collection, user, verifiedPasswordHash] = await Promise.all([
+ const [collection, user, verifiedPasswordHashes] = await Promise.all([
resolvePublicCollection(collectionId),
getCurrentUser(),
- getVerifiedPasswordHash(),
+ getVerifiedPasswordHashes(),
]);
if (!collection) return null;
@@ -174,7 +164,7 @@ export async function getPublicCollectionPageData(
allowedEmailDomain: collection.allowedEmailDomain,
viewerEmail: user?.email,
passwordHash: collection.passwordHash,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
});
if (access.state !== "allowed") {
@@ -191,8 +181,8 @@ export async function getPublicCollectionPageData(
}
const [childFolders, videoPage] = await Promise.all([
- getPublicChildFolders(collection, verifiedPasswordHash),
- getPublicCollectionVideos(collection, page, verifiedPasswordHash),
+ getPublicChildFolders(collection, verifiedPasswordHashes),
+ getPublicCollectionVideos(collection, page, verifiedPasswordHashes),
]);
return {
@@ -274,126 +264,107 @@ function resolveEffectivePublicPage(
const resolvePublicCollection = cache(
async (collectionId: string): Promise<PublicCollection | null> => {
- // Fetched by primary key, then gated in `resolvePublicCollectionCandidate`
+ // Fetched by primary key — both lookups in parallel since the id's kind
+ // isn't known up front — then gated in `resolvePublicCollectionCandidate`
// so the public/tombstone policy lives in one tested place.
- const [folderRow] = await db()
- .select({
- id: folders.id,
- name: folders.name,
- color: folders.color,
- public: folders.public,
- settings: folders.settings,
- spaceId: folders.spaceId,
- organizationId: folders.organizationId,
- organizationName: organizations.name,
- organizationTombstoneAt: organizations.tombstoneAt,
- allowedEmailDomain: organizations.allowedEmailDomain,
- organizationIconUrl: organizations.iconUrl,
- ownerStripeSubscriptionStatus: users.stripeSubscriptionStatus,
- ownerThirdPartyStripeSubscriptionId:
- users.thirdPartyStripeSubscriptionId,
- passwordHash: spaces.password,
- })
- .from(folders)
- .innerJoin(organizations, eq(folders.organizationId, organizations.id))
- .innerJoin(users, eq(organizations.ownerId, users.id))
- .leftJoin(spaces, eq(folders.spaceId, spaces.id))
- .where(eq(folders.id, collectionId as Folder.FolderId))
- .limit(1);
-
- const folder = resolvePublicCollectionCandidate(
+ const [[folderRow], [spaceRow]] = await Promise.all([
+ db()
+ .select({
+ id: folders.id,
+ name: folders.name,
+ color: folders.color,
+ public: folders.public,
+ settings: folders.settings,
+ spaceId: folders.spaceId,
+ organizationId: folders.organizationId,
+ organizationName: organizations.name,
+ organizationTombstoneAt: organizations.tombstoneAt,
+ allowedEmailDomain: organizations.allowedEmailDomain,
+ organizationIconUrl: organizations.iconUrl,
+ ownerStripeSubscriptionStatus: users.stripeSubscriptionStatus,
+ ownerThirdPartyStripeSubscriptionId:
+ users.thirdPartyStripeSubscriptionId,
+ passwordHash: spaces.password,
+ })
+ .from(folders)
+ .innerJoin(organizations, eq(folders.organizationId, organizations.id))
+ .innerJoin(users, eq(organizations.ownerId, users.id))
+ .leftJoin(spaces, eq(folders.spaceId, spaces.id))
+ .where(eq(folders.id, collectionId as Folder.FolderId))
+ .limit(1),
+ db()
+ .select({
+ id: spaces.id,
+ name: spaces.name,
+ description: spaces.description,
+ public: spaces.public,
+ settings: spaces.settings,
+ organizationId: spaces.organizationId,
+ organizationName: organizations.name,
+ organizationTombstoneAt: organizations.tombstoneAt,
+ allowedEmailDomain: organizations.allowedEmailDomain,
+ organizationIconUrl: organizations.iconUrl,
+ ownerStripeSubscriptionStatus: users.stripeSubscriptionStatus,
+ ownerThirdPartyStripeSubscriptionId:
+ users.thirdPartyStripeSubscriptionId,
+ passwordHash: spaces.password,
+ })
+ .from(spaces)
+ .innerJoin(organizations, eq(spaces.organizationId, organizations.id))
+ .innerJoin(users, eq(organizations.ownerId, users.id))
+ .where(eq(spaces.id, collectionId as Space.SpaceIdOrOrganisationId))
+ .limit(1),
+ ]);
+
+ const candidate = resolvePublicCollectionCandidate(
folderRow ? { kind: "folder" as const, ...folderRow } : null,
- null,
- );
-
- if (folder) {
- const publicPage = resolveEffectivePublicPage(
- userIsPro({
- stripeSubscriptionStatus: folder.ownerStripeSubscriptionStatus,
- thirdPartyStripeSubscriptionId:
- folder.ownerThirdPartyStripeSubscriptionId,
- }),
- folder.settings?.publicPage,
- );
- const icons = await resolveIconUrls({
- ...publicPageIconKeys(publicPage, {
- organizationIconUrl: folder.organizationIconUrl,
- }),
- });
-
- return {
- id: folder.id,
- kind: "folder",
- name: folder.name,
- color: folder.color,
- description: null,
- spaceId: folder.spaceId,
- organizationId: folder.organizationId,
- organizationName: folder.organizationName,
- allowedEmailDomain: folder.allowedEmailDomain,
- passwordHash: folder.passwordHash,
- publicPage,
- ...icons,
- };
- }
-
- const [spaceRow] = await db()
- .select({
- id: spaces.id,
- name: spaces.name,
- description: spaces.description,
- public: spaces.public,
- settings: spaces.settings,
- organizationId: spaces.organizationId,
- organizationName: organizations.name,
- organizationTombstoneAt: organizations.tombstoneAt,
- allowedEmailDomain: organizations.allowedEmailDomain,
- organizationIconUrl: organizations.iconUrl,
- ownerStripeSubscriptionStatus: users.stripeSubscriptionStatus,
- ownerThirdPartyStripeSubscriptionId:
- users.thirdPartyStripeSubscriptionId,
- passwordHash: spaces.password,
- })
- .from(spaces)
- .innerJoin(organizations, eq(spaces.organizationId, organizations.id))
- .innerJoin(users, eq(organizations.ownerId, users.id))
- .where(eq(spaces.id, collectionId as Space.SpaceIdOrOrganisationId))
- .limit(1);
-
- const space = resolvePublicCollectionCandidate(
- null,
spaceRow ? { kind: "space" as const, ...spaceRow } : null,
);
- if (!space) return null;
+ if (!candidate) return null;
const publicPage = resolveEffectivePublicPage(
userIsPro({
- stripeSubscriptionStatus: space.ownerStripeSubscriptionStatus,
+ stripeSubscriptionStatus: candidate.ownerStripeSubscriptionStatus,
thirdPartyStripeSubscriptionId:
- space.ownerThirdPartyStripeSubscriptionId,
+ candidate.ownerThirdPartyStripeSubscriptionId,
}),
- space.settings?.publicPage,
+ candidate.settings?.publicPage,
);
- const icons = await resolveIconUrls({
- ...publicPageIconKeys(publicPage, {
- organizationIconUrl: space.organizationIconUrl,
+ const icons = await resolveIconUrls(
+ publicPageIconKeys(publicPage, {
+ organizationIconUrl: candidate.organizationIconUrl,
}),
- });
+ );
+
+ const shared = {
+ name: candidate.name,
+ organizationId: candidate.organizationId,
+ organizationName: candidate.organizationName,
+ allowedEmailDomain: candidate.allowedEmailDomain,
+ passwordHash: candidate.passwordHash,
+ publicPage,
+ ...icons,
+ };
+
+ if (candidate.kind === "folder") {
+ return {
+ ...shared,
+ id: candidate.id,
+ kind: "folder",
+ color: candidate.color,
+ description: null,
+ spaceId: candidate.spaceId,
+ };
+ }
return {
- id: space.id,
+ ...shared,
+ id: candidate.id,
kind: "space",
- name: space.name,
color: null,
- description: space.description,
- spaceId: space.id,
- organizationId: space.organizationId,
- organizationName: space.organizationName,
- allowedEmailDomain: space.allowedEmailDomain,
- passwordHash: space.passwordHash,
- publicPage,
- ...icons,
+ description: candidate.description,
+ spaceId: candidate.id,
};
},
);
@@ -425,21 +396,21 @@ function isOrgLevelFolder(collection: PublicCollection) {
async function getPublicCollectionVideos(
collection: PublicCollection,
page: number,
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
if (collection.kind === "space") {
- return getPublicSpaceVideos(collection, page, verifiedPasswordHash);
+ return getPublicSpaceVideos(collection, page, verifiedPasswordHashes);
}
if (isOrgLevelFolder(collection)) {
- return getPublicOrgFolderVideos(collection, page, verifiedPasswordHash);
+ return getPublicOrgFolderVideos(collection, page, verifiedPasswordHashes);
}
if (collection.spaceId) {
- return getPublicSpaceFolderVideos(collection, page, verifiedPasswordHash);
+ return getPublicSpaceFolderVideos(collection, page, verifiedPasswordHashes);
}
- return getPublicUserFolderVideos(collection, page, verifiedPasswordHash);
+ return getPublicUserFolderVideos(collection, page, verifiedPasswordHashes);
}
const videoSelect = {
@@ -498,7 +469,7 @@ function toPublicCollectionVideos(
async function getPublicSpaceVideos(
collection: PublicCollection,
page: number,
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
const offset = (page - 1) * PUBLIC_COLLECTION_PAGE_SIZE;
const where = and(
@@ -508,7 +479,7 @@ async function getPublicSpaceVideos(
videoPasswordPredicate(
sql`${videos.id}`,
sql`${videos.password}`,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
),
);
@@ -543,7 +514,7 @@ async function getPublicSpaceVideos(
async function getPublicSpaceFolderVideos(
collection: PublicCollection,
page: number,
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
const offset = (page - 1) * PUBLIC_COLLECTION_PAGE_SIZE;
const where = and(
@@ -553,7 +524,7 @@ async function getPublicSpaceFolderVideos(
videoPasswordPredicate(
sql`${videos.id}`,
sql`${videos.password}`,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
),
);
@@ -588,7 +559,7 @@ async function getPublicSpaceFolderVideos(
async function getPublicOrgFolderVideos(
collection: PublicCollection,
page: number,
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
const offset = (page - 1) * PUBLIC_COLLECTION_PAGE_SIZE;
const where = and(
@@ -598,7 +569,7 @@ async function getPublicOrgFolderVideos(
videoPasswordPredicate(
sql`${videos.id}`,
sql`${videos.password}`,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
),
);
@@ -633,7 +604,7 @@ async function getPublicOrgFolderVideos(
async function getPublicUserFolderVideos(
collection: PublicCollection,
page: number,
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
const offset = (page - 1) * PUBLIC_COLLECTION_PAGE_SIZE;
const where = and(
@@ -643,7 +614,7 @@ async function getPublicUserFolderVideos(
videoPasswordPredicate(
sql`${videos.id}`,
sql`${videos.password}`,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
),
);
@@ -675,7 +646,7 @@ async function getPublicUserFolderVideos(
async function getPublicChildFolders(
collection: PublicCollection,
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
): Promise<PublicCollectionFolder[]> {
const where =
collection.kind === "space"
@@ -707,10 +678,10 @@ async function getPublicChildFolders(
const folderIds = childFolders.map((folder) => folder.id);
const counts = isOrgLevelFolder(collection)
- ? await getPublicOrgFolderVideoCounts(folderIds, verifiedPasswordHash)
+ ? await getPublicOrgFolderVideoCounts(folderIds, verifiedPasswordHashes)
: collection.kind === "space" || Boolean(collection.spaceId)
- ? await getPublicSpaceFolderVideoCounts(folderIds, verifiedPasswordHash)
- : await getPublicUserFolderVideoCounts(folderIds, verifiedPasswordHash);
+ ? await getPublicSpaceFolderVideoCounts(folderIds, verifiedPasswordHashes)
+ : await getPublicUserFolderVideoCounts(folderIds, verifiedPasswordHashes);
const countByFolderId = new Map(
counts.map((row) => [row.folderId, row.videoCount]),
);
@@ -723,7 +694,7 @@ async function getPublicChildFolders(
async function getPublicSpaceFolderVideoCounts(
folderIds: Folder.FolderId[],
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
return db()
.select({
@@ -741,7 +712,7 @@ async function getPublicSpaceFolderVideoCounts(
videoPasswordPredicate(
sql`${videos.id}`,
sql`${videos.password}`,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
),
),
)
@@ -750,7 +721,7 @@ async function getPublicSpaceFolderVideoCounts(
async function getPublicOrgFolderVideoCounts(
folderIds: Folder.FolderId[],
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
return db()
.select({
@@ -768,7 +739,7 @@ async function getPublicOrgFolderVideoCounts(
videoPasswordPredicate(
sql`${videos.id}`,
sql`${videos.password}`,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
),
),
)
@@ -777,7 +748,7 @@ async function getPublicOrgFolderVideoCounts(
async function getPublicUserFolderVideoCounts(
folderIds: Folder.FolderId[],
- verifiedPasswordHash: string | null,
+ verifiedPasswordHashes: readonly string[],
) {
return db()
.select({
@@ -794,7 +765,7 @@ async function getPublicUserFolderVideoCounts(
videoPasswordPredicate(
sql`${videos.id}`,
sql`${videos.password}`,
- verifiedPasswordHash,
+ verifiedPasswordHashes,
),
),
)
diff --git a/apps/web/lib/server.ts b/apps/web/lib/server.ts
index dce31de2e..0e20a0db3 100644
--- a/apps/web/lib/server.ts
+++ b/apps/web/lib/server.ts
@@ -1,6 +1,5 @@
import "server-only";
-import { decrypt } from "@cap/database/crypto";
import { serverEnv } from "@cap/env";
import {
AwsCredentials,
@@ -41,27 +40,15 @@ import {
Option,
Redacted,
} from "effect";
-import { cookies } from "next/headers";
import { allowedOrigins } from "@/utils/cors";
+import { getVerifiedPasswordHashes } from "./password-cookie";
import { layerTracer } from "./tracing";
const CookiePasswordAttachmentLive = Layer.effect(
Video.VideoPasswordAttachment,
Effect.gen(function* () {
- const password = Option.fromNullable(
- yield* Effect.promise(async () => {
- const pw = (await cookies()).get("x-cap-password")?.value;
- if (!pw) return undefined;
- try {
- return await decrypt(pw);
- } catch {
- // Corrupt or stale cookie (e.g. rotated encryption key) — treat
- // as absent rather than crashing the page with a defect.
- return undefined;
- }
- }),
- );
- return { password };
+ const passwords = yield* Effect.promise(getVerifiedPasswordHashes);
+ return { passwords };
}),
);
diff --git a/packages/web-domain/src/Video.ts b/packages/web-domain/src/Video.ts
index 711df3573..b04748c82 100644
--- a/packages/web-domain/src/Video.ts
+++ b/packages/web-domain/src/Video.ts
@@ -200,13 +200,15 @@ export function normalizeSegmentEntry(
}
/*
- * Used to specify a video password provided by a user,
+ * Used to specify video passwords provided by a user,
* whether via cookies in the case of the website,
- * or via query params for the API.
+ * or via query params for the API. Holds every hash the user has verified
+ * (the cookie remembers one per unlocked resource), so unlocking one share
+ * never invalidates another.
*/
export class VideoPasswordAttachment extends Context.Tag(
"VideoPasswordAttachment",
-)<VideoPasswordAttachment, { password: Option.Option<string> }>() {}
+)<VideoPasswordAttachment, { passwords: ReadonlyArray<string> }>() {}
export class VerifyVideoPasswordError extends Schema.TaggedError<VerifyVideoPasswordError>()(
"VerifyVideoPasswordError",
@@ -236,16 +238,17 @@ export const verifyPasswordCandidates = (
if (passwords.length === 0) return;
- if (
- Option.isNone(passwordAttachment) ||
- Option.isNone(passwordAttachment.value.password)
- )
+ const verified = Option.isSome(passwordAttachment)
+ ? passwordAttachment.value.passwords
+ : [];
+
+ if (verified.length === 0)
return yield* new VerifyVideoPasswordError({
id: video.id,
cause: "not-provided",
});
- if (!passwords.includes(passwordAttachment.value.password.value))
+ if (!verified.some((hash) => passwords.includes(hash)))
return yield* new VerifyVideoPasswordError({
id: video.id,
cause: "wrong-password",