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
18 changes: 18 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Verify prototype
on: [push, pull_request]
permissions:
contents: read
jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
with:
persist-credentials: false
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: "24"
cache: npm
- run: npm ci
- run: npm run check
- run: npm audit --omit=dev --audit-level=high
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules/
.next/
.env*
!.env.example
*.tsbuildinfo
coverage/
.local-data/
4 changes: 4 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.next
node_modules
package-lock.json
next-env.d.ts
119 changes: 118 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,119 @@
# Commonlight
A BC+AI member portrait prototype with consent-based capture, authentic photo cleanup, consistent styling, and optional shareable galleries.

**Working name · private-source local prototype for BC + AI member portraits.**

A shared frame and restrained colour grade, with the actual person preserved.
Built with Next.js, React, TypeScript and Sharp. No image model, inference account,
application analytics, remote font, or uploaded real-person fixture is included.
Next.js itself enables anonymous CLI/build usage telemetry by default. To opt out
for one run, set `NEXT_TELEMETRY_DISABLED=1` for that command; see the
[official Next.js telemetry documentation](https://nextjs.org/telemetry).

## Run locally

Node 22.13+ (Node 24 LTS recommended):

```sh
npm ci
npm run dev
```

Open http://localhost:3000. Development and production launchers bind only to
127.0.0.1; API routes reject non-loopback origins. This is intentionally **not a
production deployment**. Start production locally with `npm run build && npm start`.

## Try the workflow

1. Read and select capture/processing permission.
2. Upload a still JPEG/PNG/WebP (up to 10 MB, 40 megapixels), or grant the browser
camera permission. Camera permission is requested only by the camera button.
3. Optionally add a name and/or BC + AI text mark. Prepare the portrait.
4. Compare the full-frame cleaned preview and processed 4:5 portrait. Download the exact original or prepared JPEG. Inspect framing carefully: center cropping does not detect faces.
5. Separately check subject consent to create a gallery link. The link exposes
only the processed JPEG. Revoke it or delete both images from the review page.

All tests generate geometric solid-colour fixtures, not portraits of real people.
The hero is an abstract CSS silhouette, not an example processing result.

## What the baseline actually does

- Sharp decodes and checks still raster images; malformed, unsupported and overly
large inputs fail closed. EXIF orientation is applied before metadata stripping.
- The exact validated uploaded bytes are retained privately with their correct
JPEG/PNG/WebP media type and download extension. Original metadata is preserved
only in this private download. A separate full-frame JPEG preview and final
processed JPEG are re-encoded with EXIF/GPS/XMP stripped.
- Center crop to 576 × 720; +3.5% global brightness and 96% saturation; optional
escaped text overlay; final 8-bit sRGB JPEG. This does not restore missing detail
or make an 8-bit source into a higher-dynamic-range photograph.
- No face/body/age edits, generated details, background replacement or relighting.
Poor exposure, clipping, focus, and unsuitable framing need a better source.

## Privacy and deliberate prototype limits

Images are kept only in process-private memory, never in public/static paths or
on disk. The single-process store holds at most 12 portraits, with at most two
upload/processing operations at once. Admission happens before any request-body
read, and invalid options are rejected before admission. Every portrait expires
no later than the owning session (24 hours from session creation), so late-session
uploads have a shorter remaining lifetime. Expiry blocks access; owned timers remove
records and links when due. Server restart clears everything. Timers are subject
to runtime scheduling; read-time expiration is immediate.

Private access requires an expiring server-issued HttpOnly/SameSite=Strict session
cookie. Public links use distinct random capabilities and cannot access originals
or administration. No permanent credentials or service accounts are created.
Sharing is an explicit second action; unguessability is not a substitute for
subject consent. Revocation cannot erase copies viewers have already downloaded.
Gallery links are local and useful only on the same reachable local server.

Reloading loses review controls. Download anything to keep before leaving. A
cancelled/disconnected upload that finished just before cancellation may remain
private until expiry. Aborted processing that observes cancellation before commit
cannot store or publish its result. No processing ever publishes automatically.

## Architecture and future integrations

- `lib/contracts.ts`: size, consent, options, client response decoders.
- `lib/processor.ts`: `PortraitProcessor` and deterministic Sharp implementation.
- `lib/store.ts`: `PortraitStore`, bounded ephemeral memory adapter, short sessions.
- `lib/service.ts`: processing admission, cancellation fence, creation/publication.
- `lib/http.ts` and `app/api`: loopback/origin enforcement, auth and bounded bodies.
- `lib/camera.ts`: camera permission/stream ownership and cleanup.
- `app/page.tsx`: capture, review and separate publication user experience.

A hosted processor can implement `PortraitProcessor`; a private object store plus
transactional metadata store can implement `PortraitStore`. Neither is configured.
Before deployment: supply authorized identity/storage, review provider consent and
retention, add durable cancellation/job reconciliation, rate limits and deployment
resource boundaries, and run real-browser acceptance. Never expose the memory
adapter through multiple workers/serverless instances or remove loopback guards
without revisiting the threat model.

## Verify

```sh
npm run check
```

Unit and route integration tests cover dimensions/encoding, metadata, deterministic
output, input/consent rejection, ownership, expiry, sharing/revocation/deletion,
concurrency reservations, cancellation and delayed camera permission cleanup.
Real-browser camera/focus/navigation/mobile visual testing is separately required;
this environment prohibited localhost browser access, so it is **not claimed**.
See `docs/plans/portrait-baseline/` for current acceptance and limitations.

## Visual reference

Read-only observation of [bc-ai.ca](https://bc-ai.ca/) on 2026-10-02: near-black
`#0a0d12`, lime `#dfe250`, muted `#b8bcc4`, rounded panels and compact uppercase
labels. No BC + AI organization repository/site was modified or people imagery
copied. The optional mark is plain text, pending brand approval for official assets.

## Dependency ownership

Next/React own application routing/rendering (MIT), TypeScript/tsx static/build
execution (Apache-2.0/MIT), Sharp raster decoding/encoding (Apache-2.0; its bundled
native dependencies carry their own notices), ESLint/TypeScript/React Hooks/Next plugins own static checks; Prettier formatting.
Versions and integrity are locked in package-lock.json. Maintain with tests/build
and dependency audit; a clean audit is not a security guarantee.
73 changes: 73 additions & 0 deletions app/api/portraits/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { NextRequest } from "next/server";
import {
boundedBody,
failure,
jpeg,
json,
mutation,
owner,
originalDownload,
} from "@/lib/http";
import { state } from "@/lib/service";
import { AppError } from "@/lib/contracts";
export const runtime = "nodejs";
type Context = { params: Promise<{ id: string }> };
export async function GET(request: NextRequest, context: Context) {
try {
const identity = owner(request);
const { id } = await context.params;
const kind = request.nextUrl.searchParams.get("kind");
if (kind !== "original" && kind !== "preview" && kind !== "processed")
throw new AppError(
400,
"invalid",
"Choose original, preview or processed.",
);
const portrait = state.service.store.owned(id, identity);
return kind === "original"
? originalDownload(portrait.original, portrait.originalFormat)
: jpeg(portrait[kind]);
} catch (e) {
return failure(e);
}
}
export async function POST(request: NextRequest, context: Context) {
try {
mutation(request);
const identity = owner(request);
const { id } = await context.params;
let data: unknown;
try {
data = JSON.parse((await boundedBody(request, 1024)).toString());
} catch (e) {
if (e instanceof AppError) throw e;
throw new AppError(400, "invalid", "Invalid action.");
}
if (!data || typeof data !== "object" || !("action" in data))
throw new AppError(400, "invalid", "Invalid action.");
if (
data.action === "publish" &&
"consent" in data &&
Object.keys(data).every((k) => ["action", "consent"].includes(k))
)
return json(state.service.publish(id, identity, data.consent));
if (data.action === "revoke" && Object.keys(data).length === 1) {
state.service.store.revoke(id, identity);
return json({ revoked: true });
}
throw new AppError(400, "invalid", "Invalid action.");
} catch (e) {
return failure(e);
}
}
export async function DELETE(request: NextRequest, context: Context) {
try {
mutation(request);
const identity = owner(request);
const { id } = await context.params;
state.service.store.delete(id, identity);
return json({ deleted: true });
} catch (e) {
return failure(e);
}
}
30 changes: 30 additions & 0 deletions app/api/portraits/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { NextRequest } from "next/server";
import { boundedBody, failure, json, mutation, owner } from "@/lib/http";
import { state } from "@/lib/service";
import { AppError, decodeOptions } from "@/lib/contracts";
export const runtime = "nodejs";
export async function POST(request: NextRequest) {
try {
mutation(request);
const identity = owner(request);
let options: unknown;
try {
options = JSON.parse(
decodeURIComponent(request.headers.get("x-portrait-options") ?? ""),
);
} catch {
throw new AppError(400, "invalid", "Invalid portrait options.");
}
return json(
await state.service.create(
() => boundedBody(request),
decodeOptions(options),
{ token: identity, expiresAt: state.sessions.expiresAt(identity) },
request.signal,
),
201,
);
} catch (e) {
return failure(e);
}
}
15 changes: 15 additions & 0 deletions app/api/public/[token]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { failure, jpeg, localOnly } from "@/lib/http";
import { state } from "@/lib/service";
export const runtime = "nodejs";
export async function GET(
request: Request,
context: { params: Promise<{ token: string }> },
) {
try {
localOnly(request);
const { token } = await context.params;
return jpeg(state.service.store.published(token).processed);
} catch (e) {
return failure(e);
}
}
28 changes: 28 additions & 0 deletions app/api/session/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NextRequest } from "next/server";
import { state } from "@/lib/service";
import { failure, json, mutation } from "@/lib/http";
import { RETENTION_MS } from "@/lib/contracts";
export const runtime = "nodejs";
export async function POST(request: NextRequest) {
try {
mutation(request);
const existing = request.cookies.get("commonlight_session")?.value;
try {
state.sessions.require(existing);
return json({ ready: true });
} catch {
/* Expired sessions get new bounded capabilities. */
}
const response = json({ ready: true });
response.cookies.set("commonlight_session", state.sessions.create(), {
httpOnly: true,
sameSite: "strict",
secure: new URL(request.url).protocol === "https:",
path: "/",
maxAge: RETENTION_MS / 1000,
});
return response;
} catch (e) {
return failure(e);
}
}
36 changes: 36 additions & 0 deletions app/gallery/[token]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { notFound } from "next/navigation";
import { state } from "@/lib/service";
export const dynamic = "force-dynamic";
export default async function Gallery({
params,
}: {
params: Promise<{ token: string }>;
}) {
const { token } = await params;
try {
state.service.store.published(token);
} catch {
notFound();
}
return (
<main className="gallery">
<p className="eyebrow">COMMONLIGHT / BC + AI</p>
<h1>A face from the room.</h1>
<img
src={`/api/public/${encodeURIComponent(token)}`}
alt="Portrait shared with the subject’s consent"
/>
<p>
Shared by the subject’s choice. This link expires within 24 hours and
can be revoked.
</p>
<a
href={`/api/public/${encodeURIComponent(token)}`}
download="commonlight-portrait.jpg"
className="button primary"
>
Download portrait ↓
</a>
</main>
);
}
Loading
Loading