pontive 1.19.0 → 1.20.0

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.
Files changed (3) hide show
  1. package/README.md +6 -4
  2. package/dist/cli.js +146 -311
  3. package/package.json +3 -2
package/README.md CHANGED
@@ -9,7 +9,7 @@ instance into your workspace whenever you sign up.
9
9
  npx pontive@latest init
10
10
  ```
11
11
 
12
- Node.js 20 or later. Nothing to install first.
12
+ Node.js 20.16 or later, or 22.3 or later. Nothing to install first.
13
13
 
14
14
  ## Commands
15
15
 
@@ -27,8 +27,8 @@ Node.js 20 or later. Nothing to install first.
27
27
 
28
28
  | Framework | Detected by | Installs | Writes |
29
29
  | --- | --- | --- | --- |
30
- | Next.js | `next` | `@pontive/pontkit-nextjs` | `lib/pontive.ts`, `app/api/auth/[...pontive]/route.ts`, `middleware.ts` (`proxy.ts` from Next 16); under `src/` when the app is |
31
- | Vite + React | `vite` and `react` | `@pontive/pontkit-react`, `@pontive/pontkit-loader` | `src/pontive.tsx` (the provider), `vite.pontive.ts` (the dev server's `/__pontive` proxy) |
30
+ | Next.js | `next` | `@pontive/pontkit-nextjs` | `lib/pontive.ts` (`pontiveAuth()`), `app/api/auth/[...pontive]/route.ts`, `app/pontive-provider.tsx` (rendered with `pontive.providerProps()`, so no `NEXT_PUBLIC_` copy), `middleware.ts` (`proxy.ts` from Next 16); under `src/` when the app is |
31
+ | Vite + React | `vite` and `react` | `@pontive/pontkit-react`, `@pontive/pontkit-loader` | `src/pontive.tsx` (the provider), `vite.pontive.ts` (the dev server's `/__pontive` proxy; it hands the browser the client id and no other variable) |
32
32
  | Express | `express` | `@pontive/pontkit-server` | `pontive.ts`: `pontiveRoutes` and `pontiveSession` middleware |
33
33
  | Node | anything else | `@pontive/pontkit-server` | `pontive.ts`: `handlePontive(req, res)` for `node:http` |
34
34
 
@@ -53,7 +53,9 @@ and writes:
53
53
 
54
54
  The secrets come back encrypted to a P-256 key the CLI generates for the call
55
55
  and keeps only in memory, so they never travel in a response body anything in
56
- between could keep. An instance already in `.pontive/keyless.json`, or already
56
+ between could keep. The files are written by `@pontive/pontkit-server/keyless`,
57
+ the same code pontkit's dev server uses in keyless mode, under the same lock
58
+ (`.pontive/keyless.lock`), so the two never create two instances. An instance already in `.pontive/keyless.json`, or already
57
59
  configured in `.env.local`, is used rather than replaced.
58
60
 
59
61
  | Option | |
package/dist/cli.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { randomBytes, generateKeyPairSync, randomUUID, createHash } from "node:crypto";
3
- import { existsSync, readFileSync, writeFileSync, openSync, closeSync, statSync, unlinkSync, mkdirSync, renameSync, createReadStream, createWriteStream } from "node:fs";
4
- import { join, dirname, basename, resolve } from "node:path";
2
+ import { createUnclaimedInstance, getUnclaimedInstance, createClaimLink, PontiveApiError, DEFAULT_API_URL, readKeylessRecord, KEYLESS_FILE, withKeylessLock, KEYLESS_LOCK, appendEnvLocal, nodeApis, ENV_FILE, parseEnvFile, keylessExpired, writeKeylessRecord, ensureGitignore, GITIGNORE_ENTRIES, readEnvLocal, envVarsFor, generateSessionSecret } from "@pontive/pontkit-server/keyless";
3
+ import { generateKeyPairSync, randomUUID, createHash } from "node:crypto";
5
4
  import { calculateJwkThumbprint, decodeProtectedHeader, compactDecrypt } from "jose";
5
+ import { existsSync, readFileSync, statSync, mkdirSync, writeFileSync, createReadStream, createWriteStream } from "node:fs";
6
+ import { join, dirname, basename, resolve } from "node:path";
6
7
  import { spawnSync, spawn } from "node:child_process";
7
8
  import { readFile, rm, writeFile, rename } from "node:fs/promises";
8
9
  import { createInterface } from "node:readline";
@@ -38,127 +39,70 @@ class CliError extends Error {
38
39
  function cancelled(message, extra = {}) {
39
40
  return new CliError("cancelled", message, ExitCode.Cancelled, extra);
40
41
  }
41
- const DEFAULT_API_URL = "https://api.pontive.com";
42
42
  function apiBaseUrl$1(env) {
43
- return (env.PONTIVE_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
43
+ return (env.PONTIVE_API_URL?.trim() || DEFAULT_API_URL).replace(/\/+$/, "");
44
44
  }
45
- function retryAfterSeconds(header, now) {
46
- if (!header) return void 0;
47
- const trimmed = header.trim();
48
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
49
- const at = Date.parse(trimmed);
50
- if (Number.isNaN(at)) return void 0;
51
- return Math.max(0, Math.ceil((at - now.getTime()) / 1e3));
52
- }
53
- async function errorOf(response) {
54
- try {
55
- const body = await response.json();
56
- return {
57
- code: typeof body.error?.code === "string" ? body.error.code : void 0,
58
- message: typeof body.error?.message === "string" ? body.error.message : void 0
59
- };
60
- } catch {
61
- return {};
45
+ const MAX_RETRY_WAIT_SECONDS = 30;
46
+ function cliErrorOf(error) {
47
+ const { status, code: code2, message, retryAfter } = error;
48
+ if (status === 429) {
49
+ return new CliError(code2 ?? "rate_limited", message, ExitCode.RateLimited, { retry_after: retryAfter ?? 60 });
50
+ }
51
+ if (status === 401) {
52
+ return new CliError(
53
+ code2 ?? "unauthorized",
54
+ "Pontive refused the instance's credentials: the unclaimed instance expired or was claimed by someone else. Run pontive init --reset for a new one.",
55
+ ExitCode.ExpiredOrClaimedAway
56
+ );
57
+ }
58
+ if (status === 404 && (code2 === "unclaimed_instance_not_found" || code2 === void 0)) {
59
+ return new CliError(
60
+ "unclaimed_instance_not_found",
61
+ "Pontive no longer knows this unclaimed instance: it expired, or its claim token is no longer valid. Run pontive init --reset for a new one.",
62
+ ExitCode.ExpiredOrClaimedAway
63
+ );
62
64
  }
65
+ return new CliError(code2 ?? `http_${status}`, message, ExitCode.Error, retryAfter !== void 0 ? { retry_after: retryAfter } : {});
63
66
  }
64
- const MAX_RETRY_WAIT_SECONDS = 30;
65
67
  let PontiveApi$1 = class PontiveApi {
66
68
  constructor(options2) {
67
69
  this.options = options2;
68
70
  }
69
71
  options;
70
- /** Provisions an unclaimed development instance. Retried with the same idempotency key, so a retry never makes a second one. */
72
+ /** Provisions an unclaimed development instance. Every retry carries the same idempotency key, so none makes a second one. */
71
73
  provision(body, idempotencyKey) {
72
- return this.request("POST", "/v1/unclaimed-instances", {
73
- body,
74
- headers: { "x-idempotency-key": idempotencyKey }
75
- });
74
+ return this.call(() => createUnclaimedInstance(body, { apiUrl: this.options.baseUrl, fetch: this.options.fetch, idempotencyKey }));
76
75
  }
77
76
  getUnclaimed(instanceId, claimToken) {
78
- return this.request("GET", `/v1/unclaimed-instances/${encodeURIComponent(instanceId)}`, {
79
- headers: { "x-pontive-claim-token": claimToken }
80
- });
77
+ return this.call(() => getUnclaimedInstance(instanceId, claimToken, { apiUrl: this.options.baseUrl, fetch: this.options.fetch }));
81
78
  }
79
+ /** Minting twice is harmless: each link expires on its own, and the first one used ends the rest. */
82
80
  mintClaimLink(instanceId, claimToken) {
83
- return this.request("POST", `/v1/unclaimed-instances/${encodeURIComponent(instanceId)}/claim-links`, {
84
- headers: { "x-pontive-claim-token": claimToken }
85
- });
81
+ return this.call(() => createClaimLink(instanceId, claimToken, { apiUrl: this.options.baseUrl, fetch: this.options.fetch }));
86
82
  }
87
- async request(method, path, init) {
88
- const { baseUrl, fetch: fetch2, sleep, now, signal, userAgent } = this.options;
83
+ async call(send) {
84
+ const { sleep, signal, baseUrl } = this.options;
89
85
  const retries = this.options.retries ?? 3;
90
- const url = `${baseUrl}${path}`;
91
86
  for (let attempt = 0; ; attempt++) {
92
87
  const backoff2 = 1e3 * 2 ** attempt;
93
- let response;
94
88
  try {
95
- response = await fetch2(url, {
96
- method,
97
- headers: {
98
- accept: "application/json",
99
- "user-agent": userAgent,
100
- ...init.body !== void 0 ? { "content-type": "application/json" } : {},
101
- ...init.headers
102
- },
103
- body: init.body !== void 0 ? JSON.stringify(init.body) : void 0,
104
- signal
105
- });
89
+ return await send();
106
90
  } catch (error) {
107
91
  if (signal?.aborted) throw error;
108
- if (attempt < retries) {
109
- await sleep(backoff2, signal);
92
+ if (error instanceof PontiveApiError) {
93
+ if (error.status < 500 || attempt >= retries) throw cliErrorOf(error);
94
+ const wait = error.retryAfter !== void 0 && error.retryAfter <= MAX_RETRY_WAIT_SECONDS ? error.retryAfter * 1e3 : backoff2;
95
+ await sleep(wait, signal);
110
96
  continue;
111
97
  }
112
- throw new CliError("network_error", `Could not reach ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
113
- }
114
- if (response.ok) return await response.json();
115
- const retryAfter = retryAfterSeconds(response.headers.get("retry-after"), now());
116
- if (response.status >= 500 && attempt < retries) {
117
- const wait = retryAfter !== void 0 && retryAfter <= MAX_RETRY_WAIT_SECONDS ? retryAfter * 1e3 : backoff2;
118
- await response.body?.cancel();
119
- await sleep(wait, signal);
120
- continue;
98
+ if (attempt >= retries) {
99
+ throw new CliError("network_error", `Could not reach ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
100
+ }
101
+ await sleep(backoff2, signal);
121
102
  }
122
- throw await this.failure(response, retryAfter);
123
103
  }
124
104
  }
125
- async failure(response, retryAfter) {
126
- const { code: code2, message } = await errorOf(response);
127
- const extra = retryAfter !== void 0 ? { retry_after: retryAfter } : {};
128
- if (response.status === 429) {
129
- return new CliError(
130
- code2 ?? "rate_limited",
131
- message ?? `Pontive rate limited the request${retryAfter !== void 0 ? `; retry in ${retryAfter}s` : ""}.`,
132
- ExitCode.RateLimited,
133
- { retry_after: retryAfter ?? 60 }
134
- );
135
- }
136
- if (response.status === 401) {
137
- return new CliError(
138
- code2 ?? "unauthorized",
139
- "Pontive refused the instance's credentials: the unclaimed instance expired or was claimed by someone else. Run pontive init --reset for a new one.",
140
- ExitCode.ExpiredOrClaimedAway
141
- );
142
- }
143
- if (response.status === 404 && (code2 === "unclaimed_instance_not_found" || code2 === void 0)) {
144
- return new CliError(
145
- "unclaimed_instance_not_found",
146
- "Pontive no longer knows this unclaimed instance: it expired, or its claim token is no longer valid. Run pontive init --reset for a new one.",
147
- ExitCode.ExpiredOrClaimedAway
148
- );
149
- }
150
- return new CliError(
151
- code2 ?? `http_${response.status}`,
152
- message ?? `Pontive answered ${response.status} ${response.statusText}.`.replace(/ \./, "."),
153
- ExitCode.Error,
154
- extra
155
- );
156
- }
157
105
  };
158
- const ENV_FILE = ".env.local";
159
- const PONTIVE_DIR = ".pontive";
160
- const KEYLESS_FILE = join(PONTIVE_DIR, "keyless.json");
161
- const LOCK_FILE = join(PONTIVE_DIR, "keyless.lock");
162
106
  const CONTRACT_VARIABLES = [
163
107
  "PONTIVE_ISSUER",
164
108
  "PONTIVE_CLIENT_ID",
@@ -167,192 +111,78 @@ const CONTRACT_VARIABLES = [
167
111
  "PONTIVE_SECRET_KEY",
168
112
  "PONTIVE_INSTANCE_ID"
169
113
  ];
170
- function writeAtomic(path, contents) {
171
- mkdirSync(dirname(path), { recursive: true });
172
- const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
173
- writeFileSync(tmp, contents, { mode: 384 });
174
- renameSync(tmp, path);
175
- }
176
- function ensurePontiveDir(cwd) {
177
- const dir = join(cwd, PONTIVE_DIR);
178
- mkdirSync(dir, { recursive: true, mode: 448 });
179
- const ignore = join(dir, ".gitignore");
180
- if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
181
- }
182
- function readKeyless(cwd) {
183
- const path = join(cwd, KEYLESS_FILE);
184
- if (!existsSync(path)) return null;
185
- let parsed;
114
+ async function readKeyless(cwd) {
186
115
  try {
187
- parsed = JSON.parse(readFileSync(path, "utf8"));
188
- } catch {
189
- throw new CliError("invalid_keyless_file", `${KEYLESS_FILE} is not valid JSON.`);
190
- }
191
- const k = parsed;
192
- for (const field of ["instance_id", "issuer", "app_id", "expires_at", "region"]) {
193
- if (typeof k?.[field] !== "string") throw new CliError("invalid_keyless_file", `${KEYLESS_FILE} has no ${field}.`);
194
- }
195
- return parsed;
196
- }
197
- function writeKeyless(cwd, keyless) {
198
- ensurePontiveDir(cwd);
199
- const ordered = {
200
- instance_id: keyless.instance_id,
201
- issuer: keyless.issuer,
202
- app_id: keyless.app_id,
203
- ...keyless.claim_token ? { claim_token: keyless.claim_token } : {},
204
- expires_at: keyless.expires_at,
205
- region: keyless.region
206
- };
207
- writeAtomic(join(cwd, KEYLESS_FILE), `${JSON.stringify(ordered, null, 2)}
208
- `);
209
- }
210
- async function withKeylessLock(cwd, options2, fn) {
211
- ensurePontiveDir(cwd);
212
- const path = join(cwd, LOCK_FILE);
213
- const waitMs = options2.waitMs ?? 3e4;
214
- const staleMs = options2.staleMs ?? 12e4;
215
- const step = 250;
216
- for (let waited = 0; ; waited += step) {
217
- try {
218
- const fd = openSync(path, "wx", 384);
219
- writeFileSync(fd, `${JSON.stringify({ pid: process.pid, at: (/* @__PURE__ */ new Date()).toISOString(), by: "pontive-cli" })}
220
- `);
221
- closeSync(fd);
222
- break;
223
- } catch (error) {
224
- if (error.code !== "EEXIST") throw error;
225
- try {
226
- if (Date.now() - statSync(path).mtimeMs > staleMs) {
227
- unlinkSync(path);
228
- continue;
229
- }
230
- } catch {
231
- continue;
232
- }
233
- if (waited >= waitMs) {
234
- throw new CliError(
235
- "keyless_locked",
236
- `${LOCK_FILE} is held by another process (a dev server provisioning?). Try again shortly, or remove the file if nothing is running.`
237
- );
238
- }
239
- await options2.sleep(step, options2.signal);
240
- }
241
- }
242
- try {
243
- return await fn();
244
- } finally {
245
- try {
246
- unlinkSync(path);
247
- } catch {
248
- }
116
+ return await readKeylessRecord(cwd);
117
+ } catch (error) {
118
+ throw new CliError(
119
+ "invalid_keyless_file",
120
+ error instanceof SyntaxError ? `${KEYLESS_FILE} is not valid JSON.` : error instanceof Error ? error.message : String(error)
121
+ );
249
122
  }
250
123
  }
251
- const ENV_LINE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;
252
- function unquote(raw) {
253
- const value = raw.trim();
254
- if (value.length >= 2 && (value[0] === '"' || value[0] === "'") && value.at(-1) === value[0]) return value.slice(1, -1);
255
- return value.replace(/\s+#.*$/, "");
256
- }
257
- function readEnvFile(cwd) {
258
- const path = join(cwd, ENV_FILE);
259
- const vars = /* @__PURE__ */ new Map();
260
- if (!existsSync(path)) return vars;
261
- for (const line of readFileSync(path, "utf8").split(/\r?\n/)) {
262
- const match = ENV_LINE.exec(line);
263
- if (match && !vars.has(match[1])) vars.set(match[1], unquote(match[2]));
124
+ async function withLock(cwd, fn, options2 = { timeoutMs: 3e4 }) {
125
+ let inside = false;
126
+ try {
127
+ return await withKeylessLock(
128
+ cwd,
129
+ () => {
130
+ inside = true;
131
+ return fn();
132
+ },
133
+ options2
134
+ );
135
+ } catch (error) {
136
+ if (inside || !(error instanceof Error && error.message.includes("held by another process"))) throw error;
137
+ throw new CliError(
138
+ "keyless_locked",
139
+ `${KEYLESS_LOCK} is held by another process (a dev server provisioning?). Try again shortly, or remove the file if nothing is running.`
140
+ );
264
141
  }
265
- return vars;
266
142
  }
267
- function formatValue(value) {
268
- return /^[A-Za-z0-9_\-.:/+=@]*$/.test(value) ? value : JSON.stringify(value);
269
- }
270
- function writeEnv(cwd, entries, replace = /* @__PURE__ */ new Set()) {
271
- const path = join(cwd, ENV_FILE);
272
- const original = existsSync(path) ? readFileSync(path, "utf8") : "";
273
- const lines = original === "" ? [] : original.replace(/\r?\n$/, "").split(/\r?\n/);
274
- const result = { added: [], kept: [], replaced: [] };
275
- const wanted = new Map(entries);
276
- for (let i = 0; i < lines.length; i++) {
277
- const match = ENV_LINE.exec(lines[i]);
278
- if (!match || !wanted.has(match[1])) continue;
279
- const name = match[1];
280
- if (replace.has(name) && !result.replaced.includes(name)) {
281
- lines[i] = `${name}=${formatValue(wanted.get(name))}`;
282
- result.replaced.push(name);
283
- } else if (!result.kept.includes(name) && !result.replaced.includes(name)) {
284
- result.kept.push(name);
285
- }
286
- }
287
- const missing = entries.filter(([name]) => !result.kept.includes(name) && !result.replaced.includes(name));
288
- if (missing.length > 0) {
289
- if (lines.length > 0 && lines.at(-1).trim() !== "") lines.push("");
290
- lines.push("# Pontive: written by pontive init. See https://docs.pontive.com/unclaimed-instances");
291
- for (const [name, value] of missing) {
292
- lines.push(`${name}=${formatValue(value)}`);
293
- result.added.push(name);
143
+ async function dropEnvLines(cwd, names) {
144
+ const { fs, path } = nodeApis();
145
+ const file = path.join(cwd, ENV_FILE);
146
+ let text;
147
+ try {
148
+ text = await fs.readFile(file, "utf8");
149
+ } catch {
150
+ return [];
151
+ }
152
+ const removed = /* @__PURE__ */ new Set();
153
+ const kept = text.split(/\r?\n/).filter((line) => {
154
+ const name = [...parseEnvFile(line).keys()][0];
155
+ if (name !== void 0 && names.has(name)) {
156
+ removed.add(name);
157
+ return false;
294
158
  }
295
- }
296
- if (result.added.length > 0 || result.replaced.length > 0) writeAtomic(path, `${lines.join("\n")}
297
- `);
298
- return result;
159
+ return true;
160
+ });
161
+ if (removed.size > 0) await fs.writeFile(file, kept.join("\n"), { encoding: "utf8", mode: 384 });
162
+ return [...removed];
299
163
  }
300
- function sessionSecret() {
301
- return randomBytes(32).toString("base64url");
302
- }
303
- function patternMatches(pattern, path, isDir2) {
304
- let p = pattern.trim();
305
- if (p === "" || p.startsWith("#") || p.startsWith("!")) return false;
306
- if (p.endsWith("/")) {
307
- if (!isDir2) return false;
308
- p = p.slice(0, -1);
309
- }
310
- p = p.replace(/^\//, "").replace(/^\*\*\//, "");
311
- if (p.includes("/")) return false;
312
- const regex = new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")}$`);
313
- return regex.test(path);
314
- }
315
- function ensureGitignore(cwd, entries) {
316
- const path = join(cwd, ".gitignore");
317
- const original = existsSync(path) ? readFileSync(path, "utf8") : "";
318
- const patterns = original.split(/\r?\n/);
319
- const added = [];
320
- for (const entry of entries) {
321
- const isDir2 = entry.endsWith("/");
322
- const name = entry.replace(/\/$/, "");
323
- const exact = (p) => [name, `/${name}`, `${name}/`, `/${name}/`].includes(p.trim());
324
- if (patterns.some((p) => exact(p) || patternMatches(p, name, isDir2))) continue;
325
- added.push(entry);
326
- }
327
- if (added.length > 0) {
328
- const prefix = original === "" || original.endsWith("\n") ? original : `${original}
329
- `;
330
- writeFileSync(path, `${prefix}${prefix === "" ? "" : "\n"}# Pontive: secrets for local development
331
- ${added.join("\n")}
332
- `);
333
- }
334
- return added;
164
+ async function writeEnv(cwd, vars, options2 = {}) {
165
+ const replace = new Set(Object.keys(vars).filter((name) => options2.replace?.has(name) && vars[name] !== void 0));
166
+ const removed = replace.size > 0 ? await dropEnvLines(cwd, replace) : [];
167
+ const { written, skipped } = await appendEnvLocal(cwd, vars, { comment: options2.comment });
168
+ return {
169
+ added: written.filter((name) => !removed.includes(name)),
170
+ kept: skipped,
171
+ replaced: written.filter((name) => removed.includes(name))
172
+ };
335
173
  }
336
174
  function apiFor(ctx) {
337
- return new PontiveApi$1({
338
- baseUrl: apiBaseUrl$1(ctx.env),
339
- fetch: ctx.fetch,
340
- sleep: ctx.sleep,
341
- now: ctx.now,
342
- signal: ctx.signal,
343
- userAgent: `pontive-cli/${ctx.version}`
344
- });
175
+ return new PontiveApi$1({ baseUrl: apiBaseUrl$1(ctx.env), fetch: ctx.fetch, sleep: ctx.sleep, signal: ctx.signal });
345
176
  }
346
177
  function isExpired(keyless, now) {
347
- const at = Date.parse(keyless.expires_at);
348
- return !Number.isNaN(at) && at <= now.getTime();
178
+ return keylessExpired(keyless, now.getTime());
349
179
  }
350
180
  async function markClaimed(ctx) {
351
- await withKeylessLock(ctx.cwd, { sleep: ctx.sleep, signal: ctx.signal }, async () => {
352
- const current = readKeyless(ctx.cwd);
181
+ await withLock(ctx.cwd, async () => {
182
+ const current = await readKeyless(ctx.cwd);
353
183
  if (!current?.claim_token) return;
354
184
  const { claim_token: _dead, ...rest } = current;
355
- writeKeyless(ctx.cwd, rest);
185
+ await writeKeylessRecord(ctx.cwd, rest);
356
186
  });
357
187
  }
358
188
  function humanDate(iso) {
@@ -381,7 +211,7 @@ function timeoutSeconds(ctx) {
381
211
  }
382
212
  async function run$3(ctx) {
383
213
  const timeout = timeoutSeconds(ctx);
384
- const keyless = readKeyless(ctx.cwd);
214
+ const keyless = await readKeyless(ctx.cwd);
385
215
  if (!keyless) {
386
216
  throw new CliError("no_unclaimed_instance", `No ${KEYLESS_FILE} here, so no unclaimed instance to claim. Run pontive init first.`);
387
217
  }
@@ -642,7 +472,7 @@ function tracked(cwd, file) {
642
472
  const result = spawnSync("git", ["ls-files", "--error-unmatch", file], { cwd, stdio: "ignore" });
643
473
  return result.status === 0;
644
474
  }
645
- function writeMcpConfig(cwd, agent, url, secretKey2) {
475
+ async function writeMcpConfig(cwd, agent, url, secretKey2) {
646
476
  const target = TARGETS[agent];
647
477
  const manual = mcpManualStep(agent, url);
648
478
  if (!target) return { written: false, agent, url, reason: "no project-level config for this agent", manual };
@@ -665,26 +495,33 @@ function writeMcpConfig(cwd, agent, url, secretKey2) {
665
495
  mkdirSync(dirname(path), { recursive: true });
666
496
  writeFileSync(path, `${JSON.stringify(config, null, 2)}
667
497
  `, { mode: 384 });
668
- return { written: true, agent, file: target.file, url, gitignore: ensureGitignore(cwd, [target.file.split("\\").join("/")]) };
498
+ return { written: true, agent, file: target.file, url, gitignore: await ensureGitignore(cwd, [target.file.split("\\").join("/")]) };
669
499
  }
670
500
  const HEADER = "Written by `pontive init`. The values come from .env.local, the PONTIVE_* variables.";
671
501
  function nextjs(project) {
672
502
  const ts = project.typescript;
673
503
  const ext = ts ? "ts" : "js";
674
504
  const base = project.srcDir ? "src/" : "";
675
- const bang = ts ? "!" : "";
676
505
  const proxyFile = (project.nextMajor ?? 0) >= 16;
677
506
  const middlewareName = proxyFile ? "proxy" : "middleware";
678
507
  const middlewarePath = `${base}${middlewareName}.${ext}`;
679
508
  const lib = `import { pontiveAuth } from "@pontive/pontkit-nextjs/server";
680
509
 
681
- // ${HEADER}
682
- export const pontive = pontiveAuth({
683
- issuer: process.env.PONTIVE_ISSUER${bang},
684
- clientId: process.env.PONTIVE_CLIENT_ID${bang},
685
- clientSecret: process.env.PONTIVE_CLIENT_SECRET,
686
- sessionSecret: process.env.PONTIVE_SESSION_SECRET,
687
- });
510
+ // Written by \`pontive init\`. Configured from .env.local, the PONTIVE_*
511
+ // variables: PONTIVE_ISSUER, PONTIVE_CLIENT_ID, PONTIVE_CLIENT_SECRET and
512
+ // PONTIVE_SESSION_SECRET. Anything passed here wins over them.
513
+ export const pontive = pontiveAuth();
514
+ `;
515
+ const provider = `"use client";
516
+
517
+ // Written by \`pontive init\`. The browser gets the app's id from the server,
518
+ // never from a public variable: render it in app/layout with
519
+ // <PontiveProvider {...await pontive.providerProps()}>{children}</PontiveProvider>
520
+ ${ts ? 'import type { ReactNode } from "react";\nimport { Provider, type ProviderProps } from "@pontive/pontkit-nextjs";' : 'import { Provider } from "@pontive/pontkit-nextjs";'}
521
+
522
+ export function PontiveProvider({ children, ...props }${ts ? ': Pick<ProviderProps, "appId" | "domain" | "claimUrl"> & { children: ReactNode }' : ""}) {
523
+ return <Provider {...props}>{children}</Provider>;
524
+ }
688
525
  `;
689
526
  const route = `// Pontive's sign-in routes: /api/auth/login, /api/auth/callback, /api/auth/logout.
690
527
  import { pontive } from "../../../../lib/pontive";
@@ -710,6 +547,7 @@ export const config = {
710
547
  files: [
711
548
  { path: `${base}lib/pontive.${ext}`, contents: lib },
712
549
  { path: `${base}app/api/auth/[...pontive]/route.${ext}`, contents: route },
550
+ { path: `${base}app/pontive-provider.${ts ? "tsx" : "jsx"}`, contents: provider },
713
551
  {
714
552
  path: middlewarePath,
715
553
  contents: middleware,
@@ -718,6 +556,7 @@ export const config = {
718
556
  }
719
557
  ],
720
558
  nextSteps: [
559
+ `In ${base}app/layout, make RootLayout async and wrap {children} in <PontiveProvider {...await pontive.providerProps()}>, importing PontiveProvider from "./pontive-provider" and pontive from "../lib/pontive".`,
721
560
  "Sign in at /api/auth/login and out at /api/auth/logout.",
722
561
  "Read the session on the server with await pontive.auth()."
723
562
  ]
@@ -750,8 +589,11 @@ import { viteAuthProxy } from "@pontive/pontkit-loader/proxy";
750
589
  export function pontive()${ts ? ": Plugin" : ""} {
751
590
  return {
752
591
  name: "pontive",
753
- config(_config, { mode }) {
754
- const env = loadEnv(mode, process.cwd(), "PONTIVE_");
592
+ config(config, { mode }) {
593
+ // Read here, on the dev server, and never handed to the browser: only
594
+ // the client id is, through define. PONTIVE_ is not an envPrefix.
595
+ const envDir = typeof config.envDir === "string" ? config.envDir : (config.root ?? process.cwd());
596
+ const env = loadEnv(mode, envDir, "PONTIVE_");
755
597
  return {
756
598
  ...(env.PONTIVE_ISSUER ? { server: { proxy: viteAuthProxy({ authHost: env.PONTIVE_ISSUER }) } } : {}),
757
599
  define: { "import.meta.env.PONTIVE_CLIENT_ID": JSON.stringify(env.PONTIVE_CLIENT_ID ?? "") },
@@ -790,12 +632,8 @@ try {
790
632
  // No .env.local: the variables come from the environment.
791
633
  }
792
634
 
793
- ${exp}const pontive = createServerAuth({
794
- issuer: process.env.PONTIVE_ISSUER${t("!")},
795
- clientId: process.env.PONTIVE_CLIENT_ID${t("!")},
796
- clientSecret: process.env.PONTIVE_CLIENT_SECRET,
797
- sessionSecret: process.env.PONTIVE_SESSION_SECRET,
798
- });
635
+ // Configured from the PONTIVE_* variables; anything passed here wins over them.
636
+ ${exp}const pontive = createServerAuth();
799
637
  ${t("\ntype Next = (error?: unknown) => void;\n")}
800
638
  function toRequest(req${t(": IncomingMessage")})${t(": Request")} {
801
639
  const headers = new Headers();
@@ -948,15 +786,10 @@ async function provision(ctx, project, plan) {
948
786
  return { response, secrets };
949
787
  }
950
788
  const REPLACED_ON_RESET = /* @__PURE__ */ new Set(["PONTIVE_ISSUER", "PONTIVE_CLIENT_ID", "PONTIVE_CLIENT_SECRET", "PONTIVE_SECRET_KEY", "PONTIVE_INSTANCE_ID"]);
951
- function envEntries(response, secrets) {
952
- return [
953
- ["PONTIVE_ISSUER", response.issuer],
954
- ["PONTIVE_CLIENT_ID", response.app_id],
955
- ...secrets.client_secret ? [["PONTIVE_CLIENT_SECRET", secrets.client_secret]] : [],
956
- ...secrets.client_secret ? [["PONTIVE_SESSION_SECRET", sessionSecret()]] : [],
957
- ["PONTIVE_SECRET_KEY", secrets.secret_key],
958
- ["PONTIVE_INSTANCE_ID", response.instance_id]
959
- ];
789
+ function envVars(response, secrets, envFile) {
790
+ const vars = envVarsFor({ ...response, ...secrets }, envFile.get("PONTIVE_SESSION_SECRET") || generateSessionSecret());
791
+ if (!secrets.client_secret) delete vars.PONTIVE_SESSION_SECRET;
792
+ return vars;
960
793
  }
961
794
  async function connectMcp(ctx, secretKey2, region, nextSteps2) {
962
795
  if (ctx.values["no-mcp"] === true || !secretKey2 || !region) return null;
@@ -977,7 +810,7 @@ async function connectMcp(ctx, secretKey2, region, nextSteps2) {
977
810
  nextSteps2.push(ctx.agentMode ? `Run pontive init --yes to write the Pontive MCP server to ${file}.` : mcpManualStep(agent, url));
978
811
  return { agent, written: false, file, url, reason: ctx.agentMode ? "needs --yes" : "declined" };
979
812
  }
980
- const result = writeMcpConfig(ctx.cwd, agent, url, secretKey2);
813
+ const result = await writeMcpConfig(ctx.cwd, agent, url, secretKey2);
981
814
  if (!result.written) {
982
815
  nextSteps2.push(result.manual);
983
816
  return { agent, written: false, file: result.file, url, reason: result.reason };
@@ -993,7 +826,7 @@ async function run$2(ctx) {
993
826
  if (reset && !await confirm(ctx, "Provision a new unclaimed instance and point .env.local at it? The current instance is left to expire.")) {
994
827
  throw cancelled(ctx.agentMode ? "init --reset provisions a new instance; pass --yes to confirm." : "Cancelled.");
995
828
  }
996
- const existing = readKeyless(ctx.cwd);
829
+ const existing = await readKeyless(ctx.cwd);
997
830
  if (!reset && existing?.claim_token && isExpired(existing, ctx.now())) {
998
831
  throw new CliError(
999
832
  "instance_expired",
@@ -1005,8 +838,8 @@ async function run$2(ctx) {
1005
838
  const installed = await install(ctx, project, plan);
1006
839
  const files = writeScaffold(ctx.cwd, plan.files);
1007
840
  for (const skipped of files.skipped) if (skipped.manual) nextSteps2.push(skipped.manual);
1008
- const gitignore = ensureGitignore(ctx.cwd, [ENV_FILE, `${PONTIVE_DIR}/`]);
1009
- const envFile = readEnvFile(ctx.cwd);
841
+ const gitignore = await ensureGitignore(ctx.cwd, GITIGNORE_ENTRIES);
842
+ const envFile = await readEnvLocal(ctx.cwd);
1010
843
  const configuredIssuer = envFile.get("PONTIVE_ISSUER") || ctx.env.PONTIVE_ISSUER;
1011
844
  let instance;
1012
845
  let env = { added: [], kept: [], replaced: [] };
@@ -1025,8 +858,8 @@ async function run$2(ctx) {
1025
858
  } else {
1026
859
  const login = await loadLogin(ctx.env);
1027
860
  if (login) throw new CliError("not_supported", "Signed-in init is not supported by this version of the CLI.");
1028
- const provisioned = await withKeylessLock(ctx.cwd, { sleep: ctx.sleep, signal: ctx.signal }, async () => {
1029
- const raced = reset ? null : readKeyless(ctx.cwd);
861
+ const provisioned = await withLock(ctx.cwd, async () => {
862
+ const raced = reset ? null : await readKeyless(ctx.cwd);
1030
863
  if (raced) return { kind: "raced", keyless: raced };
1031
864
  const { response, secrets } = await provision(ctx, project, plan);
1032
865
  const keyless = {
@@ -1037,8 +870,11 @@ async function run$2(ctx) {
1037
870
  expires_at: response.expires_at,
1038
871
  region: response.region
1039
872
  };
1040
- writeKeyless(ctx.cwd, keyless);
1041
- const written = writeEnv(ctx.cwd, envEntries(response, secrets), reset ? REPLACED_ON_RESET : /* @__PURE__ */ new Set());
873
+ await writeKeylessRecord(ctx.cwd, keyless);
874
+ const written = await writeEnv(ctx.cwd, envVars(response, secrets, envFile), {
875
+ replace: reset ? REPLACED_ON_RESET : void 0,
876
+ comment: `Pontive: unclaimed development instance ${response.instance_id}, deleted ${response.expires_at} unless claimed`
877
+ });
1042
878
  return { kind: "new", keyless, env: written, secretKey: secrets.secret_key };
1043
879
  });
1044
880
  const k = provisioned.keyless;
@@ -3249,8 +3085,8 @@ const __vite_glob_0_2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.def
3249
3085
  command: migrate
3250
3086
  }, Symbol.toStringTag, { value: "Module" }));
3251
3087
  async function run$1(ctx) {
3252
- const keyless = readKeyless(ctx.cwd);
3253
- const envFile = readEnvFile(ctx.cwd);
3088
+ const keyless = await readKeyless(ctx.cwd);
3089
+ const envFile = await readEnvLocal(ctx.cwd);
3254
3090
  const set = CONTRACT_VARIABLES.filter((name) => Boolean(envFile.get(name) || ctx.env[name]));
3255
3091
  const missing = CONTRACT_VARIABLES.filter((name) => !set.includes(name));
3256
3092
  const variables = { set, missing };
@@ -3286,7 +3122,7 @@ async function run$1(ctx) {
3286
3122
  const expiresAt = state === "unclaimed" || state === "expired" ? live?.expires_at ?? keyless?.expires_at : void 0;
3287
3123
  const instance = state === "none" ? null : {
3288
3124
  instance_id: instanceId ?? null,
3289
- region: live?.region ?? keyless?.region ?? null,
3125
+ region: (typeof live?.region === "string" ? live.region : void 0) ?? keyless?.region ?? null,
3290
3126
  issuer: issuer ?? null,
3291
3127
  app_id: keyless?.app_id ?? envFile.get("PONTIVE_CLIENT_ID") ?? null,
3292
3128
  status: state,
@@ -3524,9 +3360,8 @@ function nodeRuntime(agentMode) {
3524
3360
  now: () => /* @__PURE__ */ new Date()
3525
3361
  };
3526
3362
  }
3527
- const [major] = process.versions.node.split(".").map(Number);
3528
- if (major < 20) {
3529
- process.stderr.write(`pontive needs Node.js 20 or later; this is ${process.versions.node}.
3363
+ if (typeof process.getBuiltinModule !== "function") {
3364
+ process.stderr.write(`pontive needs Node.js 20.16 or later; this is ${process.versions.node}.
3530
3365
  `);
3531
3366
  process.exit(1);
3532
3367
  }
@@ -3539,6 +3374,6 @@ const code = await main({
3539
3374
  out: streamOutput(process.stdout, process.stderr),
3540
3375
  runtime: nodeRuntime,
3541
3376
  signal: controller.signal,
3542
- version: "1.19.0"
3377
+ version: "1.20.0"
3543
3378
  });
3544
3379
  process.exitCode = code;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pontive",
3
- "version": "1.19.0",
3
+ "version": "1.20.0",
4
4
  "license": "MIT",
5
5
  "description": "The Pontive CLI: add Pontive sign-in to an app, with or without an account.",
6
6
  "type": "module",
@@ -11,7 +11,7 @@
11
11
  "dist"
12
12
  ],
13
13
  "engines": {
14
- "node": ">=20"
14
+ "node": ">=20.16"
15
15
  },
16
16
  "scripts": {
17
17
  "build": "vite build",
@@ -22,6 +22,7 @@
22
22
  "access": "public"
23
23
  },
24
24
  "dependencies": {
25
+ "@pontive/pontkit-server": "^1.20.0",
25
26
  "jose": "^6.2.3"
26
27
  }
27
28
  }