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: 0 additions & 3 deletions .dev.vars.example
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
OPENAI_API_KEY=
OPENAI_MODEL=gpt-5-mini
AI_EXTRACTOR=mock

# Auth (local dev: leave SESSION_SECRET unset to auto-login as the local user)
SESSION_SECRET=
RESEND_API_KEY=
TURNSTILE_SECRET_KEY=
15 changes: 7 additions & 8 deletions DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Use this folder for future development, commits, and deploys. The earlier Codex

## Live Beta

- URL: `https://cardcap.codylecates.workers.dev`
- URL: `https://cc.csi.run`
- Worker name: `cardcap`
- D1 database: `cardcap-db`
- D1 database ID: `d3a74ece-fba4-4d92-a167-dfa21998c9ab`
Expand All @@ -18,9 +18,8 @@ Use this folder for future development, commits, and deploys. The earlier Codex

The Worker expects these secrets to be configured in Cloudflare:

- `OPENAI_API_KEY`
- `SESSION_SECRET` (32+ random characters; rotating it signs everyone out)
- `RESEND_API_KEY` (sender domain must be verified in Resend, DKIM green)
Sign-in links are sent through the native Cloudflare EMAIL binding from `cardcap@notify.copperstateit.com`. The domain must be verified for Email Sending.
- `TURNSTILE_SECRET_KEY` (paired with the public `TURNSTILE_SITE_KEY` var in wrangler.jsonc)

`BETA_ACCESS_CODE` is retired and should be deleted from the Worker.
Expand All @@ -33,8 +32,8 @@ Do not commit secret values. Local development secrets belong in `.dev.vars`, wh
2. Fresh start (wipes pre-auth beta data): `npx wrangler d1 execute cardcap-db --remote --command "DELETE FROM extraction_jobs; DELETE FROM contacts; DELETE FROM users;"`
3. Apply migrations: `npx wrangler d1 migrations apply cardcap-db --remote`
4. Create a Turnstile widget in the Cloudflare dashboard (Managed mode, hostname `cardcap.codylecates.workers.dev`); paste the site key into `TURNSTILE_SITE_KEY` in `wrangler.jsonc`, then `npx wrangler secret put TURNSTILE_SECRET_KEY`
5. `npx wrangler secret put SESSION_SECRET` and `npx wrangler secret put RESEND_API_KEY`
6. Confirm the `SENDER_EMAIL` var's address/domain is verified in Resend (currently `cody@copperstateit.com`; adjust the var if using a different sender)
5. `npx wrangler secret put SESSION_SECRET`
6. Verify the configured sender domain in Cloudflare Email Service
7. `npx wrangler secret delete BETA_ACCESS_CODE`
8. `npm run build && npx wrangler deploy`
9. Smoke: `/api/health` returns `ok`; full sign-in round-trip from a phone; check a corporate-style inbox's spam folder for the link; upload one card and confirm `extractionMode: "openai"`; download the iContact CSV and test-import it into iContact.
Expand Down Expand Up @@ -77,9 +76,9 @@ npx cf auth login
After deployment, verify:

```powershell
Invoke-RestMethod -Uri 'https://cardcap.codylecates.workers.dev/api/health'
Invoke-RestMethod -Uri 'https://cc.csi.run/api/health'
```

Expected: JSON with `ok: true` and `extractor: openai`.
Expected: JSON with `ok: true` and `extractor: cloudflare`.

For full upload testing, unlock with the beta session, upload a real card image, confirm `extractionMode` is `openai`, then delete the temporary contact.
For full upload testing, unlock with the beta session, upload a real card image, confirm `extractionMode` is `cloudflare`, then delete the temporary contact.
16 changes: 4 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Phone-first business card capture for turning card photos into a searchable mini
- Review the source card beside or above editable contact fields.
- Save searchable contacts with email, phone, website, map, notes, tags, status, and next step.
- Export CSV, vCard, JSON, standalone HTML, or an iContact-ready CSV for email-marketing imports.
- Run AI extraction in mock mode locally, or switch to OpenAI with an API key.
- Extract card photos with Cloudflare Workers AI, or use mock photo extraction locally. Paste a signature, business details, or a website to review and save a contact.
- Abuse guards: Turnstile on sign-in, per-minute rate limits, and a 25-cards/day extraction quota per user.

