Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/features/api/payment-processing/package-pricing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
} from "#shared/booking/signed-metadata.ts";
import { childIdsMatching } from "#shared/child-parents.ts";
import {
getPackageGroupById,
getPackageDisplaysByIds,
loadPackageMemberPricing,
} from "#shared/db/groups.ts";
import {
Expand Down Expand Up @@ -86,8 +86,10 @@ export const loadPackagePricingByGroup = async (
intent: BookingIntent,
): Promise<Map<number, PackagePricing>> => {
const pricingByGroup = new Map<number, PackagePricing>();
for (const groupId of lineGroupIds(intent.items)) {
if ((await getPackageGroupById(groupId)) === null) continue;
const groupIds = [...lineGroupIds(intent.items)];
const packageDisplays = await getPackageDisplaysByIds(groupIds);
for (const groupId of groupIds) {
if (!packageDisplays.has(groupId)) continue;
const pricing = await loadPackageMemberPricing(groupId);
pricingByGroup.set(groupId, {
dayPriceMap: pricing.dayPrices,
Expand Down
5 changes: 2 additions & 3 deletions src/features/public/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@ import {
redirect,
} from "#routes/response.ts";
import { BOTPOISON_FIELD, verifyBotpoisonSolution } from "#shared/botpoison.ts";
import { isBotpoisonEnabled } from "#shared/config.ts";
import { getBotpoisonPublicKey, isBotpoisonEnabled } from "#shared/config.ts";
import {
contactFormPublicKey,
isContactFormActive,
sendContactMessage,
} from "#shared/contact-form.ts";
Expand Down Expand Up @@ -262,7 +261,7 @@ const renderContactPage = async (request: Request): Promise<Response> => {
const flash = applyFlash(request);
return htmlResponse(
contactPage({
botpoisonPublicKey: contactFormPublicKey(),
botpoisonPublicKey: getBotpoisonPublicKey(),
content: settings.contactPageText || null,
...(flash.error !== undefined ? { error: flash.error } : {}),
formActive,
Expand Down
3 changes: 1 addition & 2 deletions src/shared/boot-checks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,5 @@ export const BOOT_CHECKS: readonly BootCheck[] = [
];

export const validateBootChecks = (): void => {
validateEncryptionKey();
validateOptionalMainInstanceKey();
for (const check of BOOT_CHECKS) check.run();
};
6 changes: 1 addition & 5 deletions src/shared/contact-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* submitter, with anti-spoof handling) lives here.
*/

import { getBotpoisonPublicKey, getEffectiveDomain } from "#shared/config.ts";
import { getEffectiveDomain } from "#shared/config.ts";
import { settings } from "#shared/db/settings.ts";
import {
deliverMessage,
Expand All @@ -34,10 +34,6 @@ import {
export const isContactFormActive = (): boolean =>
settings.contactFormEnabled && settings.businessEmail !== "";

/** Public Botpoison key to embed in the form for the browser widget. Empty when
* Botpoison is not configured, in which case no widget is shown. */
export const contactFormPublicKey = (): string => getBotpoisonPublicKey();

/** Warning prepended when the submitter claimed an address on the owner's own
* business email host. */
const SPOOF_BUSINESS_WARNING =
Expand Down
10 changes: 3 additions & 7 deletions src/shared/cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,21 @@ import { isSecureMode } from "#shared/config.ts";
import type { Flash } from "#shared/flash-context.ts";
import { SESSION_MAX_AGE_S } from "#shared/limits.ts";

export { isSecureMode };

const secureAttribute = (): string => (isSecureMode() ? "; Secure" : "");

const sessionCookieName = (): string =>
export const getSessionCookieName = (): string =>
isSecureMode() ? "__Host-session" : "session";

export const getSessionCookieName = (): string => sessionCookieName();

export const buildSessionCookie = (
token: string,
options?: { maxAge?: number },
): string => {
const maxAge = options?.maxAge ?? SESSION_MAX_AGE_S;
return `${sessionCookieName()}=${token}; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=${maxAge}`;
return `${getSessionCookieName()}=${token}; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=${maxAge}`;
};

export const clearSessionCookie = (): string =>
`${sessionCookieName()}=; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=0`;
`${getSessionCookieName()}=; HttpOnly${secureAttribute()}; SameSite=Strict; Path=/; Max-Age=0`;

/** Cookie name prefix for flash messages (keyed by per-request ID) */
const FLASH_COOKIE_PREFIX = "flash_";
Expand Down
8 changes: 3 additions & 5 deletions src/shared/db/attributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
inPlaceholders,
nextSortOrder,
queryAll,
queryIdColumn,
queryOne,
} from "#shared/db/client.ts";
import {
Expand Down Expand Up @@ -198,9 +199,6 @@ const buildAttributeGroups = (
)(rows).values(),
];

const queryIds = async (sql: string): Promise<number[]> =>
map((row: { id: number }) => row.id)(await queryAll<{ id: number }>(sql));

const groupAttributeRows = async (
rows: JoinedAttributeRow[],
): Promise<AttributeWithOptions[]> =>
Expand Down Expand Up @@ -245,10 +243,10 @@ export const getAttributeId = async (id: number): Promise<number | null> =>
)?.id ?? null;

export const getAttributeIdsOrdered = async (): Promise<number[]> =>
queryIds("SELECT id FROM attributes ORDER BY sort_order, id");
queryIdColumn("SELECT id FROM attributes ORDER BY sort_order, id");

export const getAllAttributeOptionIds = async (): Promise<Set<number>> =>
new Set(await queryIds("SELECT id FROM attribute_options"));
new Set(await queryIdColumn("SELECT id FROM attribute_options"));

type OptionListingRow = StoredTableProjectionRow<
Listing,
Expand Down
107 changes: 42 additions & 65 deletions src/shared/db/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,18 @@ const rawGroupsTable = defineIdTable<Group, GroupInput>("groups", {
const queryGroups = queryAndMap<Group, Group>((row) =>
rawGroupsTable.fromDb(row),
);
const GROUP_COLUMNS = rawGroupsTable.columns.join(", ");
const GROUP_COLUMNS = rawGroupsTable.columns
.map((column) => `groupRecord.${column}`)
.join(", ");

export const groups = cachedEntityTable<Group, GroupInput>(
"groups",
rawGroupsTable,
{
fetchAll: () =>
queryGroups(`SELECT ${GROUP_COLUMNS} FROM groups ORDER BY id ASC`),
queryGroups(
`SELECT ${GROUP_COLUMNS} FROM groups AS groupRecord ORDER BY groupRecord.id ASC`,
),
idOf: (g) => g.id,
keyOf: (g) => g.slug_index,
ttlMs: GROUPS_CACHE_TTL_MS,
Expand Down Expand Up @@ -191,35 +195,6 @@ export const isGroupSlugTaken = (
excludeGroupId ? { id: excludeGroupId, table: "groups" } : undefined,
);

/** WHERE fragment matching listings that are members of the given group, via the
* group_listings join table (subquery form avoids duplicate rows). */
const IN_GROUP_SQL =
"listing.id IN (SELECT listing_id FROM group_listings WHERE group_id = ?)";

/** Query listings in a group with attendee counts, optionally filtering to active only */
const queryGroupListings = (
groupId: number,
activeOnly: boolean,
): Promise<ListingWithCount[]> =>
queryListingsWithCounts(
activeOnly
? `WHERE listing.active = 1 AND ${IN_GROUP_SQL}`
: `WHERE ${IN_GROUP_SQL}`,
[groupId],
);

/** One group's members with attendee counts; `activeOnly` gates the public
* liveness view (active members only) from the full list (active + inactive). */
const listingsInGroup =
(activeOnly: boolean) =>
(groupId: number): Promise<ListingWithCount[]> =>
queryGroupListings(groupId, activeOnly);

/**
* Get active listings in a group with attendee counts.
*/
export const getActiveListingsByGroupId = listingsInGroup(true);

/**
* Members of SEVERAL groups at once, keyed by group id — the batched form of the
* single-group loaders for a multi-group surface. A page with many group leaves
Expand Down Expand Up @@ -269,6 +244,21 @@ export const getListingsByGroupIds = async (
);
};

/** One group's entry from the shared one-or-many membership query. */
type LoadGroupListings = (groupId: number) => Promise<ListingWithCount[]>;

const listingsInGroup =
(activeOnly: boolean) =>
async (groupId: number): Promise<ListingWithCount[]> =>
requiredMapValue(
await getListingsByGroupIds([groupId], activeOnly),
groupId,
"Missing group listing membership",
);

export const getActiveListingsByGroupId: LoadGroupListings =
listingsInGroup(true);

/** Does a group row exist? The add-item revalidation's single-row check — no
* name decryption, never the whole table. */
export const groupExists = (id: number): Promise<boolean> =>
Expand All @@ -277,7 +267,7 @@ export const groupExists = (id: number): Promise<boolean> =>
/**
* Get all listings in a group with attendee counts (including inactive).
*/
export const getListingsByGroupId = listingsInGroup(false);
export const getListingsByGroupId: LoadGroupListings = listingsInGroup(false);

/**
* Validate that a listing is compatible with a group's existing listings.
Expand Down Expand Up @@ -480,32 +470,6 @@ export const packageMembersError = async (
* name on tickets/emails. */
export type PackageDisplay = { name: string; hideListings: boolean };

/** The package display for a booking's PERSISTED `package_group_id`, or null when
* the id is 0 (not a package) or names a group that no longer exists or is not a
* package. Grouping on the stored id — set on every booking row of one package
* checkout — is exact: a standalone order of the same listings carries id 0, so
* it is never mistaken for the package. The group's name is decrypted on the way
* out. */
/** Load a group by id only when it is a live package, else null. The one home
* for "this id names a package group" — a non-positive id, a missing group, or a
* non-package group all read as null. */
export const getPackageGroupById = async (
groupId: number,
): Promise<Group | null> => {
if (groupId <= 0) return null;
const group = await groups.table.findById(groupId);
return group?.is_package ? group : null;
};

export const getPackageDisplayById = async (
groupId: number,
): Promise<PackageDisplay | null> => {
const group = await getPackageGroupById(groupId);
return group === null
? null
: { hideListings: group.hide_package_listings, name: group.name };
};

/** Whether any booking row is stamped with this package's group id — sold
* tickets whose display (and hidden-member concealment) resolves through the
* live package row. Refund placeholders (quantity 0) don't count. */
Expand All @@ -521,16 +485,29 @@ export const hasPackageBookings = (groupId: number): Promise<boolean> =>
* the ticket view collapse each token's package rows into one card per package,
* so an attendee holding both a package booking and a standalone one (e.g. after
* an attendee merge) doesn't fall back to per-row cards that leak a hidden member.
* Groups are cached, so the per-id resolution is cheap. */
* Groups are resolved together from their shared cache. */
export const getPackageDisplaysByIds = async (
groupIds: readonly number[],
): Promise<Map<number, PackageDisplay>> => {
const result = new Map<number, PackageDisplay>();
for (const id of new Set(groupIds)) {
const display = await getPackageDisplayById(id);
if (display) result.set(id, display);
}
return result;
const packageGroups = await mapParallel((row: Group) =>
rawGroupsTable.fromDb(row),
)(
await rowsByIds<Group>(
[...new Set(groupIds)],
Comment thread
stefan-burke marked this conversation as resolved.
Resolved
(placeholders) =>
`SELECT ${GROUP_COLUMNS} FROM groups AS groupRecord
WHERE groupRecord.id IN (${placeholders}) AND groupRecord.is_package = 1`,
),
);
return new Map(
packageGroups.map((group) => [
group.id,
{
hideListings: group.hide_package_listings,
name: group.name,
},
]),
);
};

/** The package displays behind a set of booked rows — each row's attendee names
Expand Down
4 changes: 1 addition & 3 deletions src/shared/db/link-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,7 @@ export const linkTableSide = (
),
setIds: (keyId, ids) => executeBatch(replaceStatements(keyId, ids)),
setIdsTx: async (tx, keyId, ids) => {
for (const stmt of replaceStatements(keyId, ids)) {
await tx.execute(stmt);
}
await tx.batch(replaceStatements(keyId, ids));
},
};
};
22 changes: 8 additions & 14 deletions src/shared/db/questions/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,21 +88,15 @@ export const prepareStringRows = async (
);
};

/** Run the interning statements and return the trailing SELECT's result. When a
* `tx` is given, each statement runs on the caller's open transaction via
* `tx.execute`; otherwise as one `executeBatchWithResults` write batch. Either
* way the SELECT shares the INSERT's transaction, preserving the
* read-your-writes invariant the id resolution depends on. */
/** Run the interning statements together and return the trailing SELECT. */
const runInternStatements = async (
statements: SqlStatement[],
tx?: TxScope,
): Promise<ResultSet> => {
if (!tx) return (await executeBatchWithResults(statements)).at(-1)!;
// Run each statement on the open transaction; the trailing SELECT sees the
// rows the INSERT OR IGNORE just wrote in that same transaction.
let result: ResultSet | undefined;
for (const stmt of statements) result = await tx.execute(stmt);
return result!;
const results = await (tx
? tx.batch(statements)
: executeBatchWithResults(statements));
return results.at(-1)!;
};

/**
Expand All @@ -111,8 +105,8 @@ const runInternStatements = async (
* just-written rows: a brand-new string's id read from a replica that hasn't
* replicated the insert comes back missing, so the id resolves to undefined and
* the value is silently lost. When `tx` is given each statement runs on the
* caller's open transaction via `tx.execute`, so the SELECT sees the INSERT's
* rows within that transaction; otherwise one `executeBatchWithResults` write
* caller's open transaction, so the SELECT sees the INSERT's rows within that
* transaction; otherwise one `executeBatchWithResults` write
* batch is a single primary-pinned transaction that holds the same invariant.
*
* The per-text `INSERT OR IGNORE` values are batched into one multi-row
Expand Down Expand Up @@ -160,7 +154,7 @@ export const internStringRows = async (
* Intern a list of free-text answers, returning the `text → id` map. Encrypts
* and HMAC-indexes each unique text, then inserts-or-ignores, refreshes
* `created`, and reads the ids back in one atomic batch. When `tx` is given,
* every statement runs on the caller's open transaction via `tx.execute` (so
* every statement runs together on the caller's open transaction (so
* the read-your-writes SELECT shares the INSERT's transaction); otherwise as
* one `executeBatchWithResults` write batch.
*
Expand Down
7 changes: 1 addition & 6 deletions src/shared/db/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export const onUsersInvalidated = (listener: () => void): void => {
usersInvalidationListeners.push(listener);
};

const loadAllUsers = (): Promise<User[]> => usersCache.getAll();
export const getAllUsers = (): Promise<User[]> => usersCache.getAll();

registerCache(() => ({ entries: usersCache.size(), name: "users" }));

Expand Down Expand Up @@ -267,11 +267,6 @@ export const isUsernameTaken = async (username: string): Promise<boolean> => {
return user !== null;
};

/**
* Get all users (for admin user management page, from cache)
*/
export const getAllUsers = (): Promise<User[]> => loadAllUsers();

/** Get the minimal encrypted user fields needed to show assignable users. */
export const getUserDisplayFields = (): Promise<UserDisplayFields[]> =>
queryAll<UserDisplayFields>(USER_DISPLAY_SELECT);
Expand Down
13 changes: 6 additions & 7 deletions src/shared/package-privacy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {
getPackageDisplayById,
getPackageDisplaysByIds,
type PackageDisplay,
} from "#shared/db/groups.ts";

Expand Down Expand Up @@ -79,12 +79,11 @@ export const concealMemberNames = <T extends { name: string }>(
export const resolveNamesConcealed = async (
packageGroupIds: Iterable<number>,
): Promise<boolean> => {
for (const groupId of new Set(packageGroupIds)) {
if ((await getPackageDisplayById(groupId))?.hideListings ?? true) {
return true;
}
}
return false;
const groupIds = [...new Set(packageGroupIds)];
const displays = await getPackageDisplaysByIds(groupIds);
return groupIds.some(
(groupId) => displays.get(groupId)?.hideListings ?? true,
);
};

/** The stand-in names concealing a page's hidden bundles, for pages selling
Expand Down
Loading