@pontive/server 1.29.3 → 1.29.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{client-CBDgYajX.cjs → client-BOivaOZe.cjs} +2 -2
- package/dist/{client-CBDgYajX.cjs.map → client-BOivaOZe.cjs.map} +1 -1
- package/dist/{client-CD2MtKpz.js → client-gWGqYFNx.js} +3 -3
- package/dist/{client-CD2MtKpz.js.map → client-gWGqYFNx.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/keyless.cjs.map +1 -1
- package/dist/keyless.d.cts +1 -1
- package/dist/keyless.d.ts +1 -1
- package/dist/keyless.js.map +1 -1
- package/dist/management/client.d.cts +2 -2
- package/dist/management/client.d.ts +2 -2
- package/dist/management.cjs +1 -1
- package/dist/management.js +1 -1
- package/dist/platform/client.d.cts +1 -1
- package/dist/platform/client.d.ts +1 -1
- package/package.json +1 -1
package/dist/keyless.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyless.cjs","sources":["../src/keyless.ts"],"sourcesContent":["/**\n * Keyless mode's building blocks (pontive-spec 47 §5.1, §6.2, §7.2): creating\n * an unclaimed development instance with no Pontive account, keeping what the\n * app needs on the developer's machine, and minting claim links.\n *\n * `createServerAuth` uses them when it runs in development with no issuer, and\n * the `pontive` CLI imports them from `@pontive/server/keyless`, so the\n * dev server and the CLI write the same files the same way:\n *\n * - `.env.local`: the §6.1 variables, **appended**; a `PONTIVE_*` line already\n * there is never overwritten.\n * - `.pontive/keyless.json`: `{ instance_id, issuer, app_id, claim_token,\n * expires_at, region }`, the claim token being the instance's ownership.\n * - `.pontive/keyless.lock`: held while provisioning, so two dev workers never\n * create two instances.\n * - `.gitignore`: lists `.env.local` and `.pontive/`.\n *\n * Secrets are never logged: the console message names the instance, its region\n * and its deletion date, nothing else.\n *\n * The Node built-ins are reached through `process.getBuiltinModule` (Node\n * 20.16+, 22.3+), not imported: this module is part of the server entry, which\n * edge runtimes load too, and there it must load without a file system.\n */\n\n/** Where the provisioning routes live when `PONTIVE_API_URL` does not say. */\nexport const DEFAULT_API_URL = \"https://api.pontive.com\";\n/** The directory keyless mode keeps its files in, under the project root. */\nexport const KEYLESS_DIR = \".pontive\";\n/** The instance's record, under the project root. */\nexport const KEYLESS_FILE = \".pontive/keyless.json\";\n/** The provisioning lock, under the project root. */\nexport const KEYLESS_LOCK = \".pontive/keyless.lock\";\n/** The env file keyless mode appends to, under the project root. */\nexport const ENV_FILE = \".env.local\";\n/** What `.gitignore` must list. */\nexport const GITIGNORE_ENTRIES = [\".env.local\", \".pontive/\"] as const;\n/** The docs page on unclaimed instances. */\nexport const UNCLAIMED_DOCS_URL = \"https://www.pontive.com/docs/unclaimed-instances\";\n\n// ---------------------------------------------------------------------------\n// The API (platform-management-api, spec 47 §5.1, §7.2)\n// ---------------------------------------------------------------------------\n\n/** `POST /v1/unclaimed-instances`'s body. Every field is optional. */\nexport interface CreateUnclaimedInstanceRequest {\n name?: string;\n /** `us`, `eu`, `au`; default: the region nearest the caller. */\n region?: string;\n tenancy_mode?: \"b2c\" | \"b2b\";\n app?: {\n type?: \"web\" | \"spa\" | \"native\";\n /** Loopback only. Without a port, any port matches on a non-production instance. */\n redirect_uris?: string[];\n };\n /** A public JWK (`EC` P-256 or `OKP` X25519): the secrets come back as a JWE in `encrypted_secrets`. */\n encryption_key?: Record<string, unknown>;\n /** The tool, its version and, when detected, the agent: metrics and abuse signals only. */\n client?: { name: string; version: string; agent?: string };\n}\n\n/** `POST /v1/unclaimed-instances`'s `201`. */\nexport interface UnclaimedInstance {\n object: \"unclaimed_instance\";\n instance_id: string;\n project_id: string;\n name: string;\n region: string;\n environment: string;\n tenancy_mode: string;\n issuer: string;\n app_id: string;\n /** A `web` app's client secret; absent with `encryption_key`. */\n client_secret?: string;\n /** The `keyless` developer secret key; absent with `encryption_key`. */\n secret_key?: string;\n secret_key_id: string;\n /** Returned once; absent with `encryption_key`. */\n claim_token?: string;\n /** With `encryption_key`: a compact JWE of `{ client_secret, secret_key, claim_token }`. */\n encrypted_secrets?: string;\n expires_at: string;\n limits_url?: string;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token. */\nexport interface UnclaimedInstanceStatus {\n object: \"unclaimed_instance\";\n instance_id: string;\n status: \"unclaimed\" | \"claimed\";\n claimed_at: string | null;\n expires_at?: string;\n [field: string]: unknown;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`'s `201`. */\nexport interface ClaimLink {\n object: \"claim_link\";\n /** `https://app.pontive.com/claim/{instance_id}#code=…`: single use, one hour. */\n url: string;\n expires_at: string;\n}\n\n/** A refusal from the Pontive API, in its standard envelope. */\nexport class PontiveApiError extends Error {\n readonly status: number;\n /** The envelope's `code` (`unclaimed_instance_limit`, `instance_claimed` …), when it had one. */\n readonly code: string | undefined;\n /** Seconds, from `Retry-After`, when the API sent one. */\n readonly retryAfter: number | undefined;\n\n constructor(status: number, code: string | undefined, message: string, retryAfter?: number) {\n super(message);\n this.name = \"PontiveApiError\";\n this.status = status;\n this.code = code;\n this.retryAfter = retryAfter;\n }\n}\n\nexport interface ApiOptions {\n /** Default `PONTIVE_API_URL`, else `https://api.pontive.com`. */\n apiUrl?: string;\n /** Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\nfunction apiBase(options: ApiOptions): string {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n return (options.apiUrl || env?.PONTIVE_API_URL?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n}\n\nasync function apiError(response: Response): Promise<PontiveApiError> {\n let code: string | undefined;\n let message = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { code?: unknown; message?: unknown }; code?: unknown; message?: unknown };\n const envelope = body?.error ?? body;\n if (typeof envelope?.code === \"string\") code = envelope.code;\n if (typeof envelope?.message === \"string\") message = envelope.message;\n } catch {\n // Not JSON: the status says enough.\n }\n const retry = Number(response.headers.get(\"retry-after\"));\n return new PontiveApiError(response.status, code, message, Number.isFinite(retry) && retry > 0 ? retry : undefined);\n}\n\n/** A status worth one retry with the same idempotency key: the request may not have reached the API. */\nconst retryable = (status: number) => status === 500 || status === 502 || status === 504;\n\n/**\n * `POST /v1/unclaimed-instances` (unauthenticated). Sends `X-Idempotency-Key`\n * (generated when not given) and retries once, with the same key, on a\n * network failure or a 500, 502 or 504: a retry within 24 hours returns the\n * same instance and counts once against the caller's limit.\n */\nexport async function createUnclaimedInstance(\n body: CreateUnclaimedInstanceRequest,\n options: ApiOptions & { idempotencyKey?: string } = {},\n): Promise<UnclaimedInstance> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const key = options.idempotencyKey ?? crypto.randomUUID();\n const send = () =>\n fetchImpl(`${apiBase(options)}/v1/unclaimed-instances`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"x-idempotency-key\": key },\n body: JSON.stringify(body),\n });\n\n let response: Response;\n try {\n response = await send();\n if (retryable(response.status)) response = await send();\n } catch {\n response = await send();\n }\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as UnclaimedInstance;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`, with the claim token in `X-Pontive-Claim-Token`. */\nexport async function createClaimLink(instanceId: string, claimToken: string, options: ApiOptions = {}): Promise<ClaimLink> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}/claim-links`, {\n method: \"POST\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as ClaimLink;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token: its status, for polling. */\nexport async function getUnclaimedInstance(\n instanceId: string,\n claimToken: string,\n options: ApiOptions = {},\n): Promise<UnclaimedInstanceStatus> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}`, {\n method: \"GET\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (!response.ok) throw await apiError(response);\n return (await response.json()) as UnclaimedInstanceStatus;\n}\n\n// ---------------------------------------------------------------------------\n// The files\n// ---------------------------------------------------------------------------\n\n/** `.pontive/keyless.json`. `claim_token` is gone once the instance is claimed (`pontive claim` removes it). */\nexport interface KeylessRecord {\n instance_id: string;\n issuer: string;\n app_id: string;\n claim_token?: string;\n expires_at: string;\n region: string;\n}\n\n/** Keyless mode needs a file system: thrown in a runtime without one (an edge runtime). */\nexport class KeylessUnavailableError extends Error {\n constructor(message = \"keyless mode needs Node.js 20.16 or later (process.getBuiltinModule); this runtime has no file system\") {\n super(`@pontive/server: ${message}`);\n this.name = \"KeylessUnavailableError\";\n }\n}\n\n/** The unclaimed instance this project uses has expired (Pontive deleted it) or was claimed away. */\nexport class KeylessInstanceGoneError extends Error {\n readonly record: KeylessRecord;\n\n constructor(record: KeylessRecord, message: string) {\n super(message);\n this.name = \"KeylessInstanceGoneError\";\n this.record = record;\n }\n}\n\ntype Fs = typeof import(\"node:fs/promises\");\ntype Path = typeof import(\"node:path\");\n\ninterface NodeApis {\n fs: Fs;\n path: Path;\n}\n\n/** `fs/promises` and `path`, or KeylessUnavailableError. */\nexport function nodeApis(): NodeApis {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n if (typeof proc?.getBuiltinModule !== \"function\") throw new KeylessUnavailableError();\n const fs = proc.getBuiltinModule(\"node:fs/promises\") as Fs | undefined;\n const path = proc.getBuiltinModule(\"node:path\") as Path | undefined;\n if (!fs || !path) throw new KeylessUnavailableError();\n return { fs, path };\n}\n\nconst isMissing = (err: unknown) => (err as { code?: string } | null)?.code === \"ENOENT\";\n\n/** The project's `.pontive/keyless.json`, or null when there is none. Throws on a file that is not a record. */\nexport async function readKeylessRecord(dir: string): Promise<KeylessRecord | null> {\n const { fs, path } = nodeApis();\n let text: string;\n try {\n text = await fs.readFile(path.join(dir, KEYLESS_FILE), \"utf8\");\n } catch (err) {\n if (isMissing(err)) return null;\n throw err;\n }\n const record = JSON.parse(text) as Partial<KeylessRecord>;\n for (const field of [\"instance_id\", \"issuer\", \"app_id\", \"expires_at\"] as const) {\n if (typeof record[field] !== \"string\" || !record[field]) {\n throw new Error(`@pontive/server: ${KEYLESS_FILE} has no ${field}; run \\`npx pontive init --reset\\``);\n }\n }\n return record as KeylessRecord;\n}\n\n/** Writes `.pontive/keyless.json` (owner-only: it holds the claim token). */\nexport async function writeKeylessRecord(dir: string, record: KeylessRecord): Promise<void> {\n const { fs, path } = nodeApis();\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const file = path.join(dir, KEYLESS_FILE);\n const record_: KeylessRecord = {\n instance_id: record.instance_id,\n issuer: record.issuer,\n app_id: record.app_id,\n ...(record.claim_token ? { claim_token: record.claim_token } : {}),\n expires_at: record.expires_at,\n region: record.region,\n };\n await fs.writeFile(file, `${JSON.stringify(record_, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await fs.chmod(file, 0o600).catch(() => {});\n}\n\n/** Whether the record's instance is past its deletion date. */\nexport function keylessExpired(record: KeylessRecord, now = Date.now()): boolean {\n const at = Date.parse(record.expires_at);\n return Number.isNaN(at) || at <= now;\n}\n\n/** The `KEY=value` lines of an env file (`export `, quotes and comments handled), or an empty map. */\nexport function parseEnvFile(text: string): Map<string, string> {\n const vars = new Map<string, string>();\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const m = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/.exec(line);\n if (!m) continue;\n let value = m[2]!;\n const quote = value[0];\n const close = quote === '\"' || quote === \"'\" ? value.indexOf(quote, 1) : -1;\n if (close > 0) value = value.slice(1, close);\n else value = value.replace(/\\s+#.*$/, \"\");\n vars.set(m[1]!, value);\n }\n return vars;\n}\n\n/** The project's `.env.local`, parsed; empty when there is none. */\nexport async function readEnvLocal(dir: string): Promise<Map<string, string>> {\n const { fs, path } = nodeApis();\n try {\n return parseEnvFile(await fs.readFile(path.join(dir, ENV_FILE), \"utf8\"));\n } catch (err) {\n if (isMissing(err)) return new Map();\n throw err;\n }\n}\n\n/**\n * Appends variables to `.env.local`, creating it when missing. A variable the\n * file already sets is never overwritten: it is reported in `skipped`.\n */\nexport async function appendEnvLocal(\n dir: string,\n vars: Readonly<Record<string, string | undefined>>,\n options: { comment?: string } = {},\n): Promise<{ written: string[]; skipped: string[] }> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, ENV_FILE);\n let existing = \"\";\n try {\n existing = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const present = parseEnvFile(existing);\n const written: string[] = [];\n const skipped: string[] = [];\n const lines: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (value === undefined) continue;\n if (present.has(key)) {\n skipped.push(key);\n continue;\n }\n lines.push(`${key}=${value}`);\n written.push(key);\n }\n if (lines.length > 0) {\n const lead = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n const sep = existing.trim() ? \"\\n\" : \"\";\n const comment = options.comment ? `# ${options.comment}\\n` : \"\";\n await fs.appendFile(file, `${lead}${sep}${comment}${lines.join(\"\\n\")}\\n`, { encoding: \"utf8\", mode: 0o600 });\n }\n return { written, skipped };\n}\n\n/** Whether a `.gitignore` line already keeps `entry` out (the exact entry, or a common equivalent). */\nfunction ignores(lines: string[], entry: string): boolean {\n const bare = entry.replace(/\\/$/, \"\");\n const forms =\n entry === \".env.local\"\n ? [\".env.local\", \"/.env.local\", \".env*.local\", \"/.env*.local\", \".env*\", \"/.env*\", \"*.local\"]\n : [bare, `/${bare}`, `${bare}/`, `/${bare}/`, `${bare}/*`, `/${bare}/*`];\n return lines.some(line => forms.includes(line.trim()));\n}\n\n/** Makes sure `.gitignore` lists `.env.local` and `.pontive/`, creating it when missing. Returns what it added. */\nexport async function ensureGitignore(dir: string, entries: readonly string[] = GITIGNORE_ENTRIES): Promise<string[]> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, \".gitignore\");\n let text = \"\";\n try {\n text = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const lines = text.split(/\\r?\\n/);\n const missing = entries.filter(entry => !ignores(lines, entry));\n if (missing.length > 0) {\n const lead = text && !text.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await fs.appendFile(file, `${lead}${text.trim() ? \"\\n\" : \"\"}# Pontive keyless mode: secrets and the claim token\\n${missing.join(\"\\n\")}\\n`, \"utf8\");\n }\n return missing;\n}\n\n/** 32 random bytes, base64url: a `PONTIVE_SESSION_SECRET` (43 characters), generated locally, never by Pontive. */\nexport function generateSessionSecret(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(32));\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nexport interface LockOptions {\n /** Give up waiting for another holder after this long. Default 60 s. */\n timeoutMs?: number;\n /** A lock older than this is a crashed holder's, and is taken over. Default 2 minutes. */\n staleMs?: number;\n /** How often to look again while another process holds it. Default 200 ms. */\n pollMs?: number;\n}\n\n/**\n * Runs `fn` holding `.pontive/keyless.lock`, created exclusively (`wx`), so\n * two processes (two dev workers, the dev server and the CLI) never provision\n * at once. A waiter re-reads `keyless.json` inside `fn` and finds the other's\n * instance. A lock left by a crashed process is taken over after `staleMs`.\n */\nexport async function withKeylessLock<T>(dir: string, fn: () => Promise<T>, options: LockOptions = {}): Promise<T> {\n const { fs, path } = nodeApis();\n const timeoutMs = options.timeoutMs ?? 60_000;\n const staleMs = options.staleMs ?? 120_000;\n const pollMs = options.pollMs ?? 200;\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const lock = path.join(dir, KEYLESS_LOCK);\n const started = Date.now();\n\n for (;;) {\n try {\n const handle = await fs.open(lock, \"wx\");\n try {\n const pid = (globalThis as { process?: { pid?: number } }).process?.pid;\n await handle.writeFile(JSON.stringify({ pid, created_at: new Date().toISOString() }));\n } finally {\n await handle.close();\n }\n break;\n } catch (err) {\n if ((err as { code?: string }).code !== \"EEXIST\") throw err;\n const stat = await fs.stat(lock).catch(() => null);\n if (stat && Date.now() - stat.mtimeMs > staleMs) {\n await fs.rm(lock, { force: true });\n continue;\n }\n if (Date.now() - started > timeoutMs) {\n throw new Error(`@pontive/server: ${KEYLESS_LOCK} is held by another process; remove it if nothing is provisioning`);\n }\n await sleep(pollMs);\n }\n }\n\n try {\n return await fn();\n } finally {\n await fs.rm(lock, { force: true }).catch(() => {});\n }\n}\n\n// ---------------------------------------------------------------------------\n// Provisioning, end to end\n// ---------------------------------------------------------------------------\n\n/** The §6.1 variables for a provisioned instance (only those it has). */\nexport function envVarsFor(instance: UnclaimedInstance, sessionSecret: string): Record<string, string | undefined> {\n return {\n PONTIVE_ISSUER: instance.issuer,\n PONTIVE_CLIENT_ID: instance.app_id,\n PONTIVE_CLIENT_SECRET: instance.client_secret,\n PONTIVE_SESSION_SECRET: sessionSecret,\n PONTIVE_SECRET_KEY: instance.secret_key,\n PONTIVE_INSTANCE_ID: instance.instance_id,\n };\n}\n\n/** The default redirect URIs for a dev server's callback route: port-less loopback, which matches any port (decision E5). */\nexport function loopbackCallbacks(basePath = \"/api/auth\"): string[] {\n const route = `${basePath.replace(/\\/+$/, \"\")}/callback`;\n return [`http://localhost${route}`, `http://127.0.0.1${route}`];\n}\n\nexport interface ProvisionOptions extends ApiOptions {\n /** The project root. */\n dir: string;\n /** Sent as `app.redirect_uris` (loopback only). */\n redirectUris: string[];\n /** Sent as `client`. */\n client: { name: string; version: string; agent?: string };\n /** Default `PONTIVE_REGION`, else the API picks the region nearest the caller. */\n region?: string;\n /** The project's name. */\n name?: string;\n app?: CreateUnclaimedInstanceRequest[\"app\"];\n tenancyMode?: \"b2c\" | \"b2b\";\n lock?: LockOptions;\n}\n\nexport interface KeylessInstance {\n record: KeylessRecord;\n /** The §6.1 values: what was just written, or what `.env.local` and the environment hold for a reused instance. */\n env: Record<string, string | undefined>;\n /** Created by this call (false: an existing `keyless.json` was reused). */\n created: boolean;\n}\n\nasync function reuse(dir: string, record: KeylessRecord): Promise<KeylessInstance> {\n const local = await readEnvLocal(dir);\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const pick = (key: string) => env[key]?.trim() || local.get(key) || undefined;\n return {\n record,\n created: false,\n env: {\n PONTIVE_ISSUER: record.issuer,\n PONTIVE_CLIENT_ID: record.app_id,\n PONTIVE_CLIENT_SECRET: pick(\"PONTIVE_CLIENT_SECRET\"),\n PONTIVE_SESSION_SECRET: pick(\"PONTIVE_SESSION_SECRET\"),\n PONTIVE_SECRET_KEY: pick(\"PONTIVE_SECRET_KEY\"),\n PONTIVE_INSTANCE_ID: record.instance_id,\n },\n };\n}\n\n/** The message for an instance that is no longer there, and what to do. */\nexport function goneMessage(record: KeylessRecord, why: \"expired\" | \"refused\"): string {\n const what =\n why === \"expired\"\n ? `expired on ${record.expires_at} and Pontive deleted it, with its users`\n : \"refused its credentials (401): it expired, or was claimed and its keys rotated\";\n return (\n `@pontive/server: the unclaimed Pontive instance in ${KEYLESS_FILE} (${record.instance_id}) ${what}. ` +\n \"Pontive does not create a new one over it, since the new one would have none of its users. \" +\n \"Run `npx pontive init --reset` to create another, or set PONTIVE_ISSUER for an instance of your own.\"\n );\n}\n\n/**\n * The project's unclaimed instance: `keyless.json`'s when it is there and not\n * expired; otherwise created now, under the lock, and written to `.env.local`\n * (appended), `keyless.json` and `.gitignore`.\n *\n * An expired `keyless.json` throws `KeylessInstanceGoneError`: never a second\n * instance silently over the first. Pass `reset: true` (`pontive init\n * --reset`) to replace it.\n */\nexport async function ensureKeylessInstance(options: ProvisionOptions & { reset?: boolean }): Promise<KeylessInstance> {\n const existing = options.reset ? null : await readKeylessRecord(options.dir);\n if (existing) {\n if (keylessExpired(existing)) throw new KeylessInstanceGoneError(existing, goneMessage(existing, \"expired\"));\n return reuse(options.dir, existing);\n }\n\n return withKeylessLock(\n options.dir,\n async () => {\n // Another process may have provisioned while this one waited.\n const now = options.reset ? null : await readKeylessRecord(options.dir);\n if (now) {\n if (keylessExpired(now)) throw new KeylessInstanceGoneError(now, goneMessage(now, \"expired\"));\n return reuse(options.dir, now);\n }\n\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const region = options.region || env.PONTIVE_REGION?.trim() || undefined;\n const instance = await createUnclaimedInstance(\n {\n ...(options.name ? { name: options.name } : {}),\n ...(region ? { region } : {}),\n ...(options.tenancyMode ? { tenancy_mode: options.tenancyMode } : {}),\n app: { type: \"web\", ...options.app, redirect_uris: options.app?.redirect_uris ?? options.redirectUris },\n client: options.client,\n },\n options,\n );\n if (!instance.claim_token) {\n throw new Error(\"@pontive/server: the unclaimed instance came back without a claim token\");\n }\n\n const local = await readEnvLocal(options.dir);\n const sessionSecret = env.PONTIVE_SESSION_SECRET?.trim() || local.get(\"PONTIVE_SESSION_SECRET\") || generateSessionSecret();\n const vars = envVarsFor(instance, sessionSecret);\n\n // .gitignore first, so the secrets are never committable, even for a moment.\n await ensureGitignore(options.dir);\n await appendEnvLocal(options.dir, vars, {\n comment: `Pontive: unclaimed development instance ${instance.instance_id}, deleted ${instance.expires_at} unless claimed`,\n });\n const record: KeylessRecord = {\n instance_id: instance.instance_id,\n issuer: instance.issuer,\n app_id: instance.app_id,\n claim_token: instance.claim_token,\n expires_at: instance.expires_at,\n region: instance.region,\n };\n await writeKeylessRecord(options.dir, record);\n\n return { record, env: vars, created: true };\n },\n options.lock,\n );\n}\n\n/**\n * Mints a claim link for the project's unclaimed instance with the claim\n * token in `keyless.json`. The token itself never leaves the machine.\n */\nexport async function claimLinkFor(record: KeylessRecord, options: ApiOptions = {}): Promise<ClaimLink> {\n if (!record.claim_token) {\n throw new PontiveApiError(409, \"instance_claimed\", \"this instance was claimed; its claim token is gone\");\n }\n return createClaimLink(record.instance_id, record.claim_token, options);\n}\n\n/** The deletion date, for people: `Wed, 9 Dec 2026`. */\nfunction humanDate(iso: string): string {\n const at = new Date(iso);\n if (Number.isNaN(at.getTime())) return iso;\n return at.toLocaleDateString(\"en-GB\", { weekday: \"short\", day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: \"UTC\" });\n}\n\n/** The one boxed console message (no secrets): the instance is unclaimed, when it is deleted, and how to claim it. */\nexport function keylessMessage(record: KeylessRecord, options: { created?: boolean } = {}): string {\n const lines = [\n options.created ? \"Pontive: created an unclaimed development instance\" : \"Pontive: using an unclaimed development instance\",\n \"\",\n `Instance ${record.instance_id} (${record.region})`,\n `Deleted ${humanDate(record.expires_at)}, with its users, unless claimed`,\n \"Claim it npx pontive claim, or Claim it in the app's banner\",\n `Settings ${ENV_FILE} and ${KEYLESS_FILE} (both gitignored)`,\n `More ${UNCLAIMED_DOCS_URL}`,\n ];\n const width = Math.max(...lines.map(l => l.length));\n const bar = \"─\".repeat(width + 2);\n return [`┌${bar}┐`, ...lines.map(l => `│ ${l.padEnd(width)} │`), `└${bar}┘`].join(\"\\n\");\n}\n"],"names":["DEFAULT_API_URL","KEYLESS_DIR","KEYLESS_FILE","KEYLESS_LOCK","ENV_FILE","GITIGNORE_ENTRIES","UNCLAIMED_DOCS_URL","PontiveApiError","status","code","message","retryAfter","apiBase","options","env","apiError","response","body","envelope","retry","retryable","createUnclaimedInstance","fetchImpl","args","key","send","createClaimLink","instanceId","claimToken","getUnclaimedInstance","KeylessUnavailableError","KeylessInstanceGoneError","record","nodeApis","proc","fs","path","isMissing","err","readKeylessRecord","dir","text","field","writeKeylessRecord","file","record_","keylessExpired","now","at","parseEnvFile","vars","raw","line","m","value","quote","close","readEnvLocal","appendEnvLocal","existing","present","written","skipped","lines","lead","sep","comment","ignores","entry","bare","forms","ensureGitignore","entries","missing","generateSessionSecret","bytes","binary","b","sleep","ms","resolve","withKeylessLock","fn","timeoutMs","staleMs","pollMs","lock","started","handle","pid","stat","envVarsFor","instance","sessionSecret","loopbackCallbacks","basePath","route","reuse","local","pick","goneMessage","why","what","ensureKeylessInstance","region","claimLinkFor","humanDate","iso","keylessMessage","width","l","bar"],"mappings":"gFA0BO,MAAMA,EAAkB,0BAElBC,EAAc,WAEdC,EAAe,wBAEfC,EAAe,wBAEfC,EAAW,aAEXC,EAAoB,CAAC,aAAc,WAAW,EAE9CC,EAAqB,mDAkE3B,MAAMC,UAAwB,KAAM,CAChC,OAEA,KAEA,WAET,YAAYC,EAAgBC,EAA0BC,EAAiBC,EAAqB,CAC1F,MAAMD,CAAO,EACb,KAAK,KAAO,kBACZ,KAAK,OAASF,EACd,KAAK,KAAOC,EACZ,KAAK,WAAaE,CACpB,CACF,CASA,SAASC,EAAQC,EAA6B,CAC5C,MAAMC,EAAO,WAA0E,SAAS,IAChG,OAAQD,EAAQ,QAAUC,GAAK,iBAAiB,QAAUd,GAAiB,QAAQ,OAAQ,EAAE,CAC/F,CAEA,eAAee,EAASC,EAA8C,CACpE,IAAIP,EACAC,EAAU,QAAQM,EAAS,MAAM,GACrC,GAAI,CACF,MAAMC,EAAQ,MAAMD,EAAS,KAAA,EACvBE,EAAWD,GAAM,OAASA,EAC5B,OAAOC,GAAU,MAAS,aAAiBA,EAAS,MACpD,OAAOA,GAAU,SAAY,aAAoBA,EAAS,QAChE,MAAQ,CAER,CACA,MAAMC,EAAQ,OAAOH,EAAS,QAAQ,IAAI,aAAa,CAAC,EACxD,OAAO,IAAIT,EAAgBS,EAAS,OAAQP,EAA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AO,CAAC,IAAIE,CAAG,IAAK,GAAGhD,EAAM,OAAS,KAAK+C,EAAE,OAAOD,CAAK,CAAC,IAAI,EAAG,IAAIE,CAAG,GAAG,EAAE,KAAK;AAAA,CAAI,CACxF"}
|
|
1
|
+
{"version":3,"file":"keyless.cjs","sources":["../src/keyless.ts"],"sourcesContent":["/**\n * Keyless mode's building blocks (pontive-spec 47 §5.1, §6.2, §7.2): creating\n * an unclaimed development instance with no Pontive account, keeping what the\n * app needs on the developer's machine, and minting claim links.\n *\n * `createServerAuth` uses them when it runs in development with no issuer, and\n * the `pontive` CLI imports them from `@pontive/server/keyless`, so the\n * dev server and the CLI write the same files the same way:\n *\n * - `.env.local`: the §6.1 variables, **appended**; a `PONTIVE_*` line already\n * there is never overwritten.\n * - `.pontive/keyless.json`: `{ instance_id, issuer, app_id, claim_token,\n * expires_at, region }`, the claim token being the instance's ownership.\n * - `.pontive/keyless.lock`: held while provisioning, so two dev workers never\n * create two instances.\n * - `.gitignore`: lists `.env.local` and `.pontive/`.\n *\n * Secrets are never logged: the console message names the instance, its region\n * and its deletion date, nothing else.\n *\n * The Node built-ins are reached through `process.getBuiltinModule` (Node\n * 20.16+, 22.3+), not imported: this module is part of the server entry, which\n * edge runtimes load too, and there it must load without a file system.\n */\n\n/** Where the provisioning routes live when `PONTIVE_API_URL` does not say. */\nexport const DEFAULT_API_URL = \"https://api.pontive.com\";\n/** The directory keyless mode keeps its files in, under the project root. */\nexport const KEYLESS_DIR = \".pontive\";\n/** The instance's record, under the project root. */\nexport const KEYLESS_FILE = \".pontive/keyless.json\";\n/** The provisioning lock, under the project root. */\nexport const KEYLESS_LOCK = \".pontive/keyless.lock\";\n/** The env file keyless mode appends to, under the project root. */\nexport const ENV_FILE = \".env.local\";\n/** What `.gitignore` must list. */\nexport const GITIGNORE_ENTRIES = [\".env.local\", \".pontive/\"] as const;\n/** The docs page on unclaimed instances. */\nexport const UNCLAIMED_DOCS_URL = \"https://www.pontive.com/docs/unclaimed-instances\";\n\n// ---------------------------------------------------------------------------\n// The API (platform-management-api, spec 47 §5.1, §7.2)\n// ---------------------------------------------------------------------------\n\n/** `POST /v1/unclaimed-instances`'s body. Every field is optional. */\nexport interface CreateUnclaimedInstanceRequest {\n name?: string;\n /** `us`, `eu`, `au`; default: the region nearest the caller. */\n region?: string;\n tenancy_mode?: \"b2c\" | \"b2b\";\n app?: {\n type?: \"web\" | \"spa\" | \"native\";\n /** Loopback only. Without a port, any port matches on a sandbox instance. */\n redirect_uris?: string[];\n };\n /** A public JWK (`EC` P-256 or `OKP` X25519): the secrets come back as a JWE in `encrypted_secrets`. */\n encryption_key?: Record<string, unknown>;\n /** The tool, its version and, when detected, the agent: metrics and abuse signals only. */\n client?: { name: string; version: string; agent?: string };\n}\n\n/** `POST /v1/unclaimed-instances`'s `201`. */\nexport interface UnclaimedInstance {\n object: \"unclaimed_instance\";\n instance_id: string;\n project_id: string;\n name: string;\n region: string;\n environment: string;\n tenancy_mode: string;\n issuer: string;\n app_id: string;\n /** A `web` app's client secret; absent with `encryption_key`. */\n client_secret?: string;\n /** The `keyless` developer secret key; absent with `encryption_key`. */\n secret_key?: string;\n secret_key_id: string;\n /** Returned once; absent with `encryption_key`. */\n claim_token?: string;\n /** With `encryption_key`: a compact JWE of `{ client_secret, secret_key, claim_token }`. */\n encrypted_secrets?: string;\n expires_at: string;\n limits_url?: string;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token. */\nexport interface UnclaimedInstanceStatus {\n object: \"unclaimed_instance\";\n instance_id: string;\n status: \"unclaimed\" | \"claimed\";\n claimed_at: string | null;\n expires_at?: string;\n [field: string]: unknown;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`'s `201`. */\nexport interface ClaimLink {\n object: \"claim_link\";\n /** `https://app.pontive.com/claim/{instance_id}#code=…`: single use, one hour. */\n url: string;\n expires_at: string;\n}\n\n/** A refusal from the Pontive API, in its standard envelope. */\nexport class PontiveApiError extends Error {\n readonly status: number;\n /** The envelope's `code` (`unclaimed_instance_limit`, `instance_claimed` …), when it had one. */\n readonly code: string | undefined;\n /** Seconds, from `Retry-After`, when the API sent one. */\n readonly retryAfter: number | undefined;\n\n constructor(status: number, code: string | undefined, message: string, retryAfter?: number) {\n super(message);\n this.name = \"PontiveApiError\";\n this.status = status;\n this.code = code;\n this.retryAfter = retryAfter;\n }\n}\n\nexport interface ApiOptions {\n /** Default `PONTIVE_API_URL`, else `https://api.pontive.com`. */\n apiUrl?: string;\n /** Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\nfunction apiBase(options: ApiOptions): string {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n return (options.apiUrl || env?.PONTIVE_API_URL?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n}\n\nasync function apiError(response: Response): Promise<PontiveApiError> {\n let code: string | undefined;\n let message = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { code?: unknown; message?: unknown }; code?: unknown; message?: unknown };\n const envelope = body?.error ?? body;\n if (typeof envelope?.code === \"string\") code = envelope.code;\n if (typeof envelope?.message === \"string\") message = envelope.message;\n } catch {\n // Not JSON: the status says enough.\n }\n const retry = Number(response.headers.get(\"retry-after\"));\n return new PontiveApiError(response.status, code, message, Number.isFinite(retry) && retry > 0 ? retry : undefined);\n}\n\n/** A status worth one retry with the same idempotency key: the request may not have reached the API. */\nconst retryable = (status: number) => status === 500 || status === 502 || status === 504;\n\n/**\n * `POST /v1/unclaimed-instances` (unauthenticated). Sends `X-Idempotency-Key`\n * (generated when not given) and retries once, with the same key, on a\n * network failure or a 500, 502 or 504: a retry within 24 hours returns the\n * same instance and counts once against the caller's limit.\n */\nexport async function createUnclaimedInstance(\n body: CreateUnclaimedInstanceRequest,\n options: ApiOptions & { idempotencyKey?: string } = {},\n): Promise<UnclaimedInstance> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const key = options.idempotencyKey ?? crypto.randomUUID();\n const send = () =>\n fetchImpl(`${apiBase(options)}/v1/unclaimed-instances`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"x-idempotency-key\": key },\n body: JSON.stringify(body),\n });\n\n let response: Response;\n try {\n response = await send();\n if (retryable(response.status)) response = await send();\n } catch {\n response = await send();\n }\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as UnclaimedInstance;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`, with the claim token in `X-Pontive-Claim-Token`. */\nexport async function createClaimLink(instanceId: string, claimToken: string, options: ApiOptions = {}): Promise<ClaimLink> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}/claim-links`, {\n method: \"POST\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as ClaimLink;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token: its status, for polling. */\nexport async function getUnclaimedInstance(\n instanceId: string,\n claimToken: string,\n options: ApiOptions = {},\n): Promise<UnclaimedInstanceStatus> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}`, {\n method: \"GET\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (!response.ok) throw await apiError(response);\n return (await response.json()) as UnclaimedInstanceStatus;\n}\n\n// ---------------------------------------------------------------------------\n// The files\n// ---------------------------------------------------------------------------\n\n/** `.pontive/keyless.json`. `claim_token` is gone once the instance is claimed (`pontive claim` removes it). */\nexport interface KeylessRecord {\n instance_id: string;\n issuer: string;\n app_id: string;\n claim_token?: string;\n expires_at: string;\n region: string;\n}\n\n/** Keyless mode needs a file system: thrown in a runtime without one (an edge runtime). */\nexport class KeylessUnavailableError extends Error {\n constructor(message = \"keyless mode needs Node.js 20.16 or later (process.getBuiltinModule); this runtime has no file system\") {\n super(`@pontive/server: ${message}`);\n this.name = \"KeylessUnavailableError\";\n }\n}\n\n/** The unclaimed instance this project uses has expired (Pontive deleted it) or was claimed away. */\nexport class KeylessInstanceGoneError extends Error {\n readonly record: KeylessRecord;\n\n constructor(record: KeylessRecord, message: string) {\n super(message);\n this.name = \"KeylessInstanceGoneError\";\n this.record = record;\n }\n}\n\ntype Fs = typeof import(\"node:fs/promises\");\ntype Path = typeof import(\"node:path\");\n\ninterface NodeApis {\n fs: Fs;\n path: Path;\n}\n\n/** `fs/promises` and `path`, or KeylessUnavailableError. */\nexport function nodeApis(): NodeApis {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n if (typeof proc?.getBuiltinModule !== \"function\") throw new KeylessUnavailableError();\n const fs = proc.getBuiltinModule(\"node:fs/promises\") as Fs | undefined;\n const path = proc.getBuiltinModule(\"node:path\") as Path | undefined;\n if (!fs || !path) throw new KeylessUnavailableError();\n return { fs, path };\n}\n\nconst isMissing = (err: unknown) => (err as { code?: string } | null)?.code === \"ENOENT\";\n\n/** The project's `.pontive/keyless.json`, or null when there is none. Throws on a file that is not a record. */\nexport async function readKeylessRecord(dir: string): Promise<KeylessRecord | null> {\n const { fs, path } = nodeApis();\n let text: string;\n try {\n text = await fs.readFile(path.join(dir, KEYLESS_FILE), \"utf8\");\n } catch (err) {\n if (isMissing(err)) return null;\n throw err;\n }\n const record = JSON.parse(text) as Partial<KeylessRecord>;\n for (const field of [\"instance_id\", \"issuer\", \"app_id\", \"expires_at\"] as const) {\n if (typeof record[field] !== \"string\" || !record[field]) {\n throw new Error(`@pontive/server: ${KEYLESS_FILE} has no ${field}; run \\`npx pontive init --reset\\``);\n }\n }\n return record as KeylessRecord;\n}\n\n/** Writes `.pontive/keyless.json` (owner-only: it holds the claim token). */\nexport async function writeKeylessRecord(dir: string, record: KeylessRecord): Promise<void> {\n const { fs, path } = nodeApis();\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const file = path.join(dir, KEYLESS_FILE);\n const record_: KeylessRecord = {\n instance_id: record.instance_id,\n issuer: record.issuer,\n app_id: record.app_id,\n ...(record.claim_token ? { claim_token: record.claim_token } : {}),\n expires_at: record.expires_at,\n region: record.region,\n };\n await fs.writeFile(file, `${JSON.stringify(record_, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await fs.chmod(file, 0o600).catch(() => {});\n}\n\n/** Whether the record's instance is past its deletion date. */\nexport function keylessExpired(record: KeylessRecord, now = Date.now()): boolean {\n const at = Date.parse(record.expires_at);\n return Number.isNaN(at) || at <= now;\n}\n\n/** The `KEY=value` lines of an env file (`export `, quotes and comments handled), or an empty map. */\nexport function parseEnvFile(text: string): Map<string, string> {\n const vars = new Map<string, string>();\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const m = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/.exec(line);\n if (!m) continue;\n let value = m[2]!;\n const quote = value[0];\n const close = quote === '\"' || quote === \"'\" ? value.indexOf(quote, 1) : -1;\n if (close > 0) value = value.slice(1, close);\n else value = value.replace(/\\s+#.*$/, \"\");\n vars.set(m[1]!, value);\n }\n return vars;\n}\n\n/** The project's `.env.local`, parsed; empty when there is none. */\nexport async function readEnvLocal(dir: string): Promise<Map<string, string>> {\n const { fs, path } = nodeApis();\n try {\n return parseEnvFile(await fs.readFile(path.join(dir, ENV_FILE), \"utf8\"));\n } catch (err) {\n if (isMissing(err)) return new Map();\n throw err;\n }\n}\n\n/**\n * Appends variables to `.env.local`, creating it when missing. A variable the\n * file already sets is never overwritten: it is reported in `skipped`.\n */\nexport async function appendEnvLocal(\n dir: string,\n vars: Readonly<Record<string, string | undefined>>,\n options: { comment?: string } = {},\n): Promise<{ written: string[]; skipped: string[] }> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, ENV_FILE);\n let existing = \"\";\n try {\n existing = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const present = parseEnvFile(existing);\n const written: string[] = [];\n const skipped: string[] = [];\n const lines: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (value === undefined) continue;\n if (present.has(key)) {\n skipped.push(key);\n continue;\n }\n lines.push(`${key}=${value}`);\n written.push(key);\n }\n if (lines.length > 0) {\n const lead = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n const sep = existing.trim() ? \"\\n\" : \"\";\n const comment = options.comment ? `# ${options.comment}\\n` : \"\";\n await fs.appendFile(file, `${lead}${sep}${comment}${lines.join(\"\\n\")}\\n`, { encoding: \"utf8\", mode: 0o600 });\n }\n return { written, skipped };\n}\n\n/** Whether a `.gitignore` line already keeps `entry` out (the exact entry, or a common equivalent). */\nfunction ignores(lines: string[], entry: string): boolean {\n const bare = entry.replace(/\\/$/, \"\");\n const forms =\n entry === \".env.local\"\n ? [\".env.local\", \"/.env.local\", \".env*.local\", \"/.env*.local\", \".env*\", \"/.env*\", \"*.local\"]\n : [bare, `/${bare}`, `${bare}/`, `/${bare}/`, `${bare}/*`, `/${bare}/*`];\n return lines.some(line => forms.includes(line.trim()));\n}\n\n/** Makes sure `.gitignore` lists `.env.local` and `.pontive/`, creating it when missing. Returns what it added. */\nexport async function ensureGitignore(dir: string, entries: readonly string[] = GITIGNORE_ENTRIES): Promise<string[]> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, \".gitignore\");\n let text = \"\";\n try {\n text = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const lines = text.split(/\\r?\\n/);\n const missing = entries.filter(entry => !ignores(lines, entry));\n if (missing.length > 0) {\n const lead = text && !text.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await fs.appendFile(file, `${lead}${text.trim() ? \"\\n\" : \"\"}# Pontive keyless mode: secrets and the claim token\\n${missing.join(\"\\n\")}\\n`, \"utf8\");\n }\n return missing;\n}\n\n/** 32 random bytes, base64url: a `PONTIVE_SESSION_SECRET` (43 characters), generated locally, never by Pontive. */\nexport function generateSessionSecret(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(32));\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nexport interface LockOptions {\n /** Give up waiting for another holder after this long. Default 60 s. */\n timeoutMs?: number;\n /** A lock older than this is a crashed holder's, and is taken over. Default 2 minutes. */\n staleMs?: number;\n /** How often to look again while another process holds it. Default 200 ms. */\n pollMs?: number;\n}\n\n/**\n * Runs `fn` holding `.pontive/keyless.lock`, created exclusively (`wx`), so\n * two processes (two dev workers, the dev server and the CLI) never provision\n * at once. A waiter re-reads `keyless.json` inside `fn` and finds the other's\n * instance. A lock left by a crashed process is taken over after `staleMs`.\n */\nexport async function withKeylessLock<T>(dir: string, fn: () => Promise<T>, options: LockOptions = {}): Promise<T> {\n const { fs, path } = nodeApis();\n const timeoutMs = options.timeoutMs ?? 60_000;\n const staleMs = options.staleMs ?? 120_000;\n const pollMs = options.pollMs ?? 200;\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const lock = path.join(dir, KEYLESS_LOCK);\n const started = Date.now();\n\n for (;;) {\n try {\n const handle = await fs.open(lock, \"wx\");\n try {\n const pid = (globalThis as { process?: { pid?: number } }).process?.pid;\n await handle.writeFile(JSON.stringify({ pid, created_at: new Date().toISOString() }));\n } finally {\n await handle.close();\n }\n break;\n } catch (err) {\n if ((err as { code?: string }).code !== \"EEXIST\") throw err;\n const stat = await fs.stat(lock).catch(() => null);\n if (stat && Date.now() - stat.mtimeMs > staleMs) {\n await fs.rm(lock, { force: true });\n continue;\n }\n if (Date.now() - started > timeoutMs) {\n throw new Error(`@pontive/server: ${KEYLESS_LOCK} is held by another process; remove it if nothing is provisioning`);\n }\n await sleep(pollMs);\n }\n }\n\n try {\n return await fn();\n } finally {\n await fs.rm(lock, { force: true }).catch(() => {});\n }\n}\n\n// ---------------------------------------------------------------------------\n// Provisioning, end to end\n// ---------------------------------------------------------------------------\n\n/** The §6.1 variables for a provisioned instance (only those it has). */\nexport function envVarsFor(instance: UnclaimedInstance, sessionSecret: string): Record<string, string | undefined> {\n return {\n PONTIVE_ISSUER: instance.issuer,\n PONTIVE_CLIENT_ID: instance.app_id,\n PONTIVE_CLIENT_SECRET: instance.client_secret,\n PONTIVE_SESSION_SECRET: sessionSecret,\n PONTIVE_SECRET_KEY: instance.secret_key,\n PONTIVE_INSTANCE_ID: instance.instance_id,\n };\n}\n\n/** The default redirect URIs for a dev server's callback route: port-less loopback, which matches any port (decision E5). */\nexport function loopbackCallbacks(basePath = \"/api/auth\"): string[] {\n const route = `${basePath.replace(/\\/+$/, \"\")}/callback`;\n return [`http://localhost${route}`, `http://127.0.0.1${route}`];\n}\n\nexport interface ProvisionOptions extends ApiOptions {\n /** The project root. */\n dir: string;\n /** Sent as `app.redirect_uris` (loopback only). */\n redirectUris: string[];\n /** Sent as `client`. */\n client: { name: string; version: string; agent?: string };\n /** Default `PONTIVE_REGION`, else the API picks the region nearest the caller. */\n region?: string;\n /** The project's name. */\n name?: string;\n app?: CreateUnclaimedInstanceRequest[\"app\"];\n tenancyMode?: \"b2c\" | \"b2b\";\n lock?: LockOptions;\n}\n\nexport interface KeylessInstance {\n record: KeylessRecord;\n /** The §6.1 values: what was just written, or what `.env.local` and the environment hold for a reused instance. */\n env: Record<string, string | undefined>;\n /** Created by this call (false: an existing `keyless.json` was reused). */\n created: boolean;\n}\n\nasync function reuse(dir: string, record: KeylessRecord): Promise<KeylessInstance> {\n const local = await readEnvLocal(dir);\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const pick = (key: string) => env[key]?.trim() || local.get(key) || undefined;\n return {\n record,\n created: false,\n env: {\n PONTIVE_ISSUER: record.issuer,\n PONTIVE_CLIENT_ID: record.app_id,\n PONTIVE_CLIENT_SECRET: pick(\"PONTIVE_CLIENT_SECRET\"),\n PONTIVE_SESSION_SECRET: pick(\"PONTIVE_SESSION_SECRET\"),\n PONTIVE_SECRET_KEY: pick(\"PONTIVE_SECRET_KEY\"),\n PONTIVE_INSTANCE_ID: record.instance_id,\n },\n };\n}\n\n/** The message for an instance that is no longer there, and what to do. */\nexport function goneMessage(record: KeylessRecord, why: \"expired\" | \"refused\"): string {\n const what =\n why === \"expired\"\n ? `expired on ${record.expires_at} and Pontive deleted it, with its users`\n : \"refused its credentials (401): it expired, or was claimed and its keys rotated\";\n return (\n `@pontive/server: the unclaimed Pontive instance in ${KEYLESS_FILE} (${record.instance_id}) ${what}. ` +\n \"Pontive does not create a new one over it, since the new one would have none of its users. \" +\n \"Run `npx pontive init --reset` to create another, or set PONTIVE_ISSUER for an instance of your own.\"\n );\n}\n\n/**\n * The project's unclaimed instance: `keyless.json`'s when it is there and not\n * expired; otherwise created now, under the lock, and written to `.env.local`\n * (appended), `keyless.json` and `.gitignore`.\n *\n * An expired `keyless.json` throws `KeylessInstanceGoneError`: never a second\n * instance silently over the first. Pass `reset: true` (`pontive init\n * --reset`) to replace it.\n */\nexport async function ensureKeylessInstance(options: ProvisionOptions & { reset?: boolean }): Promise<KeylessInstance> {\n const existing = options.reset ? null : await readKeylessRecord(options.dir);\n if (existing) {\n if (keylessExpired(existing)) throw new KeylessInstanceGoneError(existing, goneMessage(existing, \"expired\"));\n return reuse(options.dir, existing);\n }\n\n return withKeylessLock(\n options.dir,\n async () => {\n // Another process may have provisioned while this one waited.\n const now = options.reset ? null : await readKeylessRecord(options.dir);\n if (now) {\n if (keylessExpired(now)) throw new KeylessInstanceGoneError(now, goneMessage(now, \"expired\"));\n return reuse(options.dir, now);\n }\n\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const region = options.region || env.PONTIVE_REGION?.trim() || undefined;\n const instance = await createUnclaimedInstance(\n {\n ...(options.name ? { name: options.name } : {}),\n ...(region ? { region } : {}),\n ...(options.tenancyMode ? { tenancy_mode: options.tenancyMode } : {}),\n app: { type: \"web\", ...options.app, redirect_uris: options.app?.redirect_uris ?? options.redirectUris },\n client: options.client,\n },\n options,\n );\n if (!instance.claim_token) {\n throw new Error(\"@pontive/server: the unclaimed instance came back without a claim token\");\n }\n\n const local = await readEnvLocal(options.dir);\n const sessionSecret = env.PONTIVE_SESSION_SECRET?.trim() || local.get(\"PONTIVE_SESSION_SECRET\") || generateSessionSecret();\n const vars = envVarsFor(instance, sessionSecret);\n\n // .gitignore first, so the secrets are never committable, even for a moment.\n await ensureGitignore(options.dir);\n await appendEnvLocal(options.dir, vars, {\n comment: `Pontive: unclaimed development instance ${instance.instance_id}, deleted ${instance.expires_at} unless claimed`,\n });\n const record: KeylessRecord = {\n instance_id: instance.instance_id,\n issuer: instance.issuer,\n app_id: instance.app_id,\n claim_token: instance.claim_token,\n expires_at: instance.expires_at,\n region: instance.region,\n };\n await writeKeylessRecord(options.dir, record);\n\n return { record, env: vars, created: true };\n },\n options.lock,\n );\n}\n\n/**\n * Mints a claim link for the project's unclaimed instance with the claim\n * token in `keyless.json`. The token itself never leaves the machine.\n */\nexport async function claimLinkFor(record: KeylessRecord, options: ApiOptions = {}): Promise<ClaimLink> {\n if (!record.claim_token) {\n throw new PontiveApiError(409, \"instance_claimed\", \"this instance was claimed; its claim token is gone\");\n }\n return createClaimLink(record.instance_id, record.claim_token, options);\n}\n\n/** The deletion date, for people: `Wed, 9 Dec 2026`. */\nfunction humanDate(iso: string): string {\n const at = new Date(iso);\n if (Number.isNaN(at.getTime())) return iso;\n return at.toLocaleDateString(\"en-GB\", { weekday: \"short\", day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: \"UTC\" });\n}\n\n/** The one boxed console message (no secrets): the instance is unclaimed, when it is deleted, and how to claim it. */\nexport function keylessMessage(record: KeylessRecord, options: { created?: boolean } = {}): string {\n const lines = [\n options.created ? \"Pontive: created an unclaimed development instance\" : \"Pontive: using an unclaimed development instance\",\n \"\",\n `Instance ${record.instance_id} (${record.region})`,\n `Deleted ${humanDate(record.expires_at)}, with its users, unless claimed`,\n \"Claim it npx pontive claim, or Claim it in the app's banner\",\n `Settings ${ENV_FILE} and ${KEYLESS_FILE} (both gitignored)`,\n `More ${UNCLAIMED_DOCS_URL}`,\n ];\n const width = Math.max(...lines.map(l => l.length));\n const bar = \"─\".repeat(width + 2);\n return [`┌${bar}┐`, ...lines.map(l => `│ ${l.padEnd(width)} │`), `└${bar}┘`].join(\"\\n\");\n}\n"],"names":["DEFAULT_API_URL","KEYLESS_DIR","KEYLESS_FILE","KEYLESS_LOCK","ENV_FILE","GITIGNORE_ENTRIES","UNCLAIMED_DOCS_URL","PontiveApiError","status","code","message","retryAfter","apiBase","options","env","apiError","response","body","envelope","retry","retryable","createUnclaimedInstance","fetchImpl","args","key","send","createClaimLink","instanceId","claimToken","getUnclaimedInstance","KeylessUnavailableError","KeylessInstanceGoneError","record","nodeApis","proc","fs","path","isMissing","err","readKeylessRecord","dir","text","field","writeKeylessRecord","file","record_","keylessExpired","now","at","parseEnvFile","vars","raw","line","m","value","quote","close","readEnvLocal","appendEnvLocal","existing","present","written","skipped","lines","lead","sep","comment","ignores","entry","bare","forms","ensureGitignore","entries","missing","generateSessionSecret","bytes","binary","b","sleep","ms","resolve","withKeylessLock","fn","timeoutMs","staleMs","pollMs","lock","started","handle","pid","stat","envVarsFor","instance","sessionSecret","loopbackCallbacks","basePath","route","reuse","local","pick","goneMessage","why","what","ensureKeylessInstance","region","claimLinkFor","humanDate","iso","keylessMessage","width","l","bar"],"mappings":"gFA0BO,MAAMA,EAAkB,0BAElBC,EAAc,WAEdC,EAAe,wBAEfC,EAAe,wBAEfC,EAAW,aAEXC,EAAoB,CAAC,aAAc,WAAW,EAE9CC,EAAqB,mDAkE3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AAoD,EAEzG,OAAOmB,EAAgBM,EAAO,YAAaA,EAAO,YAAanB,CAAO,CACxE,CAGA,SAAS6F,EAAUC,EAAqB,CACtC,MAAM3D,EAAK,IAAI,KAAK2D,CAAG,EACvB,OAAI,OAAO,MAAM3D,EAAG,QAAA,CAAS,EAAU2D,EAChC3D,EAAG,mBAAmB,QAAS,CAAE,QAAS,QAAS,IAAK,UAAW,MAAO,QAAS,KAAM,UAAW,SAAU,MAAO,CAC9H,CAGO,SAAS4D,EAAe5E,EAAuBnB,EAAiC,GAAY,CACjG,MAAMkD,EAAQ,CACZlD,EAAQ,QAAU,qDAAuD,mDACzE,GACA,cAAcmB,EAAO,WAAW,KAAKA,EAAO,MAAM,IAClD,cAAc0E,EAAU1E,EAAO,UAAU,CAAC,mCAC1C,gEACA,cAAc5B,CAAQ,QAAQF,CAAY,qBAC1C,cAAcI,CAAkB,EAAA,EAE5BuG,EAAQ,KAAK,IAAI,GAAG9C,EAAM,IAAI+C,GAAKA,EAAE,MAAM,CAAC,EAC5CC,EAAM,IAAI,OAAOF,EAAQ,CAAC,EAChC,MAAO,CAAC,IAAIE,CAAG,IAAK,GAAGhD,EAAM,OAAS,KAAK+C,EAAE,OAAOD,CAAK,CAAC,IAAI,EAAG,IAAIE,CAAG,GAAG,EAAE,KAAK;AAAA,CAAI,CACxF"}
|
package/dist/keyless.d.cts
CHANGED
|
@@ -44,7 +44,7 @@ export interface CreateUnclaimedInstanceRequest {
|
|
|
44
44
|
tenancy_mode?: "b2c" | "b2b";
|
|
45
45
|
app?: {
|
|
46
46
|
type?: "web" | "spa" | "native";
|
|
47
|
-
/** Loopback only. Without a port, any port matches on a
|
|
47
|
+
/** Loopback only. Without a port, any port matches on a sandbox instance. */
|
|
48
48
|
redirect_uris?: string[];
|
|
49
49
|
};
|
|
50
50
|
/** A public JWK (`EC` P-256 or `OKP` X25519): the secrets come back as a JWE in `encrypted_secrets`. */
|
package/dist/keyless.d.ts
CHANGED
|
@@ -44,7 +44,7 @@ export interface CreateUnclaimedInstanceRequest {
|
|
|
44
44
|
tenancy_mode?: "b2c" | "b2b";
|
|
45
45
|
app?: {
|
|
46
46
|
type?: "web" | "spa" | "native";
|
|
47
|
-
/** Loopback only. Without a port, any port matches on a
|
|
47
|
+
/** Loopback only. Without a port, any port matches on a sandbox instance. */
|
|
48
48
|
redirect_uris?: string[];
|
|
49
49
|
};
|
|
50
50
|
/** A public JWK (`EC` P-256 or `OKP` X25519): the secrets come back as a JWE in `encrypted_secrets`. */
|
package/dist/keyless.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"keyless.js","sources":["../src/keyless.ts"],"sourcesContent":["/**\n * Keyless mode's building blocks (pontive-spec 47 §5.1, §6.2, §7.2): creating\n * an unclaimed development instance with no Pontive account, keeping what the\n * app needs on the developer's machine, and minting claim links.\n *\n * `createServerAuth` uses them when it runs in development with no issuer, and\n * the `pontive` CLI imports them from `@pontive/server/keyless`, so the\n * dev server and the CLI write the same files the same way:\n *\n * - `.env.local`: the §6.1 variables, **appended**; a `PONTIVE_*` line already\n * there is never overwritten.\n * - `.pontive/keyless.json`: `{ instance_id, issuer, app_id, claim_token,\n * expires_at, region }`, the claim token being the instance's ownership.\n * - `.pontive/keyless.lock`: held while provisioning, so two dev workers never\n * create two instances.\n * - `.gitignore`: lists `.env.local` and `.pontive/`.\n *\n * Secrets are never logged: the console message names the instance, its region\n * and its deletion date, nothing else.\n *\n * The Node built-ins are reached through `process.getBuiltinModule` (Node\n * 20.16+, 22.3+), not imported: this module is part of the server entry, which\n * edge runtimes load too, and there it must load without a file system.\n */\n\n/** Where the provisioning routes live when `PONTIVE_API_URL` does not say. */\nexport const DEFAULT_API_URL = \"https://api.pontive.com\";\n/** The directory keyless mode keeps its files in, under the project root. */\nexport const KEYLESS_DIR = \".pontive\";\n/** The instance's record, under the project root. */\nexport const KEYLESS_FILE = \".pontive/keyless.json\";\n/** The provisioning lock, under the project root. */\nexport const KEYLESS_LOCK = \".pontive/keyless.lock\";\n/** The env file keyless mode appends to, under the project root. */\nexport const ENV_FILE = \".env.local\";\n/** What `.gitignore` must list. */\nexport const GITIGNORE_ENTRIES = [\".env.local\", \".pontive/\"] as const;\n/** The docs page on unclaimed instances. */\nexport const UNCLAIMED_DOCS_URL = \"https://www.pontive.com/docs/unclaimed-instances\";\n\n// ---------------------------------------------------------------------------\n// The API (platform-management-api, spec 47 §5.1, §7.2)\n// ---------------------------------------------------------------------------\n\n/** `POST /v1/unclaimed-instances`'s body. Every field is optional. */\nexport interface CreateUnclaimedInstanceRequest {\n name?: string;\n /** `us`, `eu`, `au`; default: the region nearest the caller. */\n region?: string;\n tenancy_mode?: \"b2c\" | \"b2b\";\n app?: {\n type?: \"web\" | \"spa\" | \"native\";\n /** Loopback only. Without a port, any port matches on a non-production instance. */\n redirect_uris?: string[];\n };\n /** A public JWK (`EC` P-256 or `OKP` X25519): the secrets come back as a JWE in `encrypted_secrets`. */\n encryption_key?: Record<string, unknown>;\n /** The tool, its version and, when detected, the agent: metrics and abuse signals only. */\n client?: { name: string; version: string; agent?: string };\n}\n\n/** `POST /v1/unclaimed-instances`'s `201`. */\nexport interface UnclaimedInstance {\n object: \"unclaimed_instance\";\n instance_id: string;\n project_id: string;\n name: string;\n region: string;\n environment: string;\n tenancy_mode: string;\n issuer: string;\n app_id: string;\n /** A `web` app's client secret; absent with `encryption_key`. */\n client_secret?: string;\n /** The `keyless` developer secret key; absent with `encryption_key`. */\n secret_key?: string;\n secret_key_id: string;\n /** Returned once; absent with `encryption_key`. */\n claim_token?: string;\n /** With `encryption_key`: a compact JWE of `{ client_secret, secret_key, claim_token }`. */\n encrypted_secrets?: string;\n expires_at: string;\n limits_url?: string;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token. */\nexport interface UnclaimedInstanceStatus {\n object: \"unclaimed_instance\";\n instance_id: string;\n status: \"unclaimed\" | \"claimed\";\n claimed_at: string | null;\n expires_at?: string;\n [field: string]: unknown;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`'s `201`. */\nexport interface ClaimLink {\n object: \"claim_link\";\n /** `https://app.pontive.com/claim/{instance_id}#code=…`: single use, one hour. */\n url: string;\n expires_at: string;\n}\n\n/** A refusal from the Pontive API, in its standard envelope. */\nexport class PontiveApiError extends Error {\n readonly status: number;\n /** The envelope's `code` (`unclaimed_instance_limit`, `instance_claimed` …), when it had one. */\n readonly code: string | undefined;\n /** Seconds, from `Retry-After`, when the API sent one. */\n readonly retryAfter: number | undefined;\n\n constructor(status: number, code: string | undefined, message: string, retryAfter?: number) {\n super(message);\n this.name = \"PontiveApiError\";\n this.status = status;\n this.code = code;\n this.retryAfter = retryAfter;\n }\n}\n\nexport interface ApiOptions {\n /** Default `PONTIVE_API_URL`, else `https://api.pontive.com`. */\n apiUrl?: string;\n /** Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\nfunction apiBase(options: ApiOptions): string {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n return (options.apiUrl || env?.PONTIVE_API_URL?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n}\n\nasync function apiError(response: Response): Promise<PontiveApiError> {\n let code: string | undefined;\n let message = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { code?: unknown; message?: unknown }; code?: unknown; message?: unknown };\n const envelope = body?.error ?? body;\n if (typeof envelope?.code === \"string\") code = envelope.code;\n if (typeof envelope?.message === \"string\") message = envelope.message;\n } catch {\n // Not JSON: the status says enough.\n }\n const retry = Number(response.headers.get(\"retry-after\"));\n return new PontiveApiError(response.status, code, message, Number.isFinite(retry) && retry > 0 ? retry : undefined);\n}\n\n/** A status worth one retry with the same idempotency key: the request may not have reached the API. */\nconst retryable = (status: number) => status === 500 || status === 502 || status === 504;\n\n/**\n * `POST /v1/unclaimed-instances` (unauthenticated). Sends `X-Idempotency-Key`\n * (generated when not given) and retries once, with the same key, on a\n * network failure or a 500, 502 or 504: a retry within 24 hours returns the\n * same instance and counts once against the caller's limit.\n */\nexport async function createUnclaimedInstance(\n body: CreateUnclaimedInstanceRequest,\n options: ApiOptions & { idempotencyKey?: string } = {},\n): Promise<UnclaimedInstance> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const key = options.idempotencyKey ?? crypto.randomUUID();\n const send = () =>\n fetchImpl(`${apiBase(options)}/v1/unclaimed-instances`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"x-idempotency-key\": key },\n body: JSON.stringify(body),\n });\n\n let response: Response;\n try {\n response = await send();\n if (retryable(response.status)) response = await send();\n } catch {\n response = await send();\n }\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as UnclaimedInstance;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`, with the claim token in `X-Pontive-Claim-Token`. */\nexport async function createClaimLink(instanceId: string, claimToken: string, options: ApiOptions = {}): Promise<ClaimLink> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}/claim-links`, {\n method: \"POST\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as ClaimLink;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token: its status, for polling. */\nexport async function getUnclaimedInstance(\n instanceId: string,\n claimToken: string,\n options: ApiOptions = {},\n): Promise<UnclaimedInstanceStatus> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}`, {\n method: \"GET\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (!response.ok) throw await apiError(response);\n return (await response.json()) as UnclaimedInstanceStatus;\n}\n\n// ---------------------------------------------------------------------------\n// The files\n// ---------------------------------------------------------------------------\n\n/** `.pontive/keyless.json`. `claim_token` is gone once the instance is claimed (`pontive claim` removes it). */\nexport interface KeylessRecord {\n instance_id: string;\n issuer: string;\n app_id: string;\n claim_token?: string;\n expires_at: string;\n region: string;\n}\n\n/** Keyless mode needs a file system: thrown in a runtime without one (an edge runtime). */\nexport class KeylessUnavailableError extends Error {\n constructor(message = \"keyless mode needs Node.js 20.16 or later (process.getBuiltinModule); this runtime has no file system\") {\n super(`@pontive/server: ${message}`);\n this.name = \"KeylessUnavailableError\";\n }\n}\n\n/** The unclaimed instance this project uses has expired (Pontive deleted it) or was claimed away. */\nexport class KeylessInstanceGoneError extends Error {\n readonly record: KeylessRecord;\n\n constructor(record: KeylessRecord, message: string) {\n super(message);\n this.name = \"KeylessInstanceGoneError\";\n this.record = record;\n }\n}\n\ntype Fs = typeof import(\"node:fs/promises\");\ntype Path = typeof import(\"node:path\");\n\ninterface NodeApis {\n fs: Fs;\n path: Path;\n}\n\n/** `fs/promises` and `path`, or KeylessUnavailableError. */\nexport function nodeApis(): NodeApis {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n if (typeof proc?.getBuiltinModule !== \"function\") throw new KeylessUnavailableError();\n const fs = proc.getBuiltinModule(\"node:fs/promises\") as Fs | undefined;\n const path = proc.getBuiltinModule(\"node:path\") as Path | undefined;\n if (!fs || !path) throw new KeylessUnavailableError();\n return { fs, path };\n}\n\nconst isMissing = (err: unknown) => (err as { code?: string } | null)?.code === \"ENOENT\";\n\n/** The project's `.pontive/keyless.json`, or null when there is none. Throws on a file that is not a record. */\nexport async function readKeylessRecord(dir: string): Promise<KeylessRecord | null> {\n const { fs, path } = nodeApis();\n let text: string;\n try {\n text = await fs.readFile(path.join(dir, KEYLESS_FILE), \"utf8\");\n } catch (err) {\n if (isMissing(err)) return null;\n throw err;\n }\n const record = JSON.parse(text) as Partial<KeylessRecord>;\n for (const field of [\"instance_id\", \"issuer\", \"app_id\", \"expires_at\"] as const) {\n if (typeof record[field] !== \"string\" || !record[field]) {\n throw new Error(`@pontive/server: ${KEYLESS_FILE} has no ${field}; run \\`npx pontive init --reset\\``);\n }\n }\n return record as KeylessRecord;\n}\n\n/** Writes `.pontive/keyless.json` (owner-only: it holds the claim token). */\nexport async function writeKeylessRecord(dir: string, record: KeylessRecord): Promise<void> {\n const { fs, path } = nodeApis();\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const file = path.join(dir, KEYLESS_FILE);\n const record_: KeylessRecord = {\n instance_id: record.instance_id,\n issuer: record.issuer,\n app_id: record.app_id,\n ...(record.claim_token ? { claim_token: record.claim_token } : {}),\n expires_at: record.expires_at,\n region: record.region,\n };\n await fs.writeFile(file, `${JSON.stringify(record_, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await fs.chmod(file, 0o600).catch(() => {});\n}\n\n/** Whether the record's instance is past its deletion date. */\nexport function keylessExpired(record: KeylessRecord, now = Date.now()): boolean {\n const at = Date.parse(record.expires_at);\n return Number.isNaN(at) || at <= now;\n}\n\n/** The `KEY=value` lines of an env file (`export `, quotes and comments handled), or an empty map. */\nexport function parseEnvFile(text: string): Map<string, string> {\n const vars = new Map<string, string>();\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const m = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/.exec(line);\n if (!m) continue;\n let value = m[2]!;\n const quote = value[0];\n const close = quote === '\"' || quote === \"'\" ? value.indexOf(quote, 1) : -1;\n if (close > 0) value = value.slice(1, close);\n else value = value.replace(/\\s+#.*$/, \"\");\n vars.set(m[1]!, value);\n }\n return vars;\n}\n\n/** The project's `.env.local`, parsed; empty when there is none. */\nexport async function readEnvLocal(dir: string): Promise<Map<string, string>> {\n const { fs, path } = nodeApis();\n try {\n return parseEnvFile(await fs.readFile(path.join(dir, ENV_FILE), \"utf8\"));\n } catch (err) {\n if (isMissing(err)) return new Map();\n throw err;\n }\n}\n\n/**\n * Appends variables to `.env.local`, creating it when missing. A variable the\n * file already sets is never overwritten: it is reported in `skipped`.\n */\nexport async function appendEnvLocal(\n dir: string,\n vars: Readonly<Record<string, string | undefined>>,\n options: { comment?: string } = {},\n): Promise<{ written: string[]; skipped: string[] }> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, ENV_FILE);\n let existing = \"\";\n try {\n existing = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const present = parseEnvFile(existing);\n const written: string[] = [];\n const skipped: string[] = [];\n const lines: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (value === undefined) continue;\n if (present.has(key)) {\n skipped.push(key);\n continue;\n }\n lines.push(`${key}=${value}`);\n written.push(key);\n }\n if (lines.length > 0) {\n const lead = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n const sep = existing.trim() ? \"\\n\" : \"\";\n const comment = options.comment ? `# ${options.comment}\\n` : \"\";\n await fs.appendFile(file, `${lead}${sep}${comment}${lines.join(\"\\n\")}\\n`, { encoding: \"utf8\", mode: 0o600 });\n }\n return { written, skipped };\n}\n\n/** Whether a `.gitignore` line already keeps `entry` out (the exact entry, or a common equivalent). */\nfunction ignores(lines: string[], entry: string): boolean {\n const bare = entry.replace(/\\/$/, \"\");\n const forms =\n entry === \".env.local\"\n ? [\".env.local\", \"/.env.local\", \".env*.local\", \"/.env*.local\", \".env*\", \"/.env*\", \"*.local\"]\n : [bare, `/${bare}`, `${bare}/`, `/${bare}/`, `${bare}/*`, `/${bare}/*`];\n return lines.some(line => forms.includes(line.trim()));\n}\n\n/** Makes sure `.gitignore` lists `.env.local` and `.pontive/`, creating it when missing. Returns what it added. */\nexport async function ensureGitignore(dir: string, entries: readonly string[] = GITIGNORE_ENTRIES): Promise<string[]> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, \".gitignore\");\n let text = \"\";\n try {\n text = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const lines = text.split(/\\r?\\n/);\n const missing = entries.filter(entry => !ignores(lines, entry));\n if (missing.length > 0) {\n const lead = text && !text.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await fs.appendFile(file, `${lead}${text.trim() ? \"\\n\" : \"\"}# Pontive keyless mode: secrets and the claim token\\n${missing.join(\"\\n\")}\\n`, \"utf8\");\n }\n return missing;\n}\n\n/** 32 random bytes, base64url: a `PONTIVE_SESSION_SECRET` (43 characters), generated locally, never by Pontive. */\nexport function generateSessionSecret(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(32));\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nexport interface LockOptions {\n /** Give up waiting for another holder after this long. Default 60 s. */\n timeoutMs?: number;\n /** A lock older than this is a crashed holder's, and is taken over. Default 2 minutes. */\n staleMs?: number;\n /** How often to look again while another process holds it. Default 200 ms. */\n pollMs?: number;\n}\n\n/**\n * Runs `fn` holding `.pontive/keyless.lock`, created exclusively (`wx`), so\n * two processes (two dev workers, the dev server and the CLI) never provision\n * at once. A waiter re-reads `keyless.json` inside `fn` and finds the other's\n * instance. A lock left by a crashed process is taken over after `staleMs`.\n */\nexport async function withKeylessLock<T>(dir: string, fn: () => Promise<T>, options: LockOptions = {}): Promise<T> {\n const { fs, path } = nodeApis();\n const timeoutMs = options.timeoutMs ?? 60_000;\n const staleMs = options.staleMs ?? 120_000;\n const pollMs = options.pollMs ?? 200;\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const lock = path.join(dir, KEYLESS_LOCK);\n const started = Date.now();\n\n for (;;) {\n try {\n const handle = await fs.open(lock, \"wx\");\n try {\n const pid = (globalThis as { process?: { pid?: number } }).process?.pid;\n await handle.writeFile(JSON.stringify({ pid, created_at: new Date().toISOString() }));\n } finally {\n await handle.close();\n }\n break;\n } catch (err) {\n if ((err as { code?: string }).code !== \"EEXIST\") throw err;\n const stat = await fs.stat(lock).catch(() => null);\n if (stat && Date.now() - stat.mtimeMs > staleMs) {\n await fs.rm(lock, { force: true });\n continue;\n }\n if (Date.now() - started > timeoutMs) {\n throw new Error(`@pontive/server: ${KEYLESS_LOCK} is held by another process; remove it if nothing is provisioning`);\n }\n await sleep(pollMs);\n }\n }\n\n try {\n return await fn();\n } finally {\n await fs.rm(lock, { force: true }).catch(() => {});\n }\n}\n\n// ---------------------------------------------------------------------------\n// Provisioning, end to end\n// ---------------------------------------------------------------------------\n\n/** The §6.1 variables for a provisioned instance (only those it has). */\nexport function envVarsFor(instance: UnclaimedInstance, sessionSecret: string): Record<string, string | undefined> {\n return {\n PONTIVE_ISSUER: instance.issuer,\n PONTIVE_CLIENT_ID: instance.app_id,\n PONTIVE_CLIENT_SECRET: instance.client_secret,\n PONTIVE_SESSION_SECRET: sessionSecret,\n PONTIVE_SECRET_KEY: instance.secret_key,\n PONTIVE_INSTANCE_ID: instance.instance_id,\n };\n}\n\n/** The default redirect URIs for a dev server's callback route: port-less loopback, which matches any port (decision E5). */\nexport function loopbackCallbacks(basePath = \"/api/auth\"): string[] {\n const route = `${basePath.replace(/\\/+$/, \"\")}/callback`;\n return [`http://localhost${route}`, `http://127.0.0.1${route}`];\n}\n\nexport interface ProvisionOptions extends ApiOptions {\n /** The project root. */\n dir: string;\n /** Sent as `app.redirect_uris` (loopback only). */\n redirectUris: string[];\n /** Sent as `client`. */\n client: { name: string; version: string; agent?: string };\n /** Default `PONTIVE_REGION`, else the API picks the region nearest the caller. */\n region?: string;\n /** The project's name. */\n name?: string;\n app?: CreateUnclaimedInstanceRequest[\"app\"];\n tenancyMode?: \"b2c\" | \"b2b\";\n lock?: LockOptions;\n}\n\nexport interface KeylessInstance {\n record: KeylessRecord;\n /** The §6.1 values: what was just written, or what `.env.local` and the environment hold for a reused instance. */\n env: Record<string, string | undefined>;\n /** Created by this call (false: an existing `keyless.json` was reused). */\n created: boolean;\n}\n\nasync function reuse(dir: string, record: KeylessRecord): Promise<KeylessInstance> {\n const local = await readEnvLocal(dir);\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const pick = (key: string) => env[key]?.trim() || local.get(key) || undefined;\n return {\n record,\n created: false,\n env: {\n PONTIVE_ISSUER: record.issuer,\n PONTIVE_CLIENT_ID: record.app_id,\n PONTIVE_CLIENT_SECRET: pick(\"PONTIVE_CLIENT_SECRET\"),\n PONTIVE_SESSION_SECRET: pick(\"PONTIVE_SESSION_SECRET\"),\n PONTIVE_SECRET_KEY: pick(\"PONTIVE_SECRET_KEY\"),\n PONTIVE_INSTANCE_ID: record.instance_id,\n },\n };\n}\n\n/** The message for an instance that is no longer there, and what to do. */\nexport function goneMessage(record: KeylessRecord, why: \"expired\" | \"refused\"): string {\n const what =\n why === \"expired\"\n ? `expired on ${record.expires_at} and Pontive deleted it, with its users`\n : \"refused its credentials (401): it expired, or was claimed and its keys rotated\";\n return (\n `@pontive/server: the unclaimed Pontive instance in ${KEYLESS_FILE} (${record.instance_id}) ${what}. ` +\n \"Pontive does not create a new one over it, since the new one would have none of its users. \" +\n \"Run `npx pontive init --reset` to create another, or set PONTIVE_ISSUER for an instance of your own.\"\n );\n}\n\n/**\n * The project's unclaimed instance: `keyless.json`'s when it is there and not\n * expired; otherwise created now, under the lock, and written to `.env.local`\n * (appended), `keyless.json` and `.gitignore`.\n *\n * An expired `keyless.json` throws `KeylessInstanceGoneError`: never a second\n * instance silently over the first. Pass `reset: true` (`pontive init\n * --reset`) to replace it.\n */\nexport async function ensureKeylessInstance(options: ProvisionOptions & { reset?: boolean }): Promise<KeylessInstance> {\n const existing = options.reset ? null : await readKeylessRecord(options.dir);\n if (existing) {\n if (keylessExpired(existing)) throw new KeylessInstanceGoneError(existing, goneMessage(existing, \"expired\"));\n return reuse(options.dir, existing);\n }\n\n return withKeylessLock(\n options.dir,\n async () => {\n // Another process may have provisioned while this one waited.\n const now = options.reset ? null : await readKeylessRecord(options.dir);\n if (now) {\n if (keylessExpired(now)) throw new KeylessInstanceGoneError(now, goneMessage(now, \"expired\"));\n return reuse(options.dir, now);\n }\n\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const region = options.region || env.PONTIVE_REGION?.trim() || undefined;\n const instance = await createUnclaimedInstance(\n {\n ...(options.name ? { name: options.name } : {}),\n ...(region ? { region } : {}),\n ...(options.tenancyMode ? { tenancy_mode: options.tenancyMode } : {}),\n app: { type: \"web\", ...options.app, redirect_uris: options.app?.redirect_uris ?? options.redirectUris },\n client: options.client,\n },\n options,\n );\n if (!instance.claim_token) {\n throw new Error(\"@pontive/server: the unclaimed instance came back without a claim token\");\n }\n\n const local = await readEnvLocal(options.dir);\n const sessionSecret = env.PONTIVE_SESSION_SECRET?.trim() || local.get(\"PONTIVE_SESSION_SECRET\") || generateSessionSecret();\n const vars = envVarsFor(instance, sessionSecret);\n\n // .gitignore first, so the secrets are never committable, even for a moment.\n await ensureGitignore(options.dir);\n await appendEnvLocal(options.dir, vars, {\n comment: `Pontive: unclaimed development instance ${instance.instance_id}, deleted ${instance.expires_at} unless claimed`,\n });\n const record: KeylessRecord = {\n instance_id: instance.instance_id,\n issuer: instance.issuer,\n app_id: instance.app_id,\n claim_token: instance.claim_token,\n expires_at: instance.expires_at,\n region: instance.region,\n };\n await writeKeylessRecord(options.dir, record);\n\n return { record, env: vars, created: true };\n },\n options.lock,\n );\n}\n\n/**\n * Mints a claim link for the project's unclaimed instance with the claim\n * token in `keyless.json`. The token itself never leaves the machine.\n */\nexport async function claimLinkFor(record: KeylessRecord, options: ApiOptions = {}): Promise<ClaimLink> {\n if (!record.claim_token) {\n throw new PontiveApiError(409, \"instance_claimed\", \"this instance was claimed; its claim token is gone\");\n }\n return createClaimLink(record.instance_id, record.claim_token, options);\n}\n\n/** The deletion date, for people: `Wed, 9 Dec 2026`. */\nfunction humanDate(iso: string): string {\n const at = new Date(iso);\n if (Number.isNaN(at.getTime())) return iso;\n return at.toLocaleDateString(\"en-GB\", { weekday: \"short\", day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: \"UTC\" });\n}\n\n/** The one boxed console message (no secrets): the instance is unclaimed, when it is deleted, and how to claim it. */\nexport function keylessMessage(record: KeylessRecord, options: { created?: boolean } = {}): string {\n const lines = [\n options.created ? \"Pontive: created an unclaimed development instance\" : \"Pontive: using an unclaimed development instance\",\n \"\",\n `Instance ${record.instance_id} (${record.region})`,\n `Deleted ${humanDate(record.expires_at)}, with its users, unless claimed`,\n \"Claim it npx pontive claim, or Claim it in the app's banner\",\n `Settings ${ENV_FILE} and ${KEYLESS_FILE} (both gitignored)`,\n `More ${UNCLAIMED_DOCS_URL}`,\n ];\n const width = Math.max(...lines.map(l => l.length));\n const bar = \"─\".repeat(width + 2);\n return [`┌${bar}┐`, ...lines.map(l => `│ ${l.padEnd(width)} │`), `└${bar}┘`].join(\"\\n\");\n}\n"],"names":["DEFAULT_API_URL","KEYLESS_DIR","KEYLESS_FILE","KEYLESS_LOCK","ENV_FILE","GITIGNORE_ENTRIES","UNCLAIMED_DOCS_URL","PontiveApiError","status","code","message","retryAfter","apiBase","options","env","apiError","response","body","envelope","retry","retryable","createUnclaimedInstance","fetchImpl","args","key","send","createClaimLink","instanceId","claimToken","getUnclaimedInstance","KeylessUnavailableError","KeylessInstanceGoneError","record","nodeApis","proc","fs","path","isMissing","err","readKeylessRecord","dir","text","field","writeKeylessRecord","file","record_","keylessExpired","now","at","parseEnvFile","vars","raw","line","m","value","quote","close","readEnvLocal","appendEnvLocal","existing","present","written","skipped","lines","lead","sep","comment","ignores","entry","bare","forms","ensureGitignore","entries","missing","generateSessionSecret","bytes","binary","b","sleep","ms","resolve","withKeylessLock","fn","timeoutMs","staleMs","pollMs","lock","started","handle","pid","stat","envVarsFor","instance","sessionSecret","loopbackCallbacks","basePath","route","reuse","local","pick","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,SAAS4D,EAAe5E,GAAuBnB,IAAiC,IAAY;AACjG,QAAMkD,IAAQ;AAAA,IACZlD,EAAQ,UAAU,uDAAuD;AAAA,IACzE;AAAA,IACA,cAAcmB,EAAO,WAAW,KAAKA,EAAO,MAAM;AAAA,IAClD,cAAc0E,EAAU1E,EAAO,UAAU,CAAC;AAAA,IAC1C;AAAA,IACA,cAAc5B,CAAQ,QAAQF,CAAY;AAAA,IAC1C,cAAcI,CAAkB;AAAA,EAAA,GAE5BuG,IAAQ,KAAK,IAAI,GAAG9C,EAAM,IAAI,CAAA+C,MAAKA,EAAE,MAAM,CAAC,GAC5CC,IAAM,IAAI,OAAOF,IAAQ,CAAC;AAChC,SAAO,CAAC,IAAIE,CAAG,KAAK,GAAGhD,EAAM,IAAI,OAAK,KAAK+C,EAAE,OAAOD,CAAK,CAAC,IAAI,GAAG,IAAIE,CAAG,GAAG,EAAE,KAAK;AAAA,CAAI;AACxF;"}
|
|
1
|
+
{"version":3,"file":"keyless.js","sources":["../src/keyless.ts"],"sourcesContent":["/**\n * Keyless mode's building blocks (pontive-spec 47 §5.1, §6.2, §7.2): creating\n * an unclaimed development instance with no Pontive account, keeping what the\n * app needs on the developer's machine, and minting claim links.\n *\n * `createServerAuth` uses them when it runs in development with no issuer, and\n * the `pontive` CLI imports them from `@pontive/server/keyless`, so the\n * dev server and the CLI write the same files the same way:\n *\n * - `.env.local`: the §6.1 variables, **appended**; a `PONTIVE_*` line already\n * there is never overwritten.\n * - `.pontive/keyless.json`: `{ instance_id, issuer, app_id, claim_token,\n * expires_at, region }`, the claim token being the instance's ownership.\n * - `.pontive/keyless.lock`: held while provisioning, so two dev workers never\n * create two instances.\n * - `.gitignore`: lists `.env.local` and `.pontive/`.\n *\n * Secrets are never logged: the console message names the instance, its region\n * and its deletion date, nothing else.\n *\n * The Node built-ins are reached through `process.getBuiltinModule` (Node\n * 20.16+, 22.3+), not imported: this module is part of the server entry, which\n * edge runtimes load too, and there it must load without a file system.\n */\n\n/** Where the provisioning routes live when `PONTIVE_API_URL` does not say. */\nexport const DEFAULT_API_URL = \"https://api.pontive.com\";\n/** The directory keyless mode keeps its files in, under the project root. */\nexport const KEYLESS_DIR = \".pontive\";\n/** The instance's record, under the project root. */\nexport const KEYLESS_FILE = \".pontive/keyless.json\";\n/** The provisioning lock, under the project root. */\nexport const KEYLESS_LOCK = \".pontive/keyless.lock\";\n/** The env file keyless mode appends to, under the project root. */\nexport const ENV_FILE = \".env.local\";\n/** What `.gitignore` must list. */\nexport const GITIGNORE_ENTRIES = [\".env.local\", \".pontive/\"] as const;\n/** The docs page on unclaimed instances. */\nexport const UNCLAIMED_DOCS_URL = \"https://www.pontive.com/docs/unclaimed-instances\";\n\n// ---------------------------------------------------------------------------\n// The API (platform-management-api, spec 47 §5.1, §7.2)\n// ---------------------------------------------------------------------------\n\n/** `POST /v1/unclaimed-instances`'s body. Every field is optional. */\nexport interface CreateUnclaimedInstanceRequest {\n name?: string;\n /** `us`, `eu`, `au`; default: the region nearest the caller. */\n region?: string;\n tenancy_mode?: \"b2c\" | \"b2b\";\n app?: {\n type?: \"web\" | \"spa\" | \"native\";\n /** Loopback only. Without a port, any port matches on a sandbox instance. */\n redirect_uris?: string[];\n };\n /** A public JWK (`EC` P-256 or `OKP` X25519): the secrets come back as a JWE in `encrypted_secrets`. */\n encryption_key?: Record<string, unknown>;\n /** The tool, its version and, when detected, the agent: metrics and abuse signals only. */\n client?: { name: string; version: string; agent?: string };\n}\n\n/** `POST /v1/unclaimed-instances`'s `201`. */\nexport interface UnclaimedInstance {\n object: \"unclaimed_instance\";\n instance_id: string;\n project_id: string;\n name: string;\n region: string;\n environment: string;\n tenancy_mode: string;\n issuer: string;\n app_id: string;\n /** A `web` app's client secret; absent with `encryption_key`. */\n client_secret?: string;\n /** The `keyless` developer secret key; absent with `encryption_key`. */\n secret_key?: string;\n secret_key_id: string;\n /** Returned once; absent with `encryption_key`. */\n claim_token?: string;\n /** With `encryption_key`: a compact JWE of `{ client_secret, secret_key, claim_token }`. */\n encrypted_secrets?: string;\n expires_at: string;\n limits_url?: string;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token. */\nexport interface UnclaimedInstanceStatus {\n object: \"unclaimed_instance\";\n instance_id: string;\n status: \"unclaimed\" | \"claimed\";\n claimed_at: string | null;\n expires_at?: string;\n [field: string]: unknown;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`'s `201`. */\nexport interface ClaimLink {\n object: \"claim_link\";\n /** `https://app.pontive.com/claim/{instance_id}#code=…`: single use, one hour. */\n url: string;\n expires_at: string;\n}\n\n/** A refusal from the Pontive API, in its standard envelope. */\nexport class PontiveApiError extends Error {\n readonly status: number;\n /** The envelope's `code` (`unclaimed_instance_limit`, `instance_claimed` …), when it had one. */\n readonly code: string | undefined;\n /** Seconds, from `Retry-After`, when the API sent one. */\n readonly retryAfter: number | undefined;\n\n constructor(status: number, code: string | undefined, message: string, retryAfter?: number) {\n super(message);\n this.name = \"PontiveApiError\";\n this.status = status;\n this.code = code;\n this.retryAfter = retryAfter;\n }\n}\n\nexport interface ApiOptions {\n /** Default `PONTIVE_API_URL`, else `https://api.pontive.com`. */\n apiUrl?: string;\n /** Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\nfunction apiBase(options: ApiOptions): string {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n return (options.apiUrl || env?.PONTIVE_API_URL?.trim() || DEFAULT_API_URL).replace(/\\/+$/, \"\");\n}\n\nasync function apiError(response: Response): Promise<PontiveApiError> {\n let code: string | undefined;\n let message = `HTTP ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { code?: unknown; message?: unknown }; code?: unknown; message?: unknown };\n const envelope = body?.error ?? body;\n if (typeof envelope?.code === \"string\") code = envelope.code;\n if (typeof envelope?.message === \"string\") message = envelope.message;\n } catch {\n // Not JSON: the status says enough.\n }\n const retry = Number(response.headers.get(\"retry-after\"));\n return new PontiveApiError(response.status, code, message, Number.isFinite(retry) && retry > 0 ? retry : undefined);\n}\n\n/** A status worth one retry with the same idempotency key: the request may not have reached the API. */\nconst retryable = (status: number) => status === 500 || status === 502 || status === 504;\n\n/**\n * `POST /v1/unclaimed-instances` (unauthenticated). Sends `X-Idempotency-Key`\n * (generated when not given) and retries once, with the same key, on a\n * network failure or a 500, 502 or 504: a retry within 24 hours returns the\n * same instance and counts once against the caller's limit.\n */\nexport async function createUnclaimedInstance(\n body: CreateUnclaimedInstanceRequest,\n options: ApiOptions & { idempotencyKey?: string } = {},\n): Promise<UnclaimedInstance> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const key = options.idempotencyKey ?? crypto.randomUUID();\n const send = () =>\n fetchImpl(`${apiBase(options)}/v1/unclaimed-instances`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", accept: \"application/json\", \"x-idempotency-key\": key },\n body: JSON.stringify(body),\n });\n\n let response: Response;\n try {\n response = await send();\n if (retryable(response.status)) response = await send();\n } catch {\n response = await send();\n }\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as UnclaimedInstance;\n}\n\n/** `POST /v1/unclaimed-instances/{instance_id}/claim-links`, with the claim token in `X-Pontive-Claim-Token`. */\nexport async function createClaimLink(instanceId: string, claimToken: string, options: ApiOptions = {}): Promise<ClaimLink> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}/claim-links`, {\n method: \"POST\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (response.status !== 201 && response.status !== 200) throw await apiError(response);\n return (await response.json()) as ClaimLink;\n}\n\n/** `GET /v1/unclaimed-instances/{instance_id}` with the claim token: its status, for polling. */\nexport async function getUnclaimedInstance(\n instanceId: string,\n claimToken: string,\n options: ApiOptions = {},\n): Promise<UnclaimedInstanceStatus> {\n const fetchImpl = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const response = await fetchImpl(`${apiBase(options)}/v1/unclaimed-instances/${encodeURIComponent(instanceId)}`, {\n method: \"GET\",\n headers: { accept: \"application/json\", \"x-pontive-claim-token\": claimToken },\n });\n if (!response.ok) throw await apiError(response);\n return (await response.json()) as UnclaimedInstanceStatus;\n}\n\n// ---------------------------------------------------------------------------\n// The files\n// ---------------------------------------------------------------------------\n\n/** `.pontive/keyless.json`. `claim_token` is gone once the instance is claimed (`pontive claim` removes it). */\nexport interface KeylessRecord {\n instance_id: string;\n issuer: string;\n app_id: string;\n claim_token?: string;\n expires_at: string;\n region: string;\n}\n\n/** Keyless mode needs a file system: thrown in a runtime without one (an edge runtime). */\nexport class KeylessUnavailableError extends Error {\n constructor(message = \"keyless mode needs Node.js 20.16 or later (process.getBuiltinModule); this runtime has no file system\") {\n super(`@pontive/server: ${message}`);\n this.name = \"KeylessUnavailableError\";\n }\n}\n\n/** The unclaimed instance this project uses has expired (Pontive deleted it) or was claimed away. */\nexport class KeylessInstanceGoneError extends Error {\n readonly record: KeylessRecord;\n\n constructor(record: KeylessRecord, message: string) {\n super(message);\n this.name = \"KeylessInstanceGoneError\";\n this.record = record;\n }\n}\n\ntype Fs = typeof import(\"node:fs/promises\");\ntype Path = typeof import(\"node:path\");\n\ninterface NodeApis {\n fs: Fs;\n path: Path;\n}\n\n/** `fs/promises` and `path`, or KeylessUnavailableError. */\nexport function nodeApis(): NodeApis {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n if (typeof proc?.getBuiltinModule !== \"function\") throw new KeylessUnavailableError();\n const fs = proc.getBuiltinModule(\"node:fs/promises\") as Fs | undefined;\n const path = proc.getBuiltinModule(\"node:path\") as Path | undefined;\n if (!fs || !path) throw new KeylessUnavailableError();\n return { fs, path };\n}\n\nconst isMissing = (err: unknown) => (err as { code?: string } | null)?.code === \"ENOENT\";\n\n/** The project's `.pontive/keyless.json`, or null when there is none. Throws on a file that is not a record. */\nexport async function readKeylessRecord(dir: string): Promise<KeylessRecord | null> {\n const { fs, path } = nodeApis();\n let text: string;\n try {\n text = await fs.readFile(path.join(dir, KEYLESS_FILE), \"utf8\");\n } catch (err) {\n if (isMissing(err)) return null;\n throw err;\n }\n const record = JSON.parse(text) as Partial<KeylessRecord>;\n for (const field of [\"instance_id\", \"issuer\", \"app_id\", \"expires_at\"] as const) {\n if (typeof record[field] !== \"string\" || !record[field]) {\n throw new Error(`@pontive/server: ${KEYLESS_FILE} has no ${field}; run \\`npx pontive init --reset\\``);\n }\n }\n return record as KeylessRecord;\n}\n\n/** Writes `.pontive/keyless.json` (owner-only: it holds the claim token). */\nexport async function writeKeylessRecord(dir: string, record: KeylessRecord): Promise<void> {\n const { fs, path } = nodeApis();\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const file = path.join(dir, KEYLESS_FILE);\n const record_: KeylessRecord = {\n instance_id: record.instance_id,\n issuer: record.issuer,\n app_id: record.app_id,\n ...(record.claim_token ? { claim_token: record.claim_token } : {}),\n expires_at: record.expires_at,\n region: record.region,\n };\n await fs.writeFile(file, `${JSON.stringify(record_, null, 2)}\\n`, { encoding: \"utf8\", mode: 0o600 });\n await fs.chmod(file, 0o600).catch(() => {});\n}\n\n/** Whether the record's instance is past its deletion date. */\nexport function keylessExpired(record: KeylessRecord, now = Date.now()): boolean {\n const at = Date.parse(record.expires_at);\n return Number.isNaN(at) || at <= now;\n}\n\n/** The `KEY=value` lines of an env file (`export `, quotes and comments handled), or an empty map. */\nexport function parseEnvFile(text: string): Map<string, string> {\n const vars = new Map<string, string>();\n for (const raw of text.split(/\\r?\\n/)) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const m = /^(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*(.*)$/.exec(line);\n if (!m) continue;\n let value = m[2]!;\n const quote = value[0];\n const close = quote === '\"' || quote === \"'\" ? value.indexOf(quote, 1) : -1;\n if (close > 0) value = value.slice(1, close);\n else value = value.replace(/\\s+#.*$/, \"\");\n vars.set(m[1]!, value);\n }\n return vars;\n}\n\n/** The project's `.env.local`, parsed; empty when there is none. */\nexport async function readEnvLocal(dir: string): Promise<Map<string, string>> {\n const { fs, path } = nodeApis();\n try {\n return parseEnvFile(await fs.readFile(path.join(dir, ENV_FILE), \"utf8\"));\n } catch (err) {\n if (isMissing(err)) return new Map();\n throw err;\n }\n}\n\n/**\n * Appends variables to `.env.local`, creating it when missing. A variable the\n * file already sets is never overwritten: it is reported in `skipped`.\n */\nexport async function appendEnvLocal(\n dir: string,\n vars: Readonly<Record<string, string | undefined>>,\n options: { comment?: string } = {},\n): Promise<{ written: string[]; skipped: string[] }> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, ENV_FILE);\n let existing = \"\";\n try {\n existing = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const present = parseEnvFile(existing);\n const written: string[] = [];\n const skipped: string[] = [];\n const lines: string[] = [];\n for (const [key, value] of Object.entries(vars)) {\n if (value === undefined) continue;\n if (present.has(key)) {\n skipped.push(key);\n continue;\n }\n lines.push(`${key}=${value}`);\n written.push(key);\n }\n if (lines.length > 0) {\n const lead = existing && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n const sep = existing.trim() ? \"\\n\" : \"\";\n const comment = options.comment ? `# ${options.comment}\\n` : \"\";\n await fs.appendFile(file, `${lead}${sep}${comment}${lines.join(\"\\n\")}\\n`, { encoding: \"utf8\", mode: 0o600 });\n }\n return { written, skipped };\n}\n\n/** Whether a `.gitignore` line already keeps `entry` out (the exact entry, or a common equivalent). */\nfunction ignores(lines: string[], entry: string): boolean {\n const bare = entry.replace(/\\/$/, \"\");\n const forms =\n entry === \".env.local\"\n ? [\".env.local\", \"/.env.local\", \".env*.local\", \"/.env*.local\", \".env*\", \"/.env*\", \"*.local\"]\n : [bare, `/${bare}`, `${bare}/`, `/${bare}/`, `${bare}/*`, `/${bare}/*`];\n return lines.some(line => forms.includes(line.trim()));\n}\n\n/** Makes sure `.gitignore` lists `.env.local` and `.pontive/`, creating it when missing. Returns what it added. */\nexport async function ensureGitignore(dir: string, entries: readonly string[] = GITIGNORE_ENTRIES): Promise<string[]> {\n const { fs, path } = nodeApis();\n const file = path.join(dir, \".gitignore\");\n let text = \"\";\n try {\n text = await fs.readFile(file, \"utf8\");\n } catch (err) {\n if (!isMissing(err)) throw err;\n }\n const lines = text.split(/\\r?\\n/);\n const missing = entries.filter(entry => !ignores(lines, entry));\n if (missing.length > 0) {\n const lead = text && !text.endsWith(\"\\n\") ? \"\\n\" : \"\";\n await fs.appendFile(file, `${lead}${text.trim() ? \"\\n\" : \"\"}# Pontive keyless mode: secrets and the claim token\\n${missing.join(\"\\n\")}\\n`, \"utf8\");\n }\n return missing;\n}\n\n/** 32 random bytes, base64url: a `PONTIVE_SESSION_SECRET` (43 characters), generated locally, never by Pontive. */\nexport function generateSessionSecret(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(32));\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nexport interface LockOptions {\n /** Give up waiting for another holder after this long. Default 60 s. */\n timeoutMs?: number;\n /** A lock older than this is a crashed holder's, and is taken over. Default 2 minutes. */\n staleMs?: number;\n /** How often to look again while another process holds it. Default 200 ms. */\n pollMs?: number;\n}\n\n/**\n * Runs `fn` holding `.pontive/keyless.lock`, created exclusively (`wx`), so\n * two processes (two dev workers, the dev server and the CLI) never provision\n * at once. A waiter re-reads `keyless.json` inside `fn` and finds the other's\n * instance. A lock left by a crashed process is taken over after `staleMs`.\n */\nexport async function withKeylessLock<T>(dir: string, fn: () => Promise<T>, options: LockOptions = {}): Promise<T> {\n const { fs, path } = nodeApis();\n const timeoutMs = options.timeoutMs ?? 60_000;\n const staleMs = options.staleMs ?? 120_000;\n const pollMs = options.pollMs ?? 200;\n await fs.mkdir(path.join(dir, KEYLESS_DIR), { recursive: true });\n const lock = path.join(dir, KEYLESS_LOCK);\n const started = Date.now();\n\n for (;;) {\n try {\n const handle = await fs.open(lock, \"wx\");\n try {\n const pid = (globalThis as { process?: { pid?: number } }).process?.pid;\n await handle.writeFile(JSON.stringify({ pid, created_at: new Date().toISOString() }));\n } finally {\n await handle.close();\n }\n break;\n } catch (err) {\n if ((err as { code?: string }).code !== \"EEXIST\") throw err;\n const stat = await fs.stat(lock).catch(() => null);\n if (stat && Date.now() - stat.mtimeMs > staleMs) {\n await fs.rm(lock, { force: true });\n continue;\n }\n if (Date.now() - started > timeoutMs) {\n throw new Error(`@pontive/server: ${KEYLESS_LOCK} is held by another process; remove it if nothing is provisioning`);\n }\n await sleep(pollMs);\n }\n }\n\n try {\n return await fn();\n } finally {\n await fs.rm(lock, { force: true }).catch(() => {});\n }\n}\n\n// ---------------------------------------------------------------------------\n// Provisioning, end to end\n// ---------------------------------------------------------------------------\n\n/** The §6.1 variables for a provisioned instance (only those it has). */\nexport function envVarsFor(instance: UnclaimedInstance, sessionSecret: string): Record<string, string | undefined> {\n return {\n PONTIVE_ISSUER: instance.issuer,\n PONTIVE_CLIENT_ID: instance.app_id,\n PONTIVE_CLIENT_SECRET: instance.client_secret,\n PONTIVE_SESSION_SECRET: sessionSecret,\n PONTIVE_SECRET_KEY: instance.secret_key,\n PONTIVE_INSTANCE_ID: instance.instance_id,\n };\n}\n\n/** The default redirect URIs for a dev server's callback route: port-less loopback, which matches any port (decision E5). */\nexport function loopbackCallbacks(basePath = \"/api/auth\"): string[] {\n const route = `${basePath.replace(/\\/+$/, \"\")}/callback`;\n return [`http://localhost${route}`, `http://127.0.0.1${route}`];\n}\n\nexport interface ProvisionOptions extends ApiOptions {\n /** The project root. */\n dir: string;\n /** Sent as `app.redirect_uris` (loopback only). */\n redirectUris: string[];\n /** Sent as `client`. */\n client: { name: string; version: string; agent?: string };\n /** Default `PONTIVE_REGION`, else the API picks the region nearest the caller. */\n region?: string;\n /** The project's name. */\n name?: string;\n app?: CreateUnclaimedInstanceRequest[\"app\"];\n tenancyMode?: \"b2c\" | \"b2b\";\n lock?: LockOptions;\n}\n\nexport interface KeylessInstance {\n record: KeylessRecord;\n /** The §6.1 values: what was just written, or what `.env.local` and the environment hold for a reused instance. */\n env: Record<string, string | undefined>;\n /** Created by this call (false: an existing `keyless.json` was reused). */\n created: boolean;\n}\n\nasync function reuse(dir: string, record: KeylessRecord): Promise<KeylessInstance> {\n const local = await readEnvLocal(dir);\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const pick = (key: string) => env[key]?.trim() || local.get(key) || undefined;\n return {\n record,\n created: false,\n env: {\n PONTIVE_ISSUER: record.issuer,\n PONTIVE_CLIENT_ID: record.app_id,\n PONTIVE_CLIENT_SECRET: pick(\"PONTIVE_CLIENT_SECRET\"),\n PONTIVE_SESSION_SECRET: pick(\"PONTIVE_SESSION_SECRET\"),\n PONTIVE_SECRET_KEY: pick(\"PONTIVE_SECRET_KEY\"),\n PONTIVE_INSTANCE_ID: record.instance_id,\n },\n };\n}\n\n/** The message for an instance that is no longer there, and what to do. */\nexport function goneMessage(record: KeylessRecord, why: \"expired\" | \"refused\"): string {\n const what =\n why === \"expired\"\n ? `expired on ${record.expires_at} and Pontive deleted it, with its users`\n : \"refused its credentials (401): it expired, or was claimed and its keys rotated\";\n return (\n `@pontive/server: the unclaimed Pontive instance in ${KEYLESS_FILE} (${record.instance_id}) ${what}. ` +\n \"Pontive does not create a new one over it, since the new one would have none of its users. \" +\n \"Run `npx pontive init --reset` to create another, or set PONTIVE_ISSUER for an instance of your own.\"\n );\n}\n\n/**\n * The project's unclaimed instance: `keyless.json`'s when it is there and not\n * expired; otherwise created now, under the lock, and written to `.env.local`\n * (appended), `keyless.json` and `.gitignore`.\n *\n * An expired `keyless.json` throws `KeylessInstanceGoneError`: never a second\n * instance silently over the first. Pass `reset: true` (`pontive init\n * --reset`) to replace it.\n */\nexport async function ensureKeylessInstance(options: ProvisionOptions & { reset?: boolean }): Promise<KeylessInstance> {\n const existing = options.reset ? null : await readKeylessRecord(options.dir);\n if (existing) {\n if (keylessExpired(existing)) throw new KeylessInstanceGoneError(existing, goneMessage(existing, \"expired\"));\n return reuse(options.dir, existing);\n }\n\n return withKeylessLock(\n options.dir,\n async () => {\n // Another process may have provisioned while this one waited.\n const now = options.reset ? null : await readKeylessRecord(options.dir);\n if (now) {\n if (keylessExpired(now)) throw new KeylessInstanceGoneError(now, goneMessage(now, \"expired\"));\n return reuse(options.dir, now);\n }\n\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n const region = options.region || env.PONTIVE_REGION?.trim() || undefined;\n const instance = await createUnclaimedInstance(\n {\n ...(options.name ? { name: options.name } : {}),\n ...(region ? { region } : {}),\n ...(options.tenancyMode ? { tenancy_mode: options.tenancyMode } : {}),\n app: { type: \"web\", ...options.app, redirect_uris: options.app?.redirect_uris ?? options.redirectUris },\n client: options.client,\n },\n options,\n );\n if (!instance.claim_token) {\n throw new Error(\"@pontive/server: the unclaimed instance came back without a claim token\");\n }\n\n const local = await readEnvLocal(options.dir);\n const sessionSecret = env.PONTIVE_SESSION_SECRET?.trim() || local.get(\"PONTIVE_SESSION_SECRET\") || generateSessionSecret();\n const vars = envVarsFor(instance, sessionSecret);\n\n // .gitignore first, so the secrets are never committable, even for a moment.\n await ensureGitignore(options.dir);\n await appendEnvLocal(options.dir, vars, {\n comment: `Pontive: unclaimed development instance ${instance.instance_id}, deleted ${instance.expires_at} unless claimed`,\n });\n const record: KeylessRecord = {\n instance_id: instance.instance_id,\n issuer: instance.issuer,\n app_id: instance.app_id,\n claim_token: instance.claim_token,\n expires_at: instance.expires_at,\n region: instance.region,\n };\n await writeKeylessRecord(options.dir, record);\n\n return { record, env: vars, created: true };\n },\n options.lock,\n );\n}\n\n/**\n * Mints a claim link for the project's unclaimed instance with the claim\n * token in `keyless.json`. The token itself never leaves the machine.\n */\nexport async function claimLinkFor(record: KeylessRecord, options: ApiOptions = {}): Promise<ClaimLink> {\n if (!record.claim_token) {\n throw new PontiveApiError(409, \"instance_claimed\", \"this instance was claimed; its claim token is gone\");\n }\n return createClaimLink(record.instance_id, record.claim_token, options);\n}\n\n/** The deletion date, for people: `Wed, 9 Dec 2026`. */\nfunction humanDate(iso: string): string {\n const at = new Date(iso);\n if (Number.isNaN(at.getTime())) return iso;\n return at.toLocaleDateString(\"en-GB\", { weekday: \"short\", day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: \"UTC\" });\n}\n\n/** The one boxed console message (no secrets): the instance is unclaimed, when it is deleted, and how to claim it. */\nexport function keylessMessage(record: KeylessRecord, options: { created?: boolean } = {}): string {\n const lines = [\n options.created ? \"Pontive: created an unclaimed development instance\" : \"Pontive: using an unclaimed development instance\",\n \"\",\n `Instance ${record.instance_id} (${record.region})`,\n `Deleted ${humanDate(record.expires_at)}, with its users, unless claimed`,\n \"Claim it npx pontive claim, or Claim it in the app's banner\",\n `Settings ${ENV_FILE} and ${KEYLESS_FILE} (both gitignored)`,\n `More ${UNCLAIMED_DOCS_URL}`,\n ];\n const width = Math.max(...lines.map(l => l.length));\n const bar = \"─\".repeat(width + 2);\n return [`┌${bar}┐`, ...lines.map(l => `│ ${l.padEnd(width)} │`), `└${bar}┘`].join(\"\\n\");\n}\n"],"names":["DEFAULT_API_URL","KEYLESS_DIR","KEYLESS_FILE","KEYLESS_LOCK","ENV_FILE","GITIGNORE_ENTRIES","UNCLAIMED_DOCS_URL","PontiveApiError","status","code","message","retryAfter","apiBase","options","env","apiError","response","body","envelope","retry","retryable","createUnclaimedInstance","fetchImpl","args","key","send","createClaimLink","instanceId","claimToken","getUnclaimedInstance","KeylessUnavailableError","KeylessInstanceGoneError","record","nodeApis","proc","fs","path","isMissing","err","readKeylessRecord","dir","text","field","writeKeylessRecord","file","record_","keylessExpired","now","at","parseEnvFile","vars","raw","line","m","value","quote","close","readEnvLocal","appendEnvLocal","existing","present","written","skipped","lines","lead","sep","comment","ignores","entry","bare","forms","ensureGitignore","entries","missing","generateSessionSecret","bytes","binary","b","sleep","ms","resolve","withKeylessLock","fn","timeoutMs","staleMs","pollMs","lock","started","handle","pid","stat","envVarsFor","instance","sessionSecret","loopbackCallbacks","basePath","route","reuse","local","pick","goneMessage","why","what","ensureKeylessInstance","region","claimLinkFor","humanDate","iso","keylessMessage","width","l","bar"],"mappings":"AA0BO,MAAMA,IAAkB,2BAElBC,IAAc,YAEdC,IAAe,yBAEfC,IAAe,yBAEfC,IAAW,cAEXC,IAAoB,CAAC,cAAc,WAAW,GAE9CC,IAAqB;AAkE3B,MAAMC,UAAwB,MAAM;AAAA,EAChC;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA,EAET,YAAYC,GAAgBC,GAA0BC,GAAiBC,GAAqB;AAC1F,UAAMD,CAAO,GACb,KAAK,OAAO,mBACZ,KAAK,SAASF,GACd,KAAK,OAAOC,GACZ,KAAK,aAAaE;AAAA,EACpB;AACF;AASA,SAASC,EAAQC,GAA6B;AAC5C,QAAMC,IAAO,WAA0E,SAAS;AAChG,UAAQD,EAAQ,UAAUC,GAAK,iBAAiB,UAAUd,GAAiB,QAAQ,QAAQ,EAAE;AAC/F;AAEA,eAAee,EAASC,GAA8C;AACpE,MAAIP,GACAC,IAAU,QAAQM,EAAS,MAAM;AACrC,MAAI;AACF,UAAMC,IAAQ,MAAMD,EAAS,KAAA,GACvBE,IAAWD,GAAM,SAASA;AAChC,IAAI,OAAOC,GAAU,QAAS,iBAAiBA,EAAS,OACpD,OAAOA,GAAU,WAAY,iBAAoBA,EAAS;AAAA,EAChE,QAAQ;AAAA,EAER;AACA,QAAMC,IAAQ,OAAOH,EAAS,QAAQ,IAAI,aAAa,CAAC;AACxD,SAAO,IAAIT,EAAgBS,EAAS,QAAQP,GAAMC,GAAS,OAAO,SAASS,CAAK,KAAKA,IAAQ,IAAIA,IAAQ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AAGA,SAAS6F,EAAUC,GAAqB;AACtC,QAAM3D,IAAK,IAAI,KAAK2D,CAAG;AACvB,SAAI,OAAO,MAAM3D,EAAG,QAAA,CAAS,IAAU2D,IAChC3D,EAAG,mBAAmB,SAAS,EAAE,SAAS,SAAS,KAAK,WAAW,OAAO,SAAS,MAAM,WAAW,UAAU,OAAO;AAC9H;AAGO,SAAS4D,EAAe5E,GAAuBnB,IAAiC,IAAY;AACjG,QAAMkD,IAAQ;AAAA,IACZlD,EAAQ,UAAU,uDAAuD;AAAA,IACzE;AAAA,IACA,cAAcmB,EAAO,WAAW,KAAKA,EAAO,MAAM;AAAA,IAClD,cAAc0E,EAAU1E,EAAO,UAAU,CAAC;AAAA,IAC1C;AAAA,IACA,cAAc5B,CAAQ,QAAQF,CAAY;AAAA,IAC1C,cAAcI,CAAkB;AAAA,EAAA,GAE5BuG,IAAQ,KAAK,IAAI,GAAG9C,EAAM,IAAI,CAAA+C,MAAKA,EAAE,MAAM,CAAC,GAC5CC,IAAM,IAAI,OAAOF,IAAQ,CAAC;AAChC,SAAO,CAAC,IAAIE,CAAG,KAAK,GAAGhD,EAAM,IAAI,OAAK,KAAK+C,EAAE,OAAOD,CAAK,CAAC,IAAI,GAAG,IAAIE,CAAG,GAAG,EAAE,KAAK;AAAA,CAAI;AACxF;"}
|
|
@@ -29,7 +29,7 @@ export interface PontiveOptions {
|
|
|
29
29
|
* names, then `PONTIVE_REGION`, then the region in the issuer's host.
|
|
30
30
|
*/
|
|
31
31
|
region?: string;
|
|
32
|
-
/** Overrides the management API's base, for a proxy or
|
|
32
|
+
/** Overrides the management API's base, for a proxy or another Pontive deployment. Default: `PONTIVE_MANAGEMENT_URL`. */
|
|
33
33
|
managementUrl?: string;
|
|
34
34
|
/** Overrides the authorization host. Default: `managementUrl` with its `api.` label replaced by `authz.`. */
|
|
35
35
|
authzUrl?: string;
|
|
@@ -46,7 +46,7 @@ export interface PontiveOptions {
|
|
|
46
46
|
/** The environment to fall back to. Default: `process.env`. */
|
|
47
47
|
env?: Env;
|
|
48
48
|
}
|
|
49
|
-
/** The region a secret key names: `
|
|
49
|
+
/** The region a secret key names: `pontive_sk_us_…` or `pontive_sk_sandbox_us_…` → `us`. */
|
|
50
50
|
export declare function secretKeyRegion(key: string): string | undefined;
|
|
51
51
|
/**
|
|
52
52
|
* A client for Pontive's management API, and its authorization and usage
|
|
@@ -29,7 +29,7 @@ export interface PontiveOptions {
|
|
|
29
29
|
* names, then `PONTIVE_REGION`, then the region in the issuer's host.
|
|
30
30
|
*/
|
|
31
31
|
region?: string;
|
|
32
|
-
/** Overrides the management API's base, for a proxy or
|
|
32
|
+
/** Overrides the management API's base, for a proxy or another Pontive deployment. Default: `PONTIVE_MANAGEMENT_URL`. */
|
|
33
33
|
managementUrl?: string;
|
|
34
34
|
/** Overrides the authorization host. Default: `managementUrl` with its `api.` label replaced by `authz.`. */
|
|
35
35
|
authzUrl?: string;
|
|
@@ -46,7 +46,7 @@ export interface PontiveOptions {
|
|
|
46
46
|
/** The environment to fall back to. Default: `process.env`. */
|
|
47
47
|
env?: Env;
|
|
48
48
|
}
|
|
49
|
-
/** The region a secret key names: `
|
|
49
|
+
/** The region a secret key names: `pontive_sk_us_…` or `pontive_sk_sandbox_us_…` → `us`. */
|
|
50
50
|
export declare function secretKeyRegion(key: string): string | undefined;
|
|
51
51
|
/**
|
|
52
52
|
* A client for Pontive's management API, and its authorization and usage
|
package/dist/management.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./client-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./client-BOivaOZe.cjs");exports.APIPromise=r.APIPromise;exports.AuthenticationError=r.AuthenticationError;exports.BadRequestError=r.BadRequestError;exports.ConflictError=r.ConflictError;exports.InternalServerError=r.InternalServerError;exports.NotFoundError=r.NotFoundError;exports.Page=r.Page;exports.PagePromise=r.PagePromise;exports.PermissionDeniedError=r.PermissionDeniedError;exports.Pontive=r.Pontive;exports.PontiveAPIError=r.PontiveAPIError;exports.PontiveConnectionError=r.PontiveConnectionError;exports.PreconditionFailedError=r.PreconditionFailedError;exports.RateLimitError=r.RateLimitError;exports.UnprocessableEntityError=r.UnprocessableEntityError;exports.secretKeyRegion=r.secretKeyRegion;
|
|
2
2
|
//# sourceMappingURL=management.cjs.map
|
package/dist/management.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as e, a, B as s, C as i, I as n, N as t, P as E, b as P, c, d, e as m, f as g, g as l, R as v, U as A, s as I } from "./client-
|
|
1
|
+
import { A as e, a, B as s, C as i, I as n, N as t, P as E, b as P, c, d, e as m, f as g, g as l, R as v, U as A, s as I } from "./client-gWGqYFNx.js";
|
|
2
2
|
export {
|
|
3
3
|
e as APIPromise,
|
|
4
4
|
a as AuthenticationError,
|
|
@@ -36,7 +36,7 @@ export interface PontivePlatformOptions {
|
|
|
36
36
|
*
|
|
37
37
|
* ```ts
|
|
38
38
|
* const platform = new PontivePlatform({ workspaceKey: process.env.PONTIVE_WORKSPACE_KEY });
|
|
39
|
-
* const instance = await platform.instances.create({ project_id: "proj_…", environment: "
|
|
39
|
+
* const instance = await platform.instances.create({ project_id: "proj_…", environment: "sandbox", name: "preview-42" });
|
|
40
40
|
* const key = await platform.instances.createSecretKey(instance.id!, { name: "ci", role: "developer" });
|
|
41
41
|
* ```
|
|
42
42
|
*
|
|
@@ -36,7 +36,7 @@ export interface PontivePlatformOptions {
|
|
|
36
36
|
*
|
|
37
37
|
* ```ts
|
|
38
38
|
* const platform = new PontivePlatform({ workspaceKey: process.env.PONTIVE_WORKSPACE_KEY });
|
|
39
|
-
* const instance = await platform.instances.create({ project_id: "proj_…", environment: "
|
|
39
|
+
* const instance = await platform.instances.create({ project_id: "proj_…", environment: "sandbox", name: "preview-42" });
|
|
40
40
|
* const key = await platform.instances.createSecretKey(instance.id!, { name: "ci", role: "developer" });
|
|
41
41
|
* ```
|
|
42
42
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pontive/server",
|
|
3
|
-
"version": "1.29.
|
|
3
|
+
"version": "1.29.4",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "The Pontive SDK for TypeScript servers: the management API client, sessions for apps (sign-in, a sealed session cookie, safe token refresh) and resource-server middleware for APIs and MCP servers, on Web Request/Response.",
|
|
6
6
|
"type": "module",
|