## Local Development
Expand Down Expand Up @@ -43,22 +43,14 @@ npm run build
npm run deploy -- --dry-run
```

## Turn On OpenAI Extraction Locally
## Cloudflare extraction in development

Copy `.dev.vars.example` to `.dev.vars`, then set:

```text
OPENAI_API_KEY=your_key_here
OPENAI_MODEL=gpt-5-mini
AI_EXTRACTOR=openai
```

Restart the dev server after changing `.dev.vars`.
Sign in with `npx cf auth login`. The Worker uses the remote AI binding for photo and text extraction and the Browser Run binding for website lookup. Set `AI_EXTRACTOR=cloudflare` in `.dev.vars` for live photo extraction or `AI_EXTRACTOR=mock` for local photo fixtures.

## Auth in Local Dev

- Leave `SESSION_SECRET` unset in `.dev.vars` to auto-sign-in as the local user (no email needed).
- Set `SESSION_SECRET` to any 32+ character string to exercise the real magic-link flow; with no `RESEND_API_KEY`, the sign-in link is printed to the dev-server console instead of emailed.
- Set `SESSION_SECRET` to any 32+ character string to exercise the real magic-link flow. Sign-in links use the Cloudflare EMAIL binding.
- `TURNSTILE_SECRET_KEY` unset means the Turnstile check is skipped locally.

## Production deployment
Expand Down
16 changes: 11 additions & 5 deletions cloudflare.config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { bindings, defineConfig } from 'cf/config'

const sender = 'cardcap@notify.copperstateit.com'
const hostname = 'cc.csi.run'

export default defineConfig({
accountId: '584b3d4e1cb07efb65c315c7efcce589',
worker: {
name: 'cardcap',
domains: [hostname],
workersDev: true,
entrypoint: './src/worker/index.ts',
compatibilityDate: '2026-06-07',
compatibilityFlags: ['nodejs_compat'],
Expand All @@ -13,12 +18,13 @@ export default defineConfig({
},
observability: { enabled: true, redactQueryString: true, headSamplingRate: 1 },
env: {
AI_EXTRACTOR: bindings.text('openai'),
OPENAI_MODEL: bindings.text('gpt-5.4-mini'),
SENDER_EMAIL: bindings.text('cody@copperstateit.com'),
AI: bindings.ai({ dev: { remote: true } }),
BROWSER: bindings.browser({ dev: { remote: true } }),
AI_EXTRACTOR: bindings.text('cloudflare'),
SENDER_EMAIL: bindings.text(sender),
PUBLIC_ORIGIN: bindings.text(`https://${hostname}`),
EMAIL: bindings.sendEmail({ allowedSenderAddresses: [sender] }),
TURNSTILE_SITE_KEY: bindings.text('0x4AAAAAADix1GoVxjHxnCXP'),
OPENAI_API_KEY: bindings.secret(),
RESEND_API_KEY: bindings.secret(),
SESSION_SECRET: bindings.secret(),
TURNSTILE_SECRET_KEY: bindings.secret(),
// CF's D1 CLI reads ./migrations by default.
Expand Down
2 changes: 1 addition & 1 deletion e2e/access.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ let h: Harness

