Repository navigation
feat(reviews): shareable review links + anon review submission (SC-38) - #280
Conversation
The "Reviews & Credentials" trust layer described in https://linear.app/scaffald/issue/SC-38. A worker generates a unique link and shares it with a former employer, instructor, foreman, CTE director, co-op supervisor, project lead, client, etc. The recipient opens the link in any browser and submits a review WITHOUT creating a Scaffald account. Reviews flow into the same core.reviews table existing UI already reads from, so they show up on the public profile immediately. What's new Migration: `326_review_links_and_anon_reviews.sql` - New `core.review_links` table: id, subject_user_id, token, label, expires_at, max_uses, used_count, is_revoked, timestamps. - RLS: workers manage their own rows; anon SELECT is granted so the public submit Edge Function can look up by token. The token itself (32 hex chars of v4 UUID entropy) is the secret. - `core.reviews.author_user_id` is now nullable. The existing UNIQUE (kind, subject_type, subject_id, author_user_id) constraint is replaced by a partial unique index that only applies when author_user_id IS NOT NULL — anon dedup is handled at the API layer. - Anon writes to core.reviews are NOT allowed via RLS — the Edge Function uses the service role after validating the token. This forces all anon submissions through the API where future rate limiting / anti-bot can live. API: `packages/supabase/functions/api/routes/review-links.ts` - POST /v1/reviews/links (auth) create - GET /v1/reviews/links (auth) list mine - DELETE /v1/reviews/links/:id (auth) revoke - GET /v1/reviews/links/by-token/:token (anon) validate + return subject info (name, headline, slug, avatar_path) - POST /v1/reviews/links/by-token/:token/submit (anon) submit a review. Validates token (not revoked, not expired, under max_uses), optionally dedupes by reviewer email, inserts the review with author_user_id = NULL + metadata.via_review_link = link_id, then increments used_count. Best-effort — increment errors don't block the review. SDK (submodule): `packages/sdk` bumped to include the new ReviewLinks resource. See Scaffald/sdk#3. scf-core hooks: `utils/review-links-sdk-hooks.ts` - useMyReviewLinks (worker) - useCreateReviewLinkMutation, useRevokeReviewLinkMutation (worker) - useReviewLinkByToken (anon, used by the public form) - useSubmitReviewByTokenMutation (anon) Worker UI: `features/profile/components/RequestReviewModal.tsx` - New "Request review" button on /profile next to "Share profile". - Optional label input ("Foreman at Acme") for tracking which link was given to whom. - "Generate" → mutation → modal shows QR + URL + Copy + Share. - Below: list of other active links with per-row Copy + Revoke. - Web Share API on web with clipboard fallback; native Share.share on iOS/Android. Public form: `apps/scaffald/app/(public)/reviews/[token].tsx` - Validates token via the SDK hook on mount. Invalid/expired/revoked → friendly error screen with a CTA back to scaffald.com. - Renders the worker's display name + headline at the top so the reviewer knows who they're vouching for. - Form: reviewer name (required), email (optional), relationship (instructor / manager / coworker / client / foreman / supervisor / other), 1-5 star rating, optional headline, body (max 2000 chars). - Submit → service-role insert into core.reviews via the Edge Function → success screen with a deep-link to the public profile. Deployment note This PR ships a migration. To apply locally: cd packages/supabase && pnpm supa db reset The migration is additive (relaxes constraints, adds new table) and reversible. Existing review data is unaffected. Out of scope (v1.4.0) - Anti-bot / CAPTCHA on the public form (see SC-32 — Cloudflare Turnstile). - Per-IP rate limiting on submitByToken. - Email notification to the worker when a review arrives. - "Reviews I've requested" dashboard with per-link stats. Co-Authored-By: Claude Opus 4.7 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5f012fa162
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| await service | ||
| .schema("core") | ||
| .from("review_links") | ||
| .update({ | ||
| used_count: link.used_count + 1, |
There was a problem hiding this comment.
Enforce max_uses atomically before inserting reviews
This endpoint checks used_count before insert, then later writes used_count: link.used_count + 1, so concurrent submissions for the same token can both pass validation and both insert reviews (e.g., max_uses = 1), while the counter is also vulnerable to lost updates. This breaks the advertised per-link usage cap under load; the check/increment needs to be done atomically (single SQL statement/transaction with row lock or conditional update) before accepting the review.
Useful? React with 👍 / 👎.
| CREATE POLICY review_links_anon_select ON core.review_links | ||
| FOR SELECT TO anon | ||
| USING (TRUE); |
There was a problem hiding this comment.
Restrict anonymous SELECT policy on review_links
USING (TRUE) grants the anon role unrestricted row visibility for core.review_links, which includes live review tokens. In environments where anon has table SELECT privileges (a common Supabase default for exposed schemas), this allows token enumeration and spoofed anonymous review submissions; the policy comment assumes exact-token filtering, but that filter is not enforced by RLS. The anon policy should be token-scoped (or removed, since this route already uses the service-role client for lookup).
Useful? React with 👍 / 👎.
| // Active links = non-revoked, non-expired | ||
| const activeLinks = (links ?? []).filter((l) => !l.is_revoked) | ||
| const latestLink = activeLinks[0] ?? null |
There was a problem hiding this comment.
Exclude unusable links from the modal's active list
The modal labels activeLinks as non-revoked/non-expired, but the filter only checks !is_revoked, so expired or maxed-out links are still surfaced as the “most recent link” with QR/copy/share actions. Since the submit API rejects expired/limit-reached tokens, users can end up repeatedly sharing links that always fail for reviewers.
Useful? React with 👍 / 👎.
Three Codex findings from PR #280, all reasonable: P1 — Atomic max_uses enforcement (review-links.ts submit endpoint) The previous flow validated `used_count < max_uses` then later wrote `used_count + 1` from the read value. Two concurrent submits on the same token could both pass validation and both insert reviews, breaking the advertised cap and clobbering the counter via lost update. Now uses a compare-and-swap UPDATE that claims the slot atomically before the review insert. PostgREST's chained `.eq()` filters compose into a `WHERE used_count = ? AND is_revoked = false` predicate; if a concurrent caller has incremented in the meantime, the update affects 0 rows and we return 409. The earlier read-and-validate block still runs because it produces friendlier error messages for known-invalid states (revoked, expired, max-reached at read time) — but it's no longer load-bearing for correctness. If the review insert fails after the claim, we issue a CAS refund (used_count = used_count - 1, gated by `eq("used_count", claimed)`) so a failed write doesn't burn a slot. Best-effort: if the refund also fails, the worst case is one wasted slot. P1 — Remove anon SELECT policy on core.review_links (migration 326) The previous policy granted anon `USING (TRUE)`, which would let any unauthenticated client enumerate review tokens via the Supabase REST API. The Edge Function already uses the service role for token lookup (which bypasses RLS), so the policy was dead code on top of being a vector for token enumeration. Dropped entirely. P2 — Filter unusable links from the Request Review modal The modal's `activeLinks` was `!is_revoked`, but the submit API also rejects expired and maxed-out tokens. Surfacing them in the "most recent link" QR/Copy/Share UI just produced silent failures for recipients. Filter now also excludes expired (`expires_at` in the past) and maxed (`used_count >= max_uses`) rows. Also bumps the @scaffald/sdk submodule from the feature-branch commit (now deleted) to the squash-merge of #3 on main (`0518e70 feat(reviews): ReviewLinks resource for shareable review tokens (SC-38)`). Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Addressed all three Codex review comments in P1 — Atomic P1 — Anon SELECT on P2 — Modal's Also bumped the Smoke tests after the changes:
|
Summary
SC-38 Reviews — shareable review link, no account required for reviewer — the trust layer that lets workers solicit credibility signals from people who don't (and shouldn't have to) sign up for Scaffald. A worker generates a unique link via /profile → "Request review", shares it via text/email/QR, and the recipient submits a review in any browser without an account.
Blocked by: Scaffald/sdk#3 (the ReviewLinks resource on the SDK side). This PR pins the submodule to that branch tip; the SDK PR must land first (or be reviewed concurrently).
Architecture
Migration (
326_review_links_and_anon_reviews.sql)core.review_linkstable:id, subject_user_id, token, label, expires_at, max_uses, used_count, is_revoked, timestampscore.reviews.author_user_idrelaxed to nullable; existing UNIQUE constraint replaced by a partial unique index that only applies whenauthor_user_id IS NOT NULLcore.reviewsremain blocked by RLS — the Edge Function uses the service role after token validation. All anon submissions are forced through the API layer so future rate-limiting / anti-bot can live there.API (
packages/supabase/functions/api/routes/review-links.ts, mounted at/v1/reviews/links)POST /v1/reviews/links(auth) — create a link, returns{ id, token, share_url, label, expires_at, max_uses, used_count, created_at }GET /v1/reviews/links(auth) — list mineDELETE /v1/reviews/links/:id(auth) — revokeGET /v1/reviews/links/by-token/:token(anon) — validate token, return subject infoPOST /v1/reviews/links/by-token/:token/submit(anon) — submit review. Validates not-revoked / not-expired / under max_uses, optionally dedupes by reviewer email, inserts withauthor_user_id = NULL+metadata.via_review_link = link_id, incrementsused_count(best-effort)SDK (
packages/sdksubmodule bump)ReviewLinksresource, types,client.reviewLinks. PR: Scaffald/sdk#3scf-core hooks (
packages/scf-core/utils/review-links-sdk-hooks.ts)useMyReviewLinks,useCreateReviewLinkMutation,useRevokeReviewLinkMutation(worker side)useReviewLinkByToken,useSubmitReviewByTokenMutation(anon side)Worker UI (
packages/scf-core/features/profile/components/RequestReviewModal.tsx)/profilenext to "Share profile"Share.shareon iOS/AndroidPublic form (
apps/scaffald/app/(public)/reviews/[token].tsx)Verification
Local (this branch):
pnpm --filter @scf/core run check:type— cleancd apps/scaffald && pnpm exec tsc --noEmit— cleanpnpm exec biome linton all touched files — cleanpnpm exec vitest run features/profile features/applications features/auth— 292/295 pass (3 skipped, 0 failed)pnpm prepush— affected builds + tests passpnpm --filter @scaffald/sdk run build) — DTS cleanManual (post-merge, after migration applied to dev/preview):
Worker side:
<origin>/reviews/<token>)Public form (no auth):
Database (post-migration):
select * from core.review_links— new table exists with the right columnsselect author_user_id from core.reviews where author_user_id is null limit 1— anon reviews land hereDeployment note
This PR ships a migration. Apply it to dev/preview/prod via the team's normal Supabase deploy process (
cd packages/supabase && pnpm supa db pushagainst each project). The migration is additive (new table, relaxed constraint, new partial index) and reversible. Existing review data is unaffected.Out of scope (deferred to v1.4.0)
Linear
SC-38 — labeled v1.3.0. Transition to Done after merge + migration applied.
🤖 Generated with Claude Code