Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion docs/specs/access.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Every project here is public, and one person writes (rationale).
- **Must know the writer by their GitHub account's numeric ID, never their login**, which can be renamed and taken by someone else.
- **Must sign anyone else straight back out when GitHub returns them**, and never treat their session as the writer's (rationale). **Must then send them to selfie.dev's mailing list signup, `https://selfie.dev/#join=<email>`, with the verified email GitHub gave, or none**, in the URL's fragment, which a browser never sends to a server or in a `Referer` (rationale). `site/public/join.js` fills the form in and says the cloud isn't open yet, and joining stays their click.
- **Must drive the adapter from the Worker, and let nothing outside reach it but GitHub's callback, `GET /api/auth/callback/github`.** Its CSRF token, its sign-in and sign-out writes, and its account list are only ever the Worker's own requests to it, and its email routes are reached by nothing. It's given only its own bindings, and an email sender that sends nothing.
- **Must ask the adapter who a review request is from only where the answer is used: a batch's view, which says whether they may decide, and a decision.** An image, a diff, and every other read never reach it (rationale).
- **Must refuse a sign-in or sign-out from another site, and send a person only to a path on this site after signing in**, held in a 10-minute `__Host-` cookie, since the adapter returns everyone to one fixed path.
- **Must end a sign-in GitHub or the adapter failed at `/sign-in?failed=<error code>`**, logging what the adapter answered under that code, and show the code only if it's one the Worker could have made (`docs/specs/ui.md` → ReviewSource).
- **Must keep `sameOriginWrites` and `pageHeaders` on the review routes.** The sync routes answer only to a bearer token, and never read a cookie.
Expand Down Expand Up @@ -76,7 +77,7 @@ GitHub decides. Selfie keeps no member list of its own.
### Serving images