beforeEach(async () => {
h = await startHarness({ access: true })
h.openai.mode = {
h.inference.mode = {
kind: 'card',
card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], phones: ['(602) 555-0142'], website: '', address: '', tags: [], notes: '', confidence: 0.95, needs_review: false },
}
Expand Down
27 changes: 26 additions & 1 deletion e2e/browser/access.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,32 @@ async function upload(page: Page) {
}

test.beforeEach(async ({ request }) => {
await request.get('/__test/openai?mode=card')
await request.get('/__test/inference?mode=card')
})

test('reviewing and cancelling a website draft leaves the collection empty, saving retains its source', async ({ page }) => {
await openApp(page, uniqueEmail('capture'))
const company = 'Example Landscape'
const url = 'https://example.com/contact'
await page.route('**/api/contact-drafts', route => route.fulfill({ json: { contact: {
id: crypto.randomUUID(), name: '', company, role: '', email: '', phones: ['480-555-0101'], address: '', website: 'https://example.com',
tags: [], notes: '', status: 'New', nextStep: '', sourceImageKey: '', sourceImageUrl: '',
extractionConfidence: 0.9, needsReview: true, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
source: { url, text: company + ' 480-555-0101', checkedAt: new Date().toISOString() },
} } }))
await page.getByLabel('Paste a signature, business details, or a website').fill('example.com')
await page.getByRole('button', { name: 'Review contact' }).click()
await page.getByRole('button', { name: 'Cancel' }).click()
await expect(page.getByRole('heading', { name: WELCOME_HEADING })).toBeVisible()
await page.getByRole('button', { name: 'Review contact' }).click()
await page.getByRole('button', { name: 'Save contact' }).click()
await expect(page.getByRole('status')).toContainText('Saved')
await page.reload()
await openContact(page, company)
await expect(page.getByRole('link', { name: 'View source page' })).toHaveAttribute('href', url)
const csv = await (await page.request.get('/api/export.csv')).text()
expect(csv).toContain(company)
expect(csv).toContain(url)
})

test('first visit goes through the edge, returns to the same address, and shows no CardCap sign-in or password screens', async ({ page, baseURL }) => {
Expand Down
8 changes: 4 additions & 4 deletions e2e/browser/cardcap.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { PNG_BUFFER, PNG_HEIGHT, PNG_WIDTH } from '../fixtures'
import { chooseFromMenu, openContact, WELCOME_HEADING } from './helpers'

// Real Chromium against the built SPA + the real Worker on local Miniflare (see e2e/browser/server.ts).
// OpenAI/Resend are intercepted by the server; data is synthetic.
// Cloudflare inference and email are intercepted by the server; data is synthetic.

const UPSTREAM_SECRET = 'upstream-internal-detail-abc123'

Expand Down Expand Up @@ -37,7 +37,7 @@ async function downloadText(page: Page, itemName: string): Promise<{ text: strin
}

test.beforeEach(async ({ request }) => {
await request.get('/__test/openai?mode=card')
await request.get('/__test/inference?mode=card')
})

test('upload → review/edit → save → reload → export keeps exactly the corrected values', async ({ page, request }) => {
Expand Down Expand Up @@ -99,7 +99,7 @@ test('a failed extraction shows a safe message, leaves nothing behind, and a ret
await signIn(page, request, uniqueEmail('alice'))
const r2Before = await r2Keys(request)

await request.get('/__test/openai?mode=error')
await request.get('/__test/inference?mode=error')
await uploadCard(page)
const banner = page.locator('.banner.error')
await expect(banner).toBeVisible()
Expand All @@ -108,7 +108,7 @@ test('a failed extraction shows a safe message, leaves nothing behind, and a ret
expect(await r2Keys(request)).toEqual(r2Before)
await expect(page.getByRole('heading', { name: WELCOME_HEADING })).toBeVisible()

await request.get('/__test/openai?mode=card')
await request.get('/__test/inference?mode=card')
await uploadCard(page)
await expect(page.getByLabel('Name', { exact: true })).toHaveValue('Maria Okafor')
expect((await r2Keys(request)).length).toBe(r2Before.length + 1)
Expand Down
2 changes: 1 addition & 1 deletion e2e/browser/layout.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const uniqueEmail = () => `layout-${Date.now()}-${++counter}@example.test`

async function signIn(page: Page, request: APIRequestContext) {
const email = uniqueEmail()
await request.get('/__test/openai?mode=card')
await request.get('/__test/inference?mode=card')
await page.goto('/')
await page.getByRole('button', { name: 'Use email link' }).click()
await page.getByPlaceholder('you@company.com').fill(email)
Expand Down
10 changes: 5 additions & 5 deletions e2e/browser/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function main() {
const [email, seen] = decodeURIComponent(simCookie(req) || '').split('|')
return email && Number(seen) === epoch ? email : ''
}
h.openai.mode = {
h.inference.mode = {
kind: 'card',
card: {
name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'],
Expand Down Expand Up @@ -67,11 +67,11 @@ async function main() {
res.writeHead(link ? 200 : 404, { 'content-type': 'text/plain' }).end(link ? new URL(link).pathname + new URL(link).search : '')
return
}
if (url.pathname === '/__test/openai') {
if (url.pathname === '/__test/inference') {
const kind = url.searchParams.get('mode')
if (kind === 'error') h.openai.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' }
else if (kind === 'garbage') h.openai.mode = { kind: 'garbage' }
else h.openai.mode = { kind: 'card', card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], phones: ['(602) 555-0142'], website: 'sunrise.example', address: '12 Main St, Phoenix, AZ', tags: ['Luxury'], notes: 'Met at expo', confidence: 0.62, needs_review: true } }
if (kind === 'error') h.inference.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' }
else if (kind === 'garbage') h.inference.mode = { kind: 'garbage' }
else h.inference.mode = { kind: 'card', card: { name: 'Maria Okafor', company: 'Sunrise Realty Group', role: 'Broker', emails: ['maria@sunrise.example'], phones: ['(602) 555-0142'], website: 'sunrise.example', address: '12 Main St, Phoenix, AZ', tags: ['Luxury'], notes: 'Met at expo', confidence: 0.62, needs_review: true } }
res.writeHead(200).end('ok')
return
}
Expand Down
2 changes: 1 addition & 1 deletion e2e/browser/session-states.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function signIn(page: Page, request: APIRequestContext, email: string) {
}

async function withContact(page: Page, request: APIRequestContext) {
await request.get('/__test/openai?mode=card')
await request.get('/__test/inference?mode=card')
await signIn(page, request, uniqueEmail())
await page.locator('input[type=file][accept="image/*"]').setInputFiles({ name: 'maria.png', mimeType: 'image/png', buffer: PNG_BUFFER })
await expect(page.getByLabel('Name', { exact: true })).toHaveValue('Maria Okafor')
Expand Down
12 changes: 6 additions & 6 deletions e2e/cardcap.e2e.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ let h: Harness

beforeEach(async () => {
h = await startHarness()
h.openai.mode = { kind: 'card', card: CARD }
h.inference.mode = { kind: 'card', card: CARD }
})

afterEach(async () => {
Expand Down Expand Up @@ -163,7 +163,7 @@ describe('upload → review/edit → save → reload → export', () => {
describe('failed extraction', () => {
scenario('an extraction service error fails the upload cleanly: no contact, no orphaned image, no upstream detail leaked', async () => {
const alice = await h.signIn('alice@example.test')
h.openai.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' }
h.inference.mode = { kind: 'http-error', status: 500, body: 'upstream-internal-detail-abc123' }

const { res, text } = await uploadCard(alice)
expect(res.status).toBe(502)
Expand All @@ -176,7 +176,7 @@ describe('failed extraction', () => {

scenario('unparseable model output fails the upload cleanly with no contact and no orphaned image', async () => {
const alice = await h.signIn('alice@example.test')
h.openai.mode = { kind: 'garbage' }
h.inference.mode = { kind: 'garbage' }

const { res } = await uploadCard(alice)
expect([422, 502]).toContain(res.status)
Expand All @@ -188,10 +188,10 @@ describe('failed extraction', () => {

scenario('after a failed extraction the user can retry the same card and get one correct contact', async () => {
const alice = await h.signIn('alice@example.test')
h.openai.mode = { kind: 'http-error', status: 503, body: 'overloaded' }
h.inference.mode = { kind: 'http-error', status: 503, body: 'overloaded' }
expect((await uploadCard(alice)).res.status).toBe(502)

h.openai.mode = { kind: 'card', card: CARD }
h.inference.mode = { kind: 'card', card: CARD }
const retry = await uploadCard(alice)
expect(retry.res.status).toBe(201)

Expand All @@ -207,7 +207,7 @@ describe('failed extraction', () => {
const noFile = await alice.request('/api/cards/upload', { method: 'POST', body: emptyForm() })
expect(noFile.status).toBe(400)
expect(await h.r2Keys()).toEqual([])
expect(h.openai.calls).toBe(0)
expect(h.inference.calls).toBe(0)
})
})

Expand Down
34 changes: 34 additions & 0 deletions e2e/contact-capture.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { expect, it, vi } from 'vitest'
import worker from '../src/worker/index'
import type { Contact } from '../src/shared/types'
import { SESSION_SECRET, startHarness } from './harness'
import { utcDayStartIso } from '../src/shared/quota'

it('limits capture per account, returns an unsaved draft, and preserves its source after review', async () => {
const h = await startHarness()
try {
const db = await h.mf.getD1Database('DB')
const alice = await h.signIn('capture@example.test')
const run = vi.fn(async () => ({ response: { company: 'Acme Studio', phones: ['480-555-0101'] } }))
const env = { DB: db, SESSION_SECRET, AI: { run } } as unknown as Env
const input = 'Acme Studio\n480-555-0101'
const capture = (cookie: string) => worker.fetch(new Request('https://cardcap.test/api/contact-drafts', {
method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: JSON.stringify({ input }),
}), env, { waitUntil() {} } as unknown as ExecutionContext)
expect((await capture('')).status).toBe(401)
const response = await capture(alice.cookie)
expect(response.status).toBe(200)
const { contact } = await response.json() as { contact: Contact }
expect(contact.source?.text).toBe(input)
expect(await (await alice.request('/api/contacts')).json()).toEqual({ contacts: [] })
const saved = await alice.request('/api/contacts', { method: 'POST', body: JSON.stringify({ contact: { ...contact, needsReview: false } }) })
expect(saved.status).toBe(201)
const list = await (await alice.request('/api/contacts')).json() as { contacts: Contact[] }
expect(list.contacts[0]).toMatchObject({ name: '', company: 'Acme Studio', needsReview: false, source: contact.source })
await db.prepare('UPDATE capture_usage SET attempts = 25 WHERE day = ?').bind(utcDayStartIso()).run()
expect((await capture(alice.cookie)).status).toBe(429)
expect(run).toHaveBeenCalledTimes(1)
} finally {
await h.dispose()
}
})
Loading
Loading