Skip to content

feat(reviews): shareable review links + anon review submission (SC-38) - #280

Merged
thinkclay merged 2 commits into
mainfrom
clay/sc-38-shareable-review-links
May 22, 2026
Merged

thinkclay merged 2 commits into
mainfrom
clay/sc-38-shareable-review-links

Conversation

@thinkclay

Copy link
Copy Markdown
Contributor

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)

  • 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 granted (the Edge Function looks up by exact token, which is 32 hex chars of v4 UUID entropy)
  • core.reviews.author_user_id relaxed to nullable; existing UNIQUE constraint replaced by a partial unique index that only applies when author_user_id IS NOT NULL
  • Anon writes to core.reviews remain 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 mine
  • DELETE /v1/reviews/links/:id (auth) — revoke
  • GET /v1/reviews/links/by-token/:token (anon) — validate token, return subject info
  • POST /v1/reviews/links/by-token/:token/submit (anon) — submit review. Validates not-revoked / not-expired / under max_uses, optionally dedupes by reviewer email, inserts with author_user_id = NULL + metadata.via_review_link = link_id, increments used_count (best-effort)

SDK (packages/sdk submodule bump)

  • New ReviewLinks resource, types, client.reviewLinks. PR: Scaffald/sdk#3

scf-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)

  • New "Request review" button on /profile next to "Share profile"
  • Optional label input ("Foreman at Acme") for tracking
  • Generates link → 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 on mount. Invalid/expired/revoked → friendly error screen with a CTA back to scaffald.com.
  • Renders the worker's display name + headline so reviewer knows who they're vouching for.
  • Form fields: reviewer name (required), email (optional), relationship (instructor / manager / coworker / client / foreman / supervisor / other), 1-5 star rating (custom star row), optional headline, body (max 2000 chars).
  • Submit → success screen with a deep-link to the public profile.

Verification

Local (this branch):

  • pnpm --filter @scf/core run check:type — clean
  • cd apps/scaffald && pnpm exec tsc --noEmit — clean
  • pnpm exec biome lint on all touched files — clean
  • pnpm exec vitest run features/profile features/applications features/auth — 292/295 pass (3 skipped, 0 failed)
  • pnpm prepush — affected builds + tests pass
  • SDK rebuilt (pnpm --filter @scaffald/sdk run build) — DTS clean

Manual (post-merge, after migration applied to dev/preview):

Worker side:

  • Open /profile → "Request review" button next to "Share profile"
  • Tap → modal renders, optional label field
  • Tap "Generate review link" → QR + URL + Copy + Share appear
  • Copy → URL is on clipboard (format: <origin>/reviews/<token>)
  • Generate a second link with a label → both show in the "Other active links" section
  • Tap Revoke → toast confirms, row disappears

Public form (no auth):

  • Open the generated URL in an incognito window → form renders with worker's name + headline
  • Submit without filling required fields → inline error
  • Fill name, choose relationship, choose rating, write body → submit → success screen
  • Tap "View {worker}'s profile" → routes to /users/{slug} → new review appears
  • Open the URL again, try to submit with the same email → 409 (dedup)
  • Revoke the link in the worker UI → re-opening the public URL shows the "not available" screen

Database (post-migration):

  • select * from core.review_links — new table exists with the right columns
  • select author_user_id from core.reviews where author_user_id is null limit 1 — anon reviews land here

Deployment 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 push against 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)

  • Anti-bot / CAPTCHA on the public form (SC-32 covers 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
  • Pinning a top review to the profile header (mentioned in the SC-38 description; needs design)

Linear

SC-38 — labeled v1.3.0. Transition to Done after merge + migration applied.

🤖 Generated with Claude Code

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]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +437 to +441
await service
.schema("core")
.from("review_links")
.update({
used_count: link.used_count + 1,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +85 to +87
CREATE POLICY review_links_anon_select ON core.review_links
FOR SELECT TO anon
USING (TRUE);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +139 to +141
// Active links = non-revoked, non-expired
const activeLinks = (links ?? []).filter((l) => !l.is_revoked)
const latestLink = activeLinks[0] ?? null

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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]>
@thinkclay

Copy link
Copy Markdown
Contributor Author

Addressed all three Codex review comments in 480d7bc80:

P1 — Atomic max_uses enforcement (review-links.ts submit endpoint)
Replaced the validate-then-increment flow with a compare-and-swap UPDATE that claims the slot atomically. PostgREST's chained .eq("id", id).eq("used_count", read_used_count).eq("is_revoked", false) composes into a WHERE clause; if a concurrent caller 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 errors for known-invalid states, but it's no longer load-bearing for correctness. If the review insert fails after the claim succeeds, a CAS refund is issued so a failed write doesn't burn a slot.

P1 — Anon SELECT on review_links is gone (migration 326)
Dropped the USING (TRUE) policy entirely. The Edge Function already uses the service role for token lookup (bypasses RLS), so the policy was dead code on top of being a token-enumeration vector. Comment in the migration documents the deliberate absence.

P2 — Modal's activeLinks filter (RequestReviewModal.tsx)
Now also excludes expired (expires_at in the past) and maxed-out (used_count >= max_uses) links, not just revoked ones, so the QR/Copy/Share UI no longer surfaces tokens that will fail at submit.

Also bumped the packages/sdk submodule from the now-deleted feature-branch commit to the squash-merge of Scaffald/sdk#3 on main (0518e70).

Smoke tests after the changes:

  • pnpm --filter @scf/core run check:type — clean
  • cd apps/scaffald && pnpm exec tsc --noEmit — clean
  • pnpm exec biome lint on touched files — clean
  • pnpm exec vitest run features/profile features/applications features/auth — 292/295 (3 skipped, 0 failed)
  • pnpm prepush — affected builds + tests pass

@thinkclay
thinkclay merged commit 78fe608 into main May 22, 2026
3 of 16 checks passed
@thinkclay
thinkclay deleted the clay/sc-38-shareable-review-links branch May 22, 2026 02:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant