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
1 change: 1 addition & 0 deletions listing/.env.example
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Pascal instance to read from. Defaults to https://editor.pascal.app.
# Open from Pascal uses the registered origin and root callback; no handoff secrets are needed.
VITE_PASCAL_BASE_URL=https://editor.pascal.app

# Project to show when the address has no ?project=<id>. Must be public and published.
Expand Down
53 changes: 47 additions & 6 deletions listing/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

A standalone web page that shows one published Pascal project in 3D: the baked 3D file (GLB) under
studio light, a floors control, room names and areas on hover, and doors and windows that open on
click. It reads Pascal's public scene read API and nothing else. It does not use any `@pascal-app/*`
click. It reads Pascal's published scene API, anonymously or with a short-lived viewer credential. It does not use any `@pascal-app/*`
package, so it is also the reference for building your own viewer on Pascal.

It is a template: fork it, restyle it, add UI. This file tells you (or your agent) where things are
Expand All @@ -12,7 +12,7 @@ and which rules to keep.

| Path | Owns |
| --- | --- |
| `src/pascal/` | The API client: the contract schema (`contract.ts`), `getScene` / `fetchGlb` with typed errors and signed-URL renewal (`client.ts`), and read helpers over the scene graph (`graph.ts`). No React and no three.js in here; keep it that way so it can move into an SDK unchanged. |
| `src/pascal/` | The API client: the contract schema (`contract.ts`), `getScene` / `fetchGlb` with typed errors and signed-URL renewal (`client.ts`), read helpers (`graph.ts`), and browser access resolution and PKCE (`access.ts`, `handoff.ts`). No React and no three.js in here; keep it that way so it can move into an SDK unchanged. |
| `src/useListing.ts` | Loading flow: read the scene, then download the best 3D file, poll while it is being prepared. |
| `src/App.tsx`, `src/styles.css` | Screens (loading, errors, no 3D file, WebGL unavailable) and the overlay UI. |
| `src/viewer/Viewer.tsx` | The canvas: environment light, key light and shadow, camera framing, orbit controls. |
Expand Down Expand Up @@ -107,7 +107,48 @@ Pascal account. `npm run fixture` regenerates `tests/fixtures/` (needs KTX-Softw
`TOKTX=/path/to/toktx`); the fixture is a small two-floor house with a KTX2 texture, a door clip and
meshopt compression, like a real bake.

## Private projects
## Open from Pascal

Register this viewer in Pascal settings with its entry URL, exact origins, and the callback
`<origin>/` (for example `https://viewer.example/` or `http://localhost:5173/`). The callback is
the same root page served by Vite in development and by the static production build; no extra
route or SPA rewrite is needed. Register each development port explicitly. Production origins
must use HTTPS and be verified: request the origin challenge in Pascal settings, serve it as
plain text at `/.well-known/pascal-viewer-verification`, then verify the origin in settings.
Pascal does not fetch localhost for verification. Bind the published project to this viewer,
then open it from Pascal or create a share link pinned to this viewer.

The helper resolves `GET /api/viewers/resolve?origin=<location.origin>` once per page to discover
the viewer ID and exact callback. No viewer ID or per-project deployment configuration is needed.
Pascal supplies `project`, `viewer`, and `access=session|share|anonymous` in its entry URL.
The helper captures and immediately scrubs callback `code`, `state`, and `iss` before React
renders, validates the saved transaction (including its ten-minute maximum age), then exchanges
the code using S256 PKCE and `credentials: 'omit'`. No Pascal cookies are sent by API reads.

Access resolves in order: callback, matching unexpired tab credential, private entry authorization,
then anonymous published read. Direct links without private entry context can read public projects.
If descriptor discovery is unavailable, only public projects work. An invalid callback or a
rejected credential stops loading and shows “Reopen from Pascal” or “Reopen your share link”;
it never silently retries anonymously. Share readers should reopen their original Pascal share
link; the helper never stores or reconstructs that durable link.

Credentials are isolated by Pascal issuer, viewer, project, and browser origin in `sessionStorage`.
Never store tokens in `localStorage`, query parameters, build variables, or deployment secrets.
Transactions and PKCE verifiers also live only in the current tab's `sessionStorage`. Preserve
only validated local return paths across the round trip. Keep callback bootstrap ahead of any
third-party scripts or analytics you add, and exclude callback queries and credentials from logs.

Within two minutes of expiry, the helper renews using a fresh top-level authorization round trip
with the original session/share mode. An expired credential rejected with 401 can also renew.
There is one renewal attempt with a loop guard; failed or immediately expiring renewals require
reopening from Pascal. There is no refresh token or hidden iframe. A successful read with a
fresh credential permits a later renewal cycle. Signed storage URL renewal remains separate:
storage downloads omit cookies and never receive the Pascal bearer credential.

`VITE_PASCAL_TOKEN_URL`, when set, takes precedence and skips the handoff and registry lookup.
This remains an alternative for company login flows described below.

## Private projects with your own login

The read works without a credential for public projects. For a private project, your
server mints a short-lived viewer token from its Pascal API key and your viewer sends it
Expand Down Expand Up @@ -156,9 +197,9 @@ Cloudflare Pages).

## Rules

- Never put a Pascal API key, session or any other secret in the browser. `VITE_*` variables and
everything in `src/` ship to every visitor. This template reads public, published projects
anonymously; showing private projects needs a server you control that holds the credential.
- Never put a Pascal API key or account session in the browser bundle. `VITE_*` variables and
everything in `src/` ship to every visitor. Public projects read anonymously; private projects
use the registered Pascal handoff or your own server's short-lived token endpoint.
- Do not import `@pascal-app/*`. The template must stay installable from this folder alone.
- Keep `src/pascal/` free of React and three.js.
- Keep the CSP in `vite.config.ts` in step with what the page loads. The decoders need
Expand Down
4 changes: 3 additions & 1 deletion listing/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ npm run dev
# open http://localhost:5173/?project=<project id>
```

The project must be public and published. Set `VITE_PASCAL_BASE_URL` to read from another Pascal
The project must be published; direct anonymous links require it to be public. Set `VITE_PASCAL_BASE_URL` to read from another Pascal
instance (see `.env.example`).

| Script | Does |
Expand All @@ -29,4 +29,6 @@ customisation and the rules to keep (start with: never put a Pascal API key in t

MIT licensed, like the rest of this repository.

Open from Pascal: register and verify your viewer origin with the root callback (`<origin>/`) to open private projects and share links without deployment secrets; see [AGENTS.md](AGENTS.md#open-from-pascal).

Private projects: run `examples/token-server.mjs` with your API key on your server and set `VITE_PASCAL_TOKEN_URL`. See AGENTS.md.
27 changes: 24 additions & 3 deletions listing/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
useMemo,
useState,
} from 'react'
import { PASCAL_BASE_URL, projectIdFromLocation } from './config'
import { PASCAL_BASE_URL, PASCAL_TOKEN_URL, projectIdFromLocation } from './config'
import { hasHandoffCallback } from './pascal/handoff'
import { listLevels, type PascalError, type SceneResponse } from './pascal'
import { type ListingState, useListing } from './useListing'
import type { ModelInfo } from './viewer/Model'
Expand All @@ -24,7 +25,7 @@ export function App() {
const projectId = useMemo(() => projectIdFromLocation(), [])
const webgl = useMemo(() => hasWebGL2(), [])

if (!projectId) {
if (!projectId && !(hasHandoffCallback() && !PASCAL_TOKEN_URL)) {
return (
<Status title="No project selected" state="missing-project">
Add <code>?project=&lt;id&gt;</code> to the address, or set{' '}
Expand All @@ -39,7 +40,7 @@ export function App() {
</Status>
)
}
return <Listing projectId={projectId} />
return <Listing projectId={projectId || ''} />
}

function Listing({ projectId }: { projectId: string }) {
Expand All @@ -49,6 +50,26 @@ function Listing({ projectId }: { projectId: string }) {
}, [])

if (state.kind === 'loading') return <Status title="Loading project…" state="loading" />
if (state.kind === 'opening') return <Status title="Opening from Pascal…" state="opening" />
if (state.kind === 'reopen') {
const projectUrl = new URL(
projectId ? `/editor/${encodeURIComponent(projectId)}` : '/projects',
PASCAL_BASE_URL,
).href
return (
<Status
title={state.access === 'share' ? 'Reopen your share link' : 'Reopen from Pascal'}
state="reopen"
>
{state.access === 'share'
? 'Open the original Pascal share link again to restore access.'
: 'Open this project from Pascal again to restore access.'}
<a className="button" href={projectUrl}>
Open project in Pascal
</a>
</Status>
)
}
if (state.kind === 'error') return <ErrorStatus error={state.error} onRetry={reload} />
if (state.kind === 'no-file') return <NoFileStatus scene={state.scene} onRetry={reload} />
return <Scene state={state} onRetry={reload} />
Expand Down
7 changes: 5 additions & 2 deletions listing/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { callbackProject } from './pascal/handoff'

/** Where the viewer reads from. Both are public values; no secret belongs here. */
export const PASCAL_BASE_URL = (
import.meta.env.VITE_PASCAL_BASE_URL || 'https://editor.pascal.app'
).replace(/\/+$/, '')

/**
* Optional: your own endpoint that returns `{ token }` for `?project=<id>` after your
* own login check. Set it to show private projects; leave it empty for public ones.
* own login check. When set, this takes precedence over the Pascal handoff.
*/
export const PASCAL_TOKEN_URL = import.meta.env.VITE_PASCAL_TOKEN_URL?.trim() || null

Expand All @@ -24,5 +26,6 @@ export async function fetchViewerToken(projectId: string, signal: AbortSignal):
/** `?project=<id>` wins, so one deployment can show any public project. */
export function projectIdFromLocation(search = window.location.search): string | null {
const fromQuery = new URLSearchParams(search).get('project')?.trim()
return fromQuery || import.meta.env.VITE_PASCAL_PROJECT_ID?.trim() || null
return fromQuery || (!PASCAL_TOKEN_URL && callbackProject(new URL(PASCAL_BASE_URL).origin)) ||
import.meta.env.VITE_PASCAL_PROJECT_ID?.trim() || null
}
3 changes: 3 additions & 0 deletions listing/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { App } from './App'
import { captureHandoffCallback } from './pascal/handoff'
import './styles.css'

captureHandoffCallback()

createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
Expand Down
126 changes: 126 additions & 0 deletions listing/src/pascal/access.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import {
type AccessMode, type Descriptor, type StoredCredential, ReopenRequired,
detectEntry, exchangeCallback, hasHandoffCallback,
readCredential, rejectedAccess, rememberRejection, startAuthorize, storeCredential,
} from './handoff'

export { ReopenRequired } from './handoff'
export type Access = { kind: 'anonymous' } | { kind: 'opening' } |
{ kind: 'credential'; credential: StoredCredential }

const descriptors = new Map<string, Promise<Descriptor | null>>()
const resolutions = new Map<string, Promise<Access>>()
let callbackResult: Promise<StoredCredential> | undefined
let callbackCompleted = false
const rejected = new Map<string, AccessMode>()
const RENEW_MARGIN = 120_000

/** One public registry lookup per issuer/page; an unavailable registry supports public reads only. */
function resolveDescriptor(issuer: string): Promise<Descriptor | null> {
if (!descriptors.has(issuer)) descriptors.set(issuer, (async () => {
try {
const url = new URL('/api/viewers/resolve', issuer)
url.searchParams.set('origin', location.origin)
const response = await fetch(url, { credentials: 'omit' })
const body = await response.json() as Descriptor & { availability?: string }
// This template deliberately registers the root page as its exact callback.
return response.ok && body.availability === 'available' && typeof body.viewer_id === 'string' &&
body.viewer_id && body.redirect_uri === location.origin + '/' ? body : null
} catch { return null }
})())
return descriptors.get(issuer)!
}

/**
* Whether Pascal sent this visitor or this tab already holds handoff state for the
* project. Plain public visits skip the registry lookup entirely.
*/
function handoffInvolved(issuer: string, projectId: string): boolean {
if (hasHandoffCallback() || detectEntry()) return true
try {
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i) ?? ''
if (
(key.startsWith('pascal:credential:') || key.startsWith('pascal:reopen:')) &&
key.includes(JSON.stringify(issuer)) &&
key.includes(JSON.stringify(projectId))
)
return true
}
} catch {
// Storage denied: nothing stored to resume.
}
return false
}

async function renew(credential: StoredCredential, descriptor: Descriptor | null): Promise<Access> {
rememberRejection(credential)
rejected.set(JSON.stringify([credential.issuer, credential.project_id]), credential.access)
if (!descriptor || credential.renewalAttempted) throw new ReopenRequired(credential.access)
await startAuthorize(credential.issuer, descriptor, credential.project_id, credential.access, true)
return { kind: 'opening' }
}

/** Company-token callers bypass this helper entirely. Concurrent callers share a single exchange/navigation. */
export function resolveAccess(projectId: string, baseUrl = 'https://editor.pascal.app'): Promise<Access> {
const issuer = new URL(baseUrl).origin
const key = JSON.stringify([issuer, projectId])
if (!resolutions.has(key)) {
const resolution = (async (): Promise<Access> => {
if (!handoffInvolved(issuer, projectId) && !rejected.has(key)) return { kind: 'anonymous' }
const descriptor = await resolveDescriptor(issuer)
if (rejected.has(key)) throw new ReopenRequired(rejected.get(key))
if (hasHandoffCallback() && !callbackCompleted) {
callbackResult ??= exchangeCallback(issuer, projectId, descriptor)
const credential = await callbackResult
callbackCompleted = true
if (Date.parse(credential.expires_at) - Date.now() <= RENEW_MARGIN) return renew(credential, descriptor)
return { kind: 'credential', credential }
}
const entry = detectEntry()
const mode = entry?.access === 'share' ? 'share' : 'session'
if (entry && (entry.project !== projectId || (descriptor && entry.viewer !== descriptor.viewer_id))) {
throw new ReopenRequired(mode)
}
if (descriptor) {
const credential = readCredential(issuer, descriptor.viewer_id, projectId)
if (credential) {
if (Date.parse(credential.expires_at) - Date.now() <= RENEW_MARGIN) return renew(credential, descriptor)
return { kind: 'credential', credential }
}
const refusal = rejectedAccess(issuer, descriptor.viewer_id, projectId)
if (refusal && (!entry || entry.access === 'anonymous')) throw new ReopenRequired(refusal)
}
if (entry && entry.access !== 'anonymous') {
if (!descriptor) throw new ReopenRequired(mode)
await startAuthorize(issuer, descriptor, projectId, entry.access)
return { kind: 'opening' }
}
return { kind: 'anonymous' }
})()
resolutions.set(key, resolution)
void resolution.finally(() => resolutions.delete(key)).catch(() => {})
}
return resolutions.get(key)!
}

/** Handle scene-read rejection, including signed-URL renewal reads, without anonymous fallback. */
export async function rejectCredential(credential: StoredCredential, status: number): Promise<Access> {
rememberRejection(credential)
rejected.set(JSON.stringify([credential.issuer, credential.project_id]), credential.access)
if (status === 401 && Date.parse(credential.expires_at) <= Date.now()) {
return renew(credential, await resolveDescriptor(credential.issuer))
}
throw new ReopenRequired(credential.access)
}

export function credentialReadSucceeded(credential: StoredCredential): void {
if (credential.renewalAttempted && Date.parse(credential.expires_at) - Date.now() > RENEW_MARGIN) {
credential.renewalAttempted = false
storeCredential(credential)
}
}

export function renewalDelay(credential: StoredCredential): number {
return Math.max(0, Date.parse(credential.expires_at) - Date.now() - RENEW_MARGIN)
}
8 changes: 4 additions & 4 deletions listing/src/pascal/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ export type RequestOptions = {
/** Inject a fetch, e.g. a server-side one that adds credentials. Defaults to the global fetch. */
fetch?: typeof fetch
/**
* A short-lived viewer token for a private project, minted by your own server from
* its Pascal API key (see examples/token-server.mjs). Never an API key.
* A short-lived viewer credential from the Pascal handoff or your own token
* endpoint (see examples/token-server.mjs). Never an API key or account session.
*/
token?: string
}
Expand Down Expand Up @@ -80,8 +80,8 @@ export async function getScene(
throw new PascalError('not_published', 'This project is not published', 404)
}
if (response.status === 404) throw new PascalError('not_found', 'Project not found', 404)
if (response.status === 401) {
throw new PascalError('unauthorized', 'The credential was rejected', 401)
if (response.status === 401 || response.status === 403) {
throw new PascalError('unauthorized', 'The credential was rejected', response.status)
}
throw new PascalError('http', `Pascal answered ${response.status}`, response.status)
}
Expand Down
Loading
Loading