# BoardRepo integration pilot: Connect, Pull and Push

Contact [BoardRepo](mailto:hello@boardrepo.com?subject=BoardRepo%20integration) to integrate your design tool or portal. Send your tool's name, logo, desktop/browser/backend environment, exact OAuth callbacks and browser origins, and the workflow you want to test. We register your integration and walk through it with you. There is no self-service app registration, developer dashboard or personal API key.

One HTTP API serves all three environments. The small TypeScript helper is optional. Git is optional. Send original project files; BoardRepo owns versions and any supported previews/comparisons.

### Request integration access

Email `hello@boardrepo.com` with subject **BoardRepo integration**. You can start with this short request before signing up to BoardRepo:

```text
Tool name and website:
Contact:
Runs in: desktop / browser / backend
Workflow: what users should be able to list, Pull, create or Push
Project formats:
```

During onboarding we collect the logo and exact OAuth callback URLs/browser origins, assign a client ID, and test the integration together. Backend clients also receive a secret privately; desktop/browser clients receive no secret. The registration identifies your software. Each end user still connects their own BoardRepo account and approves access.

The pilot grants the user's accessible board library, including private boards and boards they gain access to later. Choose read-only (`project:read`) or read/write (`project:read project:write`). The account's live permissions still govern each board. Access expires after 30 days. Reconnect on expiry. Users can disconnect in Settings → Connections → Connected apps, or through OAuth revocation. Public discovery, selected-board consent, refresh tokens, Changes, manufacturing and viewer extensions are later releases.

## Connection

Production origin: `https://boardrepo.com`. API resource/audience: `https://boardrepo.com/api/v1`.
Local development uses the configured BoardRepo development origin as its audience.

1. Generate a cryptographically random verifier (43–128 RFC 7636 characters) and state, and store them for this connection attempt. Compute `base64url(SHA256(verifier))` without padding.
2. Open the system browser at `/oauth/authorize` with `client_id`, `response_type=code`, your registered `redirect_uri`, `state`, `scope`, `resource`, `code_challenge`, `code_challenge_method=S256`.
3. BoardRepo handles sign-in or signup, returns to the consent request, and asks the user to approve. They can decline or narrow a write request to read-only. Do not assume a successful grant includes write access: inspect the returned `scope`.
4. Validate the callback's state, origin and path against your stored attempt. If `iss` is returned, it must name your BoardRepo origin. Handle `error=access_denied` as cancellation. Exchange the code once:

```http
POST /oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_CALLBACK&code=CODE&code_verifier=VERIFIER
```

Desktop and browser registrations are public clients: **never put a client secret in them**. Desktop callbacks are exact registered loopback URLs; pick a fixed available port and handle it being occupied. Browser callbacks and request origins are exact registered URLs. Backend registrations additionally authenticate with `client_secret` in the body or HTTP Basic client credentials. PKCE remains required. Secrets and bearer tokens never belong in URLs, logs, project source files or source control. Desktop production tools should use an OS keychain; backends should encrypt per-user credentials. Browser examples use tab-scoped storage for demonstration.

```json
{"access_token":"brp_api_…","token_type":"Bearer","scope":"project:read project:write","expires_in":2592000}
```

Codes expire in five minutes and are single-use. A failed or uncertain exchange can require restarting Connect; there is no refresh token. Successful reconnection creates another connection, which users can inspect or revoke individually or all together in Settings.

Revoke: `POST /oauth/revoke` with form-encoded `token=ACCESS_TOKEN`. Unknown or already revoked tokens return 200. Disconnect and operator app disablement block access and publication, including prepared uploads.

## HTTP reference

Browse the [Swagger UI reference](https://boardrepo.com/docs/integrations/reference) or download the [OpenAPI specification](https://boardrepo.com/docs/integrations/openapi.json) for standard API tooling. This guide covers the complete transfer flow and recovery behavior, including the coordinated
change-request protocol candidate. Deployment and partner acceptance remain separate release gates.

Send `Authorization: Bearer ACCESS_TOKEN` on API calls. Do not send BoardRepo session cookies. Partner responses, including downloaded file bytes, use `Cache-Control: no-store` so browser clients recheck access after account switches and revocation. JSON errors have a stable `reason`, a human `message`, and optional `retryable`, `retryAfterMs`, `currentHead`, `currentPolicyHash`, `code`, or
`openChangeRequest`. An open-request refusal uses `code: BLOCKED_BY_OPEN_CR`,
`openChangeRequest: { id, number, url }` and `retryable: false`. A save succeeds independently of whether previews have finished.

| Method and path under `/api/v1` | Purpose and response |
| --- | --- |
| `GET /me` | `user` plus `ownerPrincipals`: ID, name, kind, `capabilities.canCreateProject`, and `uploadPolicy.hash` for permitted create destinations. |
| `GET /projects` | `{projects:[…]}`: the user's accessible library, with `id`, `name`, `slug`, owner, `capabilities.canRead/canPublishVersion`, `headVersionId`, version number, digest and export state. This is not a public discovery endpoint. |
| `GET /projects/{id}` | The same single project envelope, with the current exact `headVersionId`. |
| `GET /projects/{id}/upload-policy` | The current policy `hash` and `version`. Use the hash in prepare and commit. The server remains the archive admission authority. |
| `GET /projects/{id}/versions/{versionId}/manifest` | Published exact-version manifest: `versionId`, `versionNumber`, `manifestDigest`, author, message, `files:[{path,blobSha,bytes}]`. Partner responses also include `previewStatus` and nullable `sourceFormat`. Files-only versions use `not_applicable` and `null`. |
| `GET /projects/{id}/blobs/{sha256}` | Exact binary contents. The hash must be referenced by this accessible project. |
| `POST /uploads` | Prepare a new-project snapshot, response described below. |
| `POST /projects` | Commit a prepared new project. |
| `POST /projects/{id}/uploads` | Prepare a complete replacement snapshot against an exact base. |
| `POST /projects/{id}/versions` | Commit that prepared replacement. |
| `GET /operations/{key}` | Integration-scoped recovery by logical idempotency key: `state=unknown/pending/failed/committed`. Committed responses include the saved result. A pending response may say `retryCommit=true`; retry the same commit intent. |

The API lists boards that the account's library exposes through BoardRepo's central permissions, including organization boards when organization access is entitled. `project:write` does not imply `project:read`. Writes also require the user's create/publish capability. Missing and inaccessible project/version/blob IDs answer 404.

For organization boards, project metadata optionally includes
`openChangeRequest: { id, number, url }` for publishers or request submitters, or
`null` when none is open. Other readers do not receive that field. The canonical URL
still requires access; metadata is a hint and publication always rechecks the gate.

### Pull

Pin a version ID before downloading anything. Fetch its manifest and every file by `blobSha`. Verify each file's byte length and SHA-256. The canonical `manifestDigest` is SHA-256 of UTF-8 JSON of `[path,blobSha]` pairs, sorted by UTF-8 path bytes, with no extra spaces. Validate paths and reject duplicate/case-colliding files before writing locally. The SDK does these checks. Downloading an exact version remains coherent while the board advances.

### Create

Prepare with JSON and `X-BoardRepo-Upload-Archive-Protocol: 2`:

```json
{
  "name":"Power module",
  "originalFilename":"boardrepo-sync.zip",
  "ownerPrincipalId":"OWNER_UUID_FROM_ME",
  "expectedBytes":12345,
  "contentHash":"SHA256_OF_EXACT_UPLOADED_ZIP",
  "policyHash":"HASH_FROM_ME_UPLOAD_POLICY",
  "idempotencyKey":"A_STABLE_LOGICAL_OPERATION_KEY",
  "message":"Initial project"
}
```

`originalFilename` is the compatibility transport label, even for native formats or a prebuilt ZIP. It does not rename files inside the archive.

Prepare returns `{uploadId,url,method:"PUT",headers,expiresAt,operationId}`. PUT the **exact ZIP bytes** to `url` with the returned headers. Include `If-None-Match` when present. **Never forward the OAuth bearer or BoardRepo cookies to storage.** Then commit at `POST /projects`, again with archive protocol 2:

```json
{"uploadId":"UPLOAD_UUID","ownerPrincipalId":"OWNER_UUID","idempotencyKey":"SAME_KEY","message":"Initial project","policyHash":"SAME_HASH"}
```

Success: `{projectId,slug,versionId,versionNumber,manifestDigest,operationId}`. Personal projects start Unlisted; organization projects start Private. The API does not publish public links or change account settings. Users can manage visibility in BoardRepo.

### Push

Both prepare and commit, including a resumed commit, require
`X-BoardRepo-Upload-Archive-Protocol: 2` and `X-BoardRepo-Change-Request-Protocol: 1`.
The latter is required even with no open request; missing or unsupported proof returns
`403 client_update_required` before archive validation or body processing. Creation,
reads, Pull and operation polling do not require change-request protocol proof.

Prepare at `POST /projects/{id}/uploads`:

```json
{"expectedBytes":12345,"contentHash":"ZIP_SHA256","policyHash":"CURRENT_POLICY_HASH","idempotencyKey":"STABLE_KEY","expectedParentVersionId":"PULLED_VERSION_UUID","message":"Updated regulator"}
```

PUT the bytes as for Create. Commit at `POST /projects/{id}/versions`:

```json
{"uploadId":"UPLOAD_UUID","idempotencyKey":"SAME_KEY","expectedParentVersionId":"SAME_BASE_UUID","message":"Updated regulator","policyHash":"SAME_POLICY_HASH"}
```

Success: `{versionId,versionNumber,manifestDigest,exportStatus,noop,operationId}`. Identical snapshots can be a no-op only when no change request blocks publication. **Push replaces the complete project snapshot. Every omitted path is removed.** To change one file, Pull first and keep all the others. The TypeScript helper's `updateSnapshot` preserves unmentioned files and accepts explicit removals. No server-side CAD merging happens.

### Resolve a Push blocked by a change request

1. Preserve local files, credentials and the saved baseline. Open the response's
   `openChangeRequest.url` in BoardRepo.
2. Have an authorized person close the request or complete its merge. An approval or
   changes-requested verdict leaves the request open and does not unblock publishing.
3. Start a fresh Push with a new logical key. If merging advanced the head, preserve
   local work and reconcile against that head before preparing the replacement snapshot.

A definitive refusal is not a retryable outage. Authenticated operation polling retains the
authoritative typed failure and reference after staged-upload cleanup. An exact commit retry
returns that failure while the upload row remains; afterward POST may return `404 not_found`.
Resolving the request does not turn the failed operation into a new Push. Already committed
operations retain their saved result even if a request opens later. A refused stage retry after
a lost stage response retires its existing live upload slot under the project lock; object
charges remain until safe cleanup.

### Native formats and safeguards

Every nonempty admitted package can be saved, including formats BoardRepo cannot preview. Files-only versions have Files, original downloads and history, settle successfully without inapplicable rendering, and remain outside Explore/search/indexing. Supported design snapshots use normal preview processing. An old preview cannot qualify a Files-only current version. Public links obey project visibility independently of discovery eligibility.

Server admission retains the existing credential scan, unsafe-path/duplicate/ZIP protections, required temporary/OS metadata omissions and quota enforcement. Raw ZIP ceiling: 5 GiB for personal boards and 250 MiB for organization boards; retained canonical files: 384 MiB; individual file: 256 MiB; retained file count: 10,000. Account capacity may be lower. Empty retained snapshots are rejected. Archives are repacked canonically; ZIP container encoding need not round-trip, but every retained original file/path/byte does. Nested ZIPs remain opaque source files. Inspect the committed manifest if admission omitted required temporary files. SDK memory limits make files-array transfers best for bounded projects; large archives can use ordinary HTTP.

### Errors, cancellation and recovery

| Response | Action |
| --- | --- |
| `401 invalid_token` | Reconnect. Do not repeatedly retry a dead credential. |
| `403 client_update_required` | Update the integration to send change-request protocol 1 on existing-project prepare/commit; retain the credential. |
| `403 insufficient_scope` | Reconnect with write permission if the user wants to publish. |
| `409 blocked_by_open_cr`, with `code: BLOCKED_BY_OPEN_CR` | Open `openChangeRequest.url`; close or merge the request, then prepare a fresh Push/key. `retryable` is false. |
| `409 head_moved`, with `currentHead` | Pull the new head and reconcile locally. Preserve the incoming files. Start a new logical operation for the reconciled snapshot. |
| `409 idempotency_mismatch` | The key was reused for different inputs. Restore the original intent or allocate a new key for a different logical change. |
| `409 in_progress` | Poll `/operations/{key}`. Honor `retryAfterMs`. |
| `409 policy_changed` | Fetch current policy and prepare a new intent/key after review. |
| `429`, `503`, or `retryable=true` | Back off. Retry the same inputs/key; retain the credential. |
| `410 upload_expired/upload_used` | Query the operation first; if it was not saved, prepare a new attempt as instructed by the response. |
| `400 invalid_content/content_mismatch/credential_detected` | Fix the archive or supplied hash/length. Do not bypass admission. |

Persist the logical key and exact commit intent before publication. A lost response is an unknown outcome: poll the operation, or replay the same commit. The server returns the saved result without creating another version. A failed open-request operation also returns optional `code`, `openChangeRequest`, `message` and
`retryable: false` with `state: failed`, `reason: blocked_by_open_cr` and `terminal: true`; current
access is rechecked before disclosing the reference. Keys are isolated per authenticated integration and user, and survive reconnection. A key is at most 255 characters and may not begin `integration:`. Preparing a different upload does not make reusing a key for different content safe.

Use `AbortSignal` to stop SDK packaging, downloads, retries and upload. Browser/Node fetch upload progress reports phase boundaries; download progress reports bytes. A user cancel is not proof that publication did not happen. Inspect the same operation after an interrupted commit. Unpublished staging is capacity-accounted and expires through existing cleanup; cancellation does not delete a board or a saved version. Python supports Ctrl-C and saves a recovery intent before commit.

For browser integrations, BoardRepo API CORS allows reviewed exact origins, bearer headers,
`X-BoardRepo-Upload-Archive-Protocol` and `X-BoardRepo-Change-Request-Protocol` with no cookie credentials. The object's upload bucket must also have that origin approved before onboarding is complete. Test OPTIONS, PUT and binary GET from your actual origin. SDK blobs download through the authorized API; storage uploads use only the presigned URL. CORS is a browser boundary, not an authorization grant.

## TypeScript helper

Install the pilot package supplied by BoardRepo: `npm install ./boardrepo-sdk-0.1.1.tgz`. It runs in browsers and Node 20+. It imports no BoardRepo application code.

```ts
import { BoardRepo, beginOAuth, finishOAuth, updateSnapshot } from '@boardrepo/sdk';

const attempt = await beginOAuth({ clientId, redirectUri, write: true });
// Save attempt for this tab/session, then navigate to attempt.authorizationUrl.
const token = await finishOAuth(savedAttempt, callbackUrl);
const api = new BoardRepo({ token: token.access_token });
const boards = await api.listBoards();
const pulled = await api.pull(boards[0].id);
const edited = updateSnapshot(pulled, [{ path: 'native/design.json', bytes: new TextEncoder().encode(updatedDesign) }]);
const saved = await api.push({ snapshot: edited, key: logicalKey, message: 'Updated layout' }, {
  signal: abortController.signal, onProgress: showProgress, onPrepared: persistCommitIntent
});
// After a lost response or restart:
const operation = await api.operation(logicalKey);
// Retry exactly the persisted intent if requested:
await api.resume(persistedCommitIntent);
```

`create({name,ownerPrincipalId,files,key,message})` accepts `{path,bytes:Uint8Array}[]` or `zip:Uint8Array` instead of files. `push` accepts an edited pulled snapshot. For a prebuilt replacement ZIP use `push({zip,projectId,baseVersionId,key,message})` through the same prepare/commit protocol. Keep the returned board/version IDs in your tool's project metadata; do not write OAuth tokens into that project.

## Runnable examples

The package includes `examples/browser/index.html`, `examples/backend.mjs`, `examples/node.mjs` and `examples/desktop.py`. The browser example ZIP also includes the bundled `sdk.mjs`; extract both files and serve them on your registered origin. Registration is required for every example.

- Browser: serve the browser directory on your registered origin. Configure the client ID and BoardRepo origin, connect, create, Pull, select file replacements and Push. The callback is the exact `index.html` URL. The page handles OAuth callback validation, stores the connection in sessionStorage, and uses actual cross-origin API and storage requests.
- Backend: set `BOARDREPO_CLIENT_ID`, `BOARDREPO_CLIENT_SECRET`, `BOARDREPO_ORIGIN`, `BOARDREPO_CALLBACK`. Run `node examples/backend.mjs`, then open `http://127.0.0.1:4313/connect`. This local demo stores connections in memory; production software should bind OAuth state to its initiating user/session and encrypt tokens.
- Node: `BOARDREPO_TOKEN=… node examples/node.mjs BOARD_UUID replacement.md README.md` shows a file-preserving Pull/edit/Push cycle. Supply the token through your secure runtime configuration.
- Desktop: `python3 examples/desktop.py --client-id YOUR_ID connect`, then `python3 examples/desktop.py list`. Pull with `python3 examples/desktop.py --baseline baseline.json pull BOARD_UUID new-folder`. Edit files in that folder, then `python3 examples/desktop.py --baseline baseline.json push new-folder --key YOUR_STABLE_KEY`. Create with `create folder --name NAME --owner OWNER_UUID --key KEY`. `operation KEY` and `resume` recover uncertain commits. Keep baseline/recovery files outside the project folder. The demo uses a mode-0600 config file; production desktop tools should use a keychain.

Ordinary HTTP works too:

```sh
curl -H "Authorization: Bearer $BOARDREPO_TOKEN" https://boardrepo.com/api/v1/me
curl -H "Authorization: Bearer $BOARDREPO_TOKEN" https://boardrepo.com/api/v1/projects
# prepare.json uses the schemas above; retain intent.json and the key for recovery.
curl -H "Authorization: Bearer $BOARDREPO_TOKEN" -H 'Content-Type: application/json' \
  -H 'X-BoardRepo-Upload-Archive-Protocol: 2' --data-binary @prepare.json \
  https://boardrepo.com/api/v1/uploads > upload.json
# PUT the exact ZIP using every returned storage header, including conditional-write headers.
# This Python standard-library example sends no BoardRepo bearer to object storage.
python3 - <<'PY'
import json, urllib.request
with open('upload.json') as response:
    upload = json.load(response)
with open('project.zip', 'rb') as archive:
    request = urllib.request.Request(upload['url'], data=archive.read(),
                                    headers=upload['headers'], method='PUT')
with urllib.request.urlopen(request) as response:
    print(response.status)
PY
curl -H "Authorization: Bearer $BOARDREPO_TOKEN" -H 'Content-Type: application/json' \
  -H 'X-BoardRepo-Upload-Archive-Protocol: 2' --data-binary @intent.json \
  https://boardrepo.com/api/v1/projects
curl -H "Authorization: Bearer $BOARDREPO_TOKEN" https://boardrepo.com/api/v1/operations/YOUR_KEY
```

## Pilot readiness

Before enabling a partner, we test new/existing-user Connect in its real environment, exact native-file round trips, preserved unrelated files, conflict handling, lost-response recovery, read-only refusal, operation isolation, revocation and disablement, browser CORS, and the unchanged KiCad/MCP contracts. An outside developer completing these journeys using these materials is the final pilot acceptance gate.

## Change requests (organization boards)

`changeWorkflow(projectId)` reads the open change request and whether a change can start.
`startChange` reserves publication against the verified current head, and `changeLifecycle`
marks the exact observed revision Ready or closes it. Persist each `operationKey` before
sending and call `recoverChangeOperation` after a lost response; a replay returns the original
receipt. Revisions are uploaded by BoardRepo Sync, which records the proposal revision its
folder incorporates; this helper does not upload change request source.