- **Never give an image a direct R2 URL.** Every image is served by the Worker after an access check, and the bucket issues no presigned URLs. Its public URLs are already off ([Who can do what](#who-can-do-what)).
- **Never treat an image hash as a secret**, since anyone holding an image can compute it. Access depends on who is asking and which project they ask about.
- **Never treat an image hash as a secret**, since anyone holding an image can compute it. Access depends on who is asking and which project they ask about, which is still never a question to the auth adapter per image ([Who can do what](#who-can-do-what)).
- **Must serve images with `Cache-Control: private`, for public repositories too**, since a repository can become private and a shared cache would keep serving it.
- **Must serve images with `X-Content-Type-Options: nosniff`, and a type read from their first bytes**, since the cloud doesn't read a file's body (`docs/specs/sync.md` → What a store takes).
- **Must rate-limit anonymous requests**, since anyone can make them and each one costs an R2 read.
Expand Down
2 changes: 2 additions & 0 deletions docs/specs/access.rationale.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,6 @@

**On to the mailing list.** Anyone who gets as far as GitHub's consent screen wants Selfie, and doesn't know who its one writer is, so they're offered the list rather than a refusal. Their address is already in hand, so it's filled in, but in the fragment: a query string would land in Cloudflare's and Pages' logs, and in MailerLite's if the page's own requests carried a `Referer`. The form still needs their click, and MailerLite's double opt-in still applies.

**Asking who it is only where that's used.** Each question is a request to the adapter, which keeps Better Auth's rate limit on, by default 100 requests in 10 seconds from one address. A batch's page asks for a diff and two images for each changed story, 4 at a time, so the 143 stories of PR #108's batch, signed in, asked the adapter over 400 times in a few seconds. Past about 100 it answered 429, those requests failed, and 34 stories were left out of the deltas offered (`docs/specs/ui.md` → Screens). Anyone can read an image or a diff anyway, and a decision asks again for itself, so nothing is lost by not asking.

**An upload token rather than OIDC.** It's a secret a repository has to hold, which OIDC avoids, and it costs a rotation if it leaks. A leak lets someone upload to a public project, which can't approve anything, and can only add batches at commits GitHub has.
3 changes: 2 additions & 1 deletion docs/specs/ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,11 @@ Source of truth: `ui/src/client/`.
- **Must find a delta from a pair's own diff, fetched by both hashes, and never a review's stats** ([Screens](#screens)), since those are by story, and could be of another pair.
- **Must group raw hunks, not the groups a list shows, by the size of each side, and then by the SHA-256 of each side's pixels**, wherever in an image a hunk sits (rationale). It decodes only images with a size at least 3 stories share.
- **Must key a hunk as `<golden width>x<golden height>><current width>x<current height>:<golden digest>:<current digest>`, each digest the lowercase hex SHA-256 of that side's pixels as RGB row by row, as the store has them, or empty for a side with no pixels**, through `hunkKeysOf`, so Node and a browser give one pair the same keys (rationale). A key accepted before keys were RGB matches no hunk, and is ignored.
- **Must use pixels a browser decoded only if they hash to the image they were fetched by**, as the store computes an image's hash (`docs/specs/store.md` → Image identity). A pair either of whose images doesn't is one that can't be looked at, so it's in no delta (rationale).
- **Must use pixels a browser decoded only if they hash to the image they were fetched by**, as the store computes an image's hash (`docs/specs/store.md` → Image identity). A pair either of whose images doesn't is one that can't be looked at, so it's in no delta, and counts among the stories it couldn't look at, without being tried again (rationale).
- **Must only group a hunk that can be redrawn on its own:** one with the same size on both sides, or one the whole width of both images. A narrower hunk that changes height only balances out with others in its column, so it stays a hunk to look at.
- **Must grow a delta, and never merge two:** once all are hashed, a straggler, which is a hunk whose pixels fewer than 3 stories have, joins the first delta of its size whose own pixels it's within a level of in every channel, on both sides (rationale). Deltas are tried most stories first, counting every story whatever's decided, so what a hunk joins doesn't change as images are approved. Only a hunk of at most `MAX_FIT_AREA` pixels, both sides together, is fitted, each story's images are decoded once for all of its hunks being fitted, and a delta's own pixels are held only while fitting.
- **Must say which stories only fit a delta**, by how many beside its count, and on each as it's gone through, and list them after the stories that are exactly its pixels.
- **Must try a story again when the server or the connection refused it**, which is a 429, a 5xx, or no answer: twice more, after half a second and then two. **Must say how many changed stories it still couldn't look at, with a way to look again**, so what's offered never reads as all there is (rationale). Looking again keeps whatever it found.
- **Must offer each delta at least 3 undecided changed stories have**, most stories first, once all of them have been looked through, each with how many stories and a crop of it before and after. An image with a decision isn't affected.
- **Must let someone go through a delta's stories before accepting it**, one delta at a time, starting with the first and moving on once it's accepted: previous and next through its stories, wrapping around, naming each with a link to it, and showing that story's crop and all of its image on each side as it is on record, with the delta outlined where that story has it (rationale).
- **Must say what's accepted, and let each be undone**, which brings its hunks back, the ones that joined it too, and takes back no approval. Accepting holds the key of every hunk it covers, so a story's page redraws the ones that joined it too, wherever it's opened.
Expand Down
2 changes: 2 additions & 0 deletions docs/specs/ui.rationale.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ Evidence and reasoning for `docs/specs/ui.md`, keyed by its headings.

**Repeated changes, in the browser.** A header that grew 15 rows made all 124 stories of one batch change, and each had to be looked at for whatever else was in it. Of 146 distinct hunks there, 28 were in at least 3 stories, and those accounted for all of 83 images. Whether accepting one should outlive a batch, or be something a team shares, is what **Scope: hunks** in `docs/specs/renders.md` is for. Nothing here narrows that, since a store only ever hears of an approval of a whole image.

**Saying what it couldn't look at.** Looking costs a request per pair's diff and two images each, so a batch of 143 changed stories makes over 400 requests. Signed in to the cloud, each once asked the auth adapter who was asking, its rate limit refused some, and 34 stories were left out of every delta without a word while the progress bar said done (`docs/specs/access.md` → Who can do what). That's fixed at the server, but anything else that refuses a few in a burst would do the same, and a delta that's missing stories looks no different from one that isn't. A 404 or an image that won't decode is never tried again, since it won't change, but it's still counted.

**Why say what was approved earlier.** A merged pull request's commit reads as nothing differing, since its approvals are what it's compared with, which is right for what blocks it and hides what it did. It's found on the page, instead of on the batch that was approved, since that's where a link from a commit lands, and nothing else leads from a later commit to an earlier batch.

**Why say what changed since the base, approved or not.** Someone following a commit's status from GitHub wants to know what it changed. What's left to decide on is something else: it leaves out what was approved on an earlier commit, and takes in whatever its base never approved. A decision on a row goes to the batch's own row for the same image, since that's what the store decides on, and a row approved on another batch has nothing left to decide here.
Expand Down
1 change: 1 addition & 0 deletions ui/src/client/BatchScreen.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ export const ChangesApprovedEarlier: Story = { args: { view: viewOf([]), state:
export const ChangesApprovedEarlierListed: Story = { args: { view: viewOf([]), state: { approvedSince: APPROVED_EARLIER }, search: "?show=approved-earlier" } };
export const LookingForRepeatedChanges: Story = { args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ progress: 40 }) } };
export const RepeatedChanges: Story = { args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ offers: OFFERS }) } };
export const RepeatedChangesNotAllLookedAt: Story = { args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ offers: OFFERS.slice(1), missed: 34 }) } };
export const LookingThroughADelta: Story = {
args: { view: viewOf(SOME_CHANGES), deltas: deltasOf({ offers: OFFERS }) },
play: async ({ canvasElement }) => {
Expand Down
14 changes: 11 additions & 3 deletions ui/src/client/DeltaOffers.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// The changes that repeat across stories, to accept once instead of looking at each.
import { Button, Details, Heading, ProgressBar, Stack, Text, useDetails } from "@primer/react";
import { Banner, Button, Details, Heading, ProgressBar, Stack, Text, useDetails } from "@primer/react";
import { ScrollableRegion } from "@primer/react/experimental";
import { useState, type ReactNode } from "react";
import type { RenderRow } from "../shared/api.ts";
Expand Down Expand Up @@ -191,7 +191,7 @@ function AcceptedDeltas({ deltas }: { deltas: DeltaState }) {
export function DeltaOffers({ deltas, state, batchId }: { deltas: DeltaState; state: BatchState; batchId: string }) {
const [pending, setPending] = useState<{ readonly delta: Delta; readonly rows: readonly RenderRow[] } | null>(null);
const [openKey, setOpenKey] = useState<string | null>(null);
const { progress, offers, taken } = deltas;
const { progress, missed, offers, taken } = deltas;
// One's always open, so accepting one moves on to the next to look at.
const open = offers.find(({ key }) => key === openKey) ?? offers[0];

Expand All @@ -203,7 +203,7 @@ export function DeltaOffers({ deltas, state, batchId }: { deltas: DeltaState; st
</Stack>
);
}
if (offers.length === 0 && taken.length === 0) return null;
if (offers.length === 0 && taken.length === 0 && missed === 0) return null;

const pick = (delta: Delta) => {
const rows = deltas.finishes(delta);
Expand All @@ -224,6 +224,14 @@ export function DeltaOffers({ deltas, state, batchId }: { deltas: DeltaState; st
<Heading as="h3" id="deltas-heading" variant="small">
Repeated changes
</Heading>
{missed > 0 && (
<Banner
variant="warning"
title={`Couldn't look at ${plural(missed, "changed story", "changed stories")}`}
description="So a repeated change may be missing here, or be in more stories than it says."
primaryAction={<Banner.PrimaryAction onClick={deltas.retry}>Look again</Banner.PrimaryAction>}
/>
)}
{offers.length > 0 && (
<>
<Text as="p" className="selfie-muted">
Expand Down
31 changes: 25 additions & 6 deletions ui/src/client/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,30 +25,49 @@ import {
} from "../shared/api.ts";
import { BASE, isHosted } from "./base.ts";

/** What went wrong, in words a screen can show. `code` tells the cases apart, and `id` is the code the server logged it under, if it did. */
/**
* What went wrong, in words a screen can show. `code` tells the cases apart, `id` is the code the server logged it under,
* if it did, and `status` is what the server answered, if it did.
*/
export class RequestError extends Error {
readonly code: string;
readonly id: string | null;
readonly status: number | null;

constructor(code: string, message: string, id: string | null = null) {
constructor(code: string, message: string, id: string | null = null, status: number | null = null) {
super(message);
this.code = code;
this.id = id;
this.status = status;
}
}

async function request<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response;
/** Whether asking again could work: the connection dropped, the server was busy, or something went wrong there. */
export const mightPassLater = (error: unknown) => error instanceof RequestError && (error.code === "unreachable" || error.status === 429 || (error.status ?? 0) >= 500);

/** The server's answer, whatever it is, or a `RequestError` saying it couldn't be reached. */
async function reached(url: string, init?: RequestInit): Promise<Response> {
try {
response = await fetch(`${BASE}/api${path}`, init);
return await fetch(url, init);
} catch (error) {
if (init?.signal?.aborted) throw error;
throw new RequestError("unreachable", isHosted ? "Can't reach Selfie. Check your connection, and try again." : "Can't reach the Selfie server. Is selfie ui still running?");
}
}

/** An image's bytes from `imageUrl` or `diffImageUrl`, or a `RequestError` saying what the server answered. */
export async function fetchImage(url: string): Promise<Blob> {
const response = await reached(url);
if (!response.ok) throw new RequestError("bad-response", `The server answered ${response.status} for ${url}.`, null, response.status);
return response.blob();
}

async function request<T>(path: string, init?: RequestInit): Promise<T> {
const response = await reached(`${BASE}/api${path}`, init);
const body = (await response.json().catch(() => null)) as T | ApiError | null;
if (!response.ok || body === null) {
const error = (body as ApiError | null)?.error;
throw new RequestError(error?.code ?? "bad-response", error?.message ?? `The server answered ${response.status}.`, error?.id ?? null);
throw new RequestError(error?.code ?? "bad-response", error?.message ?? `The server answered ${response.status}.`, error?.id ?? null, response.status);
}
return body as T;
}
Expand Down
Loading
Loading