@pontive/server 0.0.0-stage → 1.23.1
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 +146 -2
- package/dist/auth.d.cts +34 -0
- package/dist/auth.d.ts +34 -0
- package/dist/authorization.cjs +2 -0
- package/dist/authorization.cjs.map +1 -0
- package/dist/authorization.d.cts +222 -0
- package/dist/authorization.d.ts +222 -0
- package/dist/authorization.js +153 -0
- package/dist/authorization.js.map +1 -0
- package/dist/browser-mode.d.cts +23 -0
- package/dist/browser-mode.d.ts +23 -0
- package/dist/config.d.cts +131 -0
- package/dist/config.d.ts +131 -0
- package/dist/cookies.d.cts +50 -0
- package/dist/cookies.d.ts +50 -0
- package/dist/env.d.cts +44 -0
- package/dist/env.d.ts +44 -0
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +20 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +700 -0
- package/dist/index.js.map +1 -0
- package/dist/keyless.cjs +16 -0
- package/dist/keyless.cjs.map +1 -0
- package/dist/keyless.d.cts +244 -0
- package/dist/keyless.d.ts +244 -0
- package/dist/keyless.js +355 -0
- package/dist/keyless.js.map +1 -0
- package/dist/management-credential-BNyhHagG.cjs +2 -0
- package/dist/management-credential-BNyhHagG.cjs.map +1 -0
- package/dist/management-credential-VhmMzGDl.js +39 -0
- package/dist/management-credential-VhmMzGDl.js.map +1 -0
- package/dist/management-credential.d.cts +40 -0
- package/dist/management-credential.d.ts +40 -0
- package/dist/mcp-auth-info-BGyWua_9.js +19 -0
- package/dist/mcp-auth-info-BGyWua_9.js.map +1 -0
- package/dist/mcp-auth-info-jblMsSJo.cjs +2 -0
- package/dist/mcp-auth-info-jblMsSJo.cjs.map +1 -0
- package/dist/mcp-auth-info.d.cts +17 -0
- package/dist/mcp-auth-info.d.ts +17 -0
- package/dist/oidc--We55Nrh.cjs +2 -0
- package/dist/oidc--We55Nrh.cjs.map +1 -0
- package/dist/oidc-CB0FqjFz.js +131 -0
- package/dist/oidc-CB0FqjFz.js.map +1 -0
- package/dist/oidc.d.cts +80 -0
- package/dist/oidc.d.ts +80 -0
- package/dist/organization.d.cts +35 -0
- package/dist/organization.d.ts +35 -0
- package/dist/preview-hosts.d.cts +33 -0
- package/dist/preview-hosts.d.ts +33 -0
- package/dist/refresh.d.cts +28 -0
- package/dist/refresh.d.ts +28 -0
- package/dist/resource-server-express.cjs +2 -0
- package/dist/resource-server-express.cjs.map +1 -0
- package/dist/resource-server-express.d.cts +73 -0
- package/dist/resource-server-express.d.ts +73 -0
- package/dist/resource-server-express.js +57 -0
- package/dist/resource-server-express.js.map +1 -0
- package/dist/resource-server-mcp.cjs +2 -0
- package/dist/resource-server-mcp.cjs.map +1 -0
- package/dist/resource-server-mcp.d.cts +70 -0
- package/dist/resource-server-mcp.d.ts +70 -0
- package/dist/resource-server-mcp.js +59 -0
- package/dist/resource-server-mcp.js.map +1 -0
- package/dist/resource-server.cjs +2 -0
- package/dist/resource-server.cjs.map +1 -0
- package/dist/resource-server.d.cts +290 -0
- package/dist/resource-server.d.ts +290 -0
- package/dist/resource-server.js +301 -0
- package/dist/resource-server.js.map +1 -0
- package/dist/seal.d.cts +3 -0
- package/dist/seal.d.ts +3 -0
- package/dist/server-auth.d.cts +100 -0
- package/dist/server-auth.d.ts +100 -0
- package/package.json +96 -4
package/dist/keyless.js
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
const b = "https://api.pontive.com", $ = ".pontive", f = ".pontive/keyless.json", y = ".pontive/keyless.lock", E = ".env.local", C = [".env.local", ".pontive/"], R = "https://www.pontive.com/docs/unclaimed-instances";
|
|
2
|
+
class k extends Error {
|
|
3
|
+
status;
|
|
4
|
+
/** The envelope's `code` (`unclaimed_instance_limit`, `instance_claimed` …), when it had one. */
|
|
5
|
+
code;
|
|
6
|
+
/** Seconds, from `Retry-After`, when the API sent one. */
|
|
7
|
+
retryAfter;
|
|
8
|
+
constructor(t, i, a, s) {
|
|
9
|
+
super(a), this.name = "PontiveApiError", this.status = t, this.code = i, this.retryAfter = s;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function w(e) {
|
|
13
|
+
const t = globalThis.process?.env;
|
|
14
|
+
return (e.apiUrl || t?.PONTIVE_API_URL?.trim() || b).replace(/\/+$/, "");
|
|
15
|
+
}
|
|
16
|
+
async function _(e) {
|
|
17
|
+
let t, i = `HTTP ${e.status}`;
|
|
18
|
+
try {
|
|
19
|
+
const s = await e.json(), n = s?.error ?? s;
|
|
20
|
+
typeof n?.code == "string" && (t = n.code), typeof n?.message == "string" && (i = n.message);
|
|
21
|
+
} catch {
|
|
22
|
+
}
|
|
23
|
+
const a = Number(e.headers.get("retry-after"));
|
|
24
|
+
return new k(e.status, t, i, Number.isFinite(a) && a > 0 ? a : void 0);
|
|
25
|
+
}
|
|
26
|
+
const V = (e) => e === 500 || e === 502 || e === 504;
|
|
27
|
+
async function j(e, t = {}) {
|
|
28
|
+
const i = t.fetch ?? ((...r) => fetch(...r)), a = t.idempotencyKey ?? crypto.randomUUID(), s = () => i(`${w(t)}/v1/unclaimed-instances`, {
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: { "content-type": "application/json", accept: "application/json", "x-idempotency-key": a },
|
|
31
|
+
body: JSON.stringify(e)
|
|
32
|
+
});
|
|
33
|
+
let n;
|
|
34
|
+
try {
|
|
35
|
+
n = await s(), V(n.status) && (n = await s());
|
|
36
|
+
} catch {
|
|
37
|
+
n = await s();
|
|
38
|
+
}
|
|
39
|
+
if (n.status !== 201 && n.status !== 200) throw await _(n);
|
|
40
|
+
return await n.json();
|
|
41
|
+
}
|
|
42
|
+
async function L(e, t, i = {}) {
|
|
43
|
+
const s = await (i.fetch ?? ((...n) => fetch(...n)))(`${w(i)}/v1/unclaimed-instances/${encodeURIComponent(e)}/claim-links`, {
|
|
44
|
+
method: "POST",
|
|
45
|
+
headers: { accept: "application/json", "x-pontive-claim-token": t }
|
|
46
|
+
});
|
|
47
|
+
if (s.status !== 201 && s.status !== 200) throw await _(s);
|
|
48
|
+
return await s.json();
|
|
49
|
+
}
|
|
50
|
+
async function J(e, t, i = {}) {
|
|
51
|
+
const s = await (i.fetch ?? ((...n) => fetch(...n)))(`${w(i)}/v1/unclaimed-instances/${encodeURIComponent(e)}`, {
|
|
52
|
+
method: "GET",
|
|
53
|
+
headers: { accept: "application/json", "x-pontive-claim-token": t }
|
|
54
|
+
});
|
|
55
|
+
if (!s.ok) throw await _(s);
|
|
56
|
+
return await s.json();
|
|
57
|
+
}
|
|
58
|
+
class v extends Error {
|
|
59
|
+
constructor(t = "keyless mode needs Node.js 20.16 or later (process.getBuiltinModule); this runtime has no file system") {
|
|
60
|
+
super(`@pontive/server: ${t}`), this.name = "KeylessUnavailableError";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
class I extends Error {
|
|
64
|
+
record;
|
|
65
|
+
constructor(t, i) {
|
|
66
|
+
super(i), this.name = "KeylessInstanceGoneError", this.record = t;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function p() {
|
|
70
|
+
const e = globalThis.process;
|
|
71
|
+
if (typeof e?.getBuiltinModule != "function") throw new v();
|
|
72
|
+
const t = e.getBuiltinModule("node:fs/promises"), i = e.getBuiltinModule("node:path");
|
|
73
|
+
if (!t || !i) throw new v();
|
|
74
|
+
return { fs: t, path: i };
|
|
75
|
+
}
|
|
76
|
+
const h = (e) => e?.code === "ENOENT";
|
|
77
|
+
async function g(e) {
|
|
78
|
+
const { fs: t, path: i } = p();
|
|
79
|
+
let a;
|
|
80
|
+
try {
|
|
81
|
+
a = await t.readFile(i.join(e, f), "utf8");
|
|
82
|
+
} catch (n) {
|
|
83
|
+
if (h(n)) return null;
|
|
84
|
+
throw n;
|
|
85
|
+
}
|
|
86
|
+
const s = JSON.parse(a);
|
|
87
|
+
for (const n of ["instance_id", "issuer", "app_id", "expires_at"])
|
|
88
|
+
if (typeof s[n] != "string" || !s[n])
|
|
89
|
+
throw new Error(`@pontive/server: ${f} has no ${n}; run \`npx pontive init --reset\``);
|
|
90
|
+
return s;
|
|
91
|
+
}
|
|
92
|
+
async function M(e, t) {
|
|
93
|
+
const { fs: i, path: a } = p();
|
|
94
|
+
await i.mkdir(a.join(e, $), { recursive: !0 });
|
|
95
|
+
const s = a.join(e, f), n = {
|
|
96
|
+
instance_id: t.instance_id,
|
|
97
|
+
issuer: t.issuer,
|
|
98
|
+
app_id: t.app_id,
|
|
99
|
+
...t.claim_token ? { claim_token: t.claim_token } : {},
|
|
100
|
+
expires_at: t.expires_at,
|
|
101
|
+
region: t.region
|
|
102
|
+
};
|
|
103
|
+
await i.writeFile(s, `${JSON.stringify(n, null, 2)}
|
|
104
|
+
`, { encoding: "utf8", mode: 384 }), await i.chmod(s, 384).catch(() => {
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
function S(e, t = Date.now()) {
|
|
108
|
+
const i = Date.parse(e.expires_at);
|
|
109
|
+
return Number.isNaN(i) || i <= t;
|
|
110
|
+
}
|
|
111
|
+
function O(e) {
|
|
112
|
+
const t = /* @__PURE__ */ new Map();
|
|
113
|
+
for (const i of e.split(/\r?\n/)) {
|
|
114
|
+
const a = i.trim();
|
|
115
|
+
if (!a || a.startsWith("#")) continue;
|
|
116
|
+
const s = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(a);
|
|
117
|
+
if (!s) continue;
|
|
118
|
+
let n = s[2];
|
|
119
|
+
const r = n[0], l = r === '"' || r === "'" ? n.indexOf(r, 1) : -1;
|
|
120
|
+
l > 0 ? n = n.slice(1, l) : n = n.replace(/\s+#.*$/, ""), t.set(s[1], n);
|
|
121
|
+
}
|
|
122
|
+
return t;
|
|
123
|
+
}
|
|
124
|
+
async function P(e) {
|
|
125
|
+
const { fs: t, path: i } = p();
|
|
126
|
+
try {
|
|
127
|
+
return O(await t.readFile(i.join(e, E), "utf8"));
|
|
128
|
+
} catch (a) {
|
|
129
|
+
if (h(a)) return /* @__PURE__ */ new Map();
|
|
130
|
+
throw a;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async function U(e, t, i = {}) {
|
|
134
|
+
const { fs: a, path: s } = p(), n = s.join(e, E);
|
|
135
|
+
let r = "";
|
|
136
|
+
try {
|
|
137
|
+
r = await a.readFile(n, "utf8");
|
|
138
|
+
} catch (c) {
|
|
139
|
+
if (!h(c)) throw c;
|
|
140
|
+
}
|
|
141
|
+
const l = O(r), o = [], d = [], u = [];
|
|
142
|
+
for (const [c, m] of Object.entries(t))
|
|
143
|
+
if (m !== void 0) {
|
|
144
|
+
if (l.has(c)) {
|
|
145
|
+
d.push(c);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
u.push(`${c}=${m}`), o.push(c);
|
|
149
|
+
}
|
|
150
|
+
if (u.length > 0) {
|
|
151
|
+
const c = r && !r.endsWith(`
|
|
152
|
+
`) ? `
|
|
153
|
+
` : "", m = r.trim() ? `
|
|
154
|
+
` : "", x = i.comment ? `# ${i.comment}
|
|
155
|
+
` : "";
|
|
156
|
+
await a.appendFile(n, `${c}${m}${x}${u.join(`
|
|
157
|
+
`)}
|
|
158
|
+
`, { encoding: "utf8", mode: 384 });
|
|
159
|
+
}
|
|
160
|
+
return { written: o, skipped: d };
|
|
161
|
+
}
|
|
162
|
+
function D(e, t) {
|
|
163
|
+
const i = t.replace(/\/$/, ""), a = t === ".env.local" ? [".env.local", "/.env.local", ".env*.local", "/.env*.local", ".env*", "/.env*", "*.local"] : [i, `/${i}`, `${i}/`, `/${i}/`, `${i}/*`, `/${i}/*`];
|
|
164
|
+
return e.some((s) => a.includes(s.trim()));
|
|
165
|
+
}
|
|
166
|
+
async function K(e, t = C) {
|
|
167
|
+
const { fs: i, path: a } = p(), s = a.join(e, ".gitignore");
|
|
168
|
+
let n = "";
|
|
169
|
+
try {
|
|
170
|
+
n = await i.readFile(s, "utf8");
|
|
171
|
+
} catch (o) {
|
|
172
|
+
if (!h(o)) throw o;
|
|
173
|
+
}
|
|
174
|
+
const r = n.split(/\r?\n/), l = t.filter((o) => !D(r, o));
|
|
175
|
+
if (l.length > 0) {
|
|
176
|
+
const o = n && !n.endsWith(`
|
|
177
|
+
`) ? `
|
|
178
|
+
` : "";
|
|
179
|
+
await i.appendFile(s, `${o}${n.trim() ? `
|
|
180
|
+
` : ""}# Pontive keyless mode: secrets and the claim token
|
|
181
|
+
${l.join(`
|
|
182
|
+
`)}
|
|
183
|
+
`, "utf8");
|
|
184
|
+
}
|
|
185
|
+
return l;
|
|
186
|
+
}
|
|
187
|
+
function F() {
|
|
188
|
+
const e = crypto.getRandomValues(new Uint8Array(32));
|
|
189
|
+
let t = "";
|
|
190
|
+
for (const i of e) t += String.fromCharCode(i);
|
|
191
|
+
return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
192
|
+
}
|
|
193
|
+
const A = (e) => new Promise((t) => setTimeout(t, e));
|
|
194
|
+
async function G(e, t, i = {}) {
|
|
195
|
+
const { fs: a, path: s } = p(), n = i.timeoutMs ?? 6e4, r = i.staleMs ?? 12e4, l = i.pollMs ?? 200;
|
|
196
|
+
await a.mkdir(s.join(e, $), { recursive: !0 });
|
|
197
|
+
const o = s.join(e, y), d = Date.now();
|
|
198
|
+
for (; ; )
|
|
199
|
+
try {
|
|
200
|
+
const u = await a.open(o, "wx");
|
|
201
|
+
try {
|
|
202
|
+
const c = globalThis.process?.pid;
|
|
203
|
+
await u.writeFile(JSON.stringify({ pid: c, created_at: (/* @__PURE__ */ new Date()).toISOString() }));
|
|
204
|
+
} finally {
|
|
205
|
+
await u.close();
|
|
206
|
+
}
|
|
207
|
+
break;
|
|
208
|
+
} catch (u) {
|
|
209
|
+
if (u.code !== "EEXIST") throw u;
|
|
210
|
+
const c = await a.stat(o).catch(() => null);
|
|
211
|
+
if (c && Date.now() - c.mtimeMs > r) {
|
|
212
|
+
await a.rm(o, { force: !0 });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (Date.now() - d > n)
|
|
216
|
+
throw new Error(`@pontive/server: ${y} is held by another process; remove it if nothing is provisioning`);
|
|
217
|
+
await A(l);
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
return await t();
|
|
221
|
+
} finally {
|
|
222
|
+
await a.rm(o, { force: !0 }).catch(() => {
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
function B(e, t) {
|
|
227
|
+
return {
|
|
228
|
+
PONTIVE_ISSUER: e.issuer,
|
|
229
|
+
PONTIVE_CLIENT_ID: e.app_id,
|
|
230
|
+
PONTIVE_CLIENT_SECRET: e.client_secret,
|
|
231
|
+
PONTIVE_SESSION_SECRET: t,
|
|
232
|
+
PONTIVE_SECRET_KEY: e.secret_key,
|
|
233
|
+
PONTIVE_INSTANCE_ID: e.instance_id
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
function W(e = "/api/auth") {
|
|
237
|
+
const t = `${e.replace(/\/+$/, "")}/callback`;
|
|
238
|
+
return [`http://localhost${t}`, `http://127.0.0.1${t}`];
|
|
239
|
+
}
|
|
240
|
+
async function T(e, t) {
|
|
241
|
+
const i = await P(e), a = globalThis.process?.env ?? {}, s = (n) => a[n]?.trim() || i.get(n) || void 0;
|
|
242
|
+
return {
|
|
243
|
+
record: t,
|
|
244
|
+
created: !1,
|
|
245
|
+
env: {
|
|
246
|
+
PONTIVE_ISSUER: t.issuer,
|
|
247
|
+
PONTIVE_CLIENT_ID: t.app_id,
|
|
248
|
+
PONTIVE_CLIENT_SECRET: s("PONTIVE_CLIENT_SECRET"),
|
|
249
|
+
PONTIVE_SESSION_SECRET: s("PONTIVE_SESSION_SECRET"),
|
|
250
|
+
PONTIVE_SECRET_KEY: s("PONTIVE_SECRET_KEY"),
|
|
251
|
+
PONTIVE_INSTANCE_ID: t.instance_id
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function N(e, t) {
|
|
256
|
+
const i = t === "expired" ? `expired on ${e.expires_at} and Pontive deleted it, with its users` : "refused its credentials (401): it expired, or was claimed and its keys rotated";
|
|
257
|
+
return `@pontive/server: the unclaimed Pontive instance in ${f} (${e.instance_id}) ${i}. Pontive does not create a new one over it, since the new one would have none of its users. Run \`npx pontive init --reset\` to create another, or set PONTIVE_ISSUER for an instance of your own.`;
|
|
258
|
+
}
|
|
259
|
+
async function Z(e) {
|
|
260
|
+
const t = e.reset ? null : await g(e.dir);
|
|
261
|
+
if (t) {
|
|
262
|
+
if (S(t)) throw new I(t, N(t, "expired"));
|
|
263
|
+
return T(e.dir, t);
|
|
264
|
+
}
|
|
265
|
+
return G(
|
|
266
|
+
e.dir,
|
|
267
|
+
async () => {
|
|
268
|
+
const i = e.reset ? null : await g(e.dir);
|
|
269
|
+
if (i) {
|
|
270
|
+
if (S(i)) throw new I(i, N(i, "expired"));
|
|
271
|
+
return T(e.dir, i);
|
|
272
|
+
}
|
|
273
|
+
const a = globalThis.process?.env ?? {}, s = e.region || a.PONTIVE_REGION?.trim() || void 0, n = await j(
|
|
274
|
+
{
|
|
275
|
+
...e.name ? { name: e.name } : {},
|
|
276
|
+
...s ? { region: s } : {},
|
|
277
|
+
...e.tenancyMode ? { tenancy_mode: e.tenancyMode } : {},
|
|
278
|
+
app: { type: "web", ...e.app, redirect_uris: e.app?.redirect_uris ?? e.redirectUris },
|
|
279
|
+
client: e.client
|
|
280
|
+
},
|
|
281
|
+
e
|
|
282
|
+
);
|
|
283
|
+
if (!n.claim_token)
|
|
284
|
+
throw new Error("@pontive/server: the unclaimed instance came back without a claim token");
|
|
285
|
+
const r = await P(e.dir), l = a.PONTIVE_SESSION_SECRET?.trim() || r.get("PONTIVE_SESSION_SECRET") || F(), o = B(n, l);
|
|
286
|
+
await K(e.dir), await U(e.dir, o, {
|
|
287
|
+
comment: `Pontive: unclaimed development instance ${n.instance_id}, deleted ${n.expires_at} unless claimed`
|
|
288
|
+
});
|
|
289
|
+
const d = {
|
|
290
|
+
instance_id: n.instance_id,
|
|
291
|
+
issuer: n.issuer,
|
|
292
|
+
app_id: n.app_id,
|
|
293
|
+
claim_token: n.claim_token,
|
|
294
|
+
expires_at: n.expires_at,
|
|
295
|
+
region: n.region
|
|
296
|
+
};
|
|
297
|
+
return await M(e.dir, d), { record: d, env: o, created: !0 };
|
|
298
|
+
},
|
|
299
|
+
e.lock
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
async function z(e, t = {}) {
|
|
303
|
+
if (!e.claim_token)
|
|
304
|
+
throw new k(409, "instance_claimed", "this instance was claimed; its claim token is gone");
|
|
305
|
+
return L(e.instance_id, e.claim_token, t);
|
|
306
|
+
}
|
|
307
|
+
function Y(e) {
|
|
308
|
+
const t = new Date(e);
|
|
309
|
+
return Number.isNaN(t.getTime()) ? e : t.toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
|
|
310
|
+
}
|
|
311
|
+
function q(e, t = {}) {
|
|
312
|
+
const i = [
|
|
313
|
+
t.created ? "Pontive: created an unclaimed development instance" : "Pontive: using an unclaimed development instance",
|
|
314
|
+
"",
|
|
315
|
+
`Instance ${e.instance_id} (${e.region})`,
|
|
316
|
+
`Deleted ${Y(e.expires_at)}, with its users, unless claimed`,
|
|
317
|
+
"Claim it npx pontive claim, or Claim it in the app's banner",
|
|
318
|
+
`Settings ${E} and ${f} (both gitignored)`,
|
|
319
|
+
`More ${R}`
|
|
320
|
+
], a = Math.max(...i.map((n) => n.length)), s = "─".repeat(a + 2);
|
|
321
|
+
return [`┌${s}┐`, ...i.map((n) => `│ ${n.padEnd(a)} │`), `└${s}┘`].join(`
|
|
322
|
+
`);
|
|
323
|
+
}
|
|
324
|
+
export {
|
|
325
|
+
b as DEFAULT_API_URL,
|
|
326
|
+
E as ENV_FILE,
|
|
327
|
+
C as GITIGNORE_ENTRIES,
|
|
328
|
+
$ as KEYLESS_DIR,
|
|
329
|
+
f as KEYLESS_FILE,
|
|
330
|
+
y as KEYLESS_LOCK,
|
|
331
|
+
I as KeylessInstanceGoneError,
|
|
332
|
+
v as KeylessUnavailableError,
|
|
333
|
+
k as PontiveApiError,
|
|
334
|
+
R as UNCLAIMED_DOCS_URL,
|
|
335
|
+
U as appendEnvLocal,
|
|
336
|
+
z as claimLinkFor,
|
|
337
|
+
L as createClaimLink,
|
|
338
|
+
j as createUnclaimedInstance,
|
|
339
|
+
K as ensureGitignore,
|
|
340
|
+
Z as ensureKeylessInstance,
|
|
341
|
+
B as envVarsFor,
|
|
342
|
+
F as generateSessionSecret,
|
|
343
|
+
J as getUnclaimedInstance,
|
|
344
|
+
N as goneMessage,
|
|
345
|
+
S as keylessExpired,
|
|
346
|
+
q as keylessMessage,
|
|
347
|
+
W as loopbackCallbacks,
|
|
348
|
+
p as nodeApis,
|
|
349
|
+
O as parseEnvFile,
|
|
350
|
+
P as readEnvLocal,
|
|
351
|
+
g as readKeylessRecord,
|
|
352
|
+
G as withKeylessLock,
|
|
353
|
+
M as writeKeylessRecord
|
|
354
|
+
};
|
|
355
|
+
//# sourceMappingURL=keyless.js.map
|
|
@@ -0,0 +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","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,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EAAO;AACV,UAAM,IAAIzB,EAAgB,KAAK,oBAAoB,oDAAoD;AAEzG,SAAOmB,EAAgBM,EAAO,aAAaA,EAAO,aAAanB,CAAO;AACxE;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;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const i=require("./oidc--We55Nrh.cjs");function s(n){const e=n.trim();let r=e;try{const t=new URL(e);r=`${t.origin}${t.pathname}`}catch{}return r.replace(/\/+$/,"").replace(/\/(mgmt(\/v1)?|v1)$/,"")}function c(n){const e=n.trim();try{return new URL(e).origin}catch{return e.replace(/\/+$/,"")}}function o(n){const{credential:e,managementUrl:r}=n;let t;return async()=>{if(typeof e=="string")return e;if(typeof e=="function")return e();if(t&&Date.now()<t.until)return t.value;if(!n.issuer)throw new Error("pontive: client credentials need the issuer to exchange them at");const a=await i.clientCredentialsToken({issuer:n.issuer,...e},n.fetch,{resource:c(r)});return t={value:a.access_token,until:Date.now()+((a.expires_in??300)-60)*1e3},a.access_token}}exports.managementAudience=c;exports.managementBase=s;exports.managementTokenSource=o;
|
|
2
|
+
//# sourceMappingURL=management-credential-BNyhHagG.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"management-credential-BNyhHagG.cjs","sources":["../src/management-credential.ts"],"sourcesContent":["import { clientCredentialsToken } from \"./oidc\";\n\n/**\n * How a server gets a management API token: a token, a function returning\n * one, or the client credentials of a service account (exchanged at the\n * issuer for a management-audience token, and reused until it is about to\n * expire).\n */\nexport type ManagementCredential =\n | string\n | (() => string | Promise<string>)\n | { clientId: string; clientSecret: string };\n\n/**\n * The management API's base for a configured `managementUrl`: its origin and\n * any gateway path, without a trailing slash and without a `/v1`, `/mgmt` or\n * `/mgmt/v1` suffix (as pontkit-core and oidc-client read `apiBaseUrl`). The\n * routes are built on it (`{base}/v1/…`, api-route-review D12), so\n * `https://api.us.pontive.com` and `…/v1` configure the same API. Query and\n * fragment are dropped.\n */\nexport function managementBase(managementUrl: string): string {\n const raw = managementUrl.trim();\n let base = raw;\n try {\n const url = new URL(raw);\n base = `${url.origin}${url.pathname}`;\n } catch {\n // Not an absolute URL: trimmed as given.\n }\n return base.replace(/\\/+$/, \"\").replace(/\\/(mgmt(\\/v1)?|v1)$/, \"\");\n}\n\n/**\n * The management API's audience for a configured `managementUrl`: its origin,\n * `https://api.us.pontive.com`, with no path and no trailing slash, whatever\n * path the URL carries (api-route-review D51; pontive-core's\n * `directory.ManagementAudience` and oidc-client's `managementAudience()`\n * derive it the same way). A value that is not an absolute URL is returned\n * trimmed, so the token request fails visibly.\n */\nexport function managementAudience(managementUrl: string): string {\n const raw = managementUrl.trim();\n try {\n return new URL(raw).origin;\n } catch {\n return raw.replace(/\\/+$/, \"\");\n }\n}\n\n/**\n * A function that returns a management API bearer token for `credential`.\n * Client credentials are exchanged at `issuer` for the management API's\n * audience (`managementAudience(managementUrl)`) and the token is reused until\n * a minute before it expires.\n */\nexport function managementTokenSource(input: {\n credential: ManagementCredential;\n managementUrl: string;\n issuer?: string;\n fetch: typeof fetch;\n}): () => Promise<string> {\n const { credential, managementUrl } = input;\n let cached: { value: string; until: number } | undefined;\n\n return async () => {\n if (typeof credential === \"string\") return credential;\n if (typeof credential === \"function\") return credential();\n if (cached && Date.now() < cached.until) return cached.value;\n if (!input.issuer) throw new Error(\"pontive: client credentials need the issuer to exchange them at\");\n\n const res = await clientCredentialsToken({ issuer: input.issuer, ...credential }, input.fetch, {\n resource: managementAudience(managementUrl),\n });\n cached = { value: res.access_token, until: Date.now() + ((res.expires_in ?? 300) - 60) * 1000 };\n return res.access_token;\n };\n}\n"],"names":["managementBase","managementUrl","raw","base","url","managementAudience","managementTokenSource","input","credential","cached","res","clientCredentialsToken"],"mappings":"oDAqBO,SAASA,EAAeC,EAA+B,CAC5D,MAAMC,EAAMD,EAAc,KAAA,EAC1B,IAAIE,EAAOD,EACX,GAAI,CACF,MAAME,EAAM,IAAI,IAAIF,CAAG,EACvBC,EAAO,GAAGC,EAAI,MAAM,GAAGA,EAAI,QAAQ,EACrC,MAAQ,CAER,CACA,OAAOD,EAAK,QAAQ,OAAQ,EAAE,EAAE,QAAQ,sBAAuB,EAAE,CACnE,CAUO,SAASE,EAAmBJ,EAA+B,CAChE,MAAMC,EAAMD,EAAc,KAAA,EAC1B,GAAI,CACF,OAAO,IAAI,IAAIC,CAAG,EAAE,MACtB,MAAQ,CACN,OAAOA,EAAI,QAAQ,OAAQ,EAAE,CAC/B,CACF,CAQO,SAASI,EAAsBC,EAKZ,CACxB,KAAM,CAAE,WAAAC,EAAY,cAAAP,CAAA,EAAkBM,EACtC,IAAIE,EAEJ,MAAO,UAAY,CACjB,GAAI,OAAOD,GAAe,SAAU,OAAOA,EAC3C,GAAI,OAAOA,GAAe,WAAY,OAAOA,EAAA,EAC7C,GAAIC,GAAU,KAAK,IAAA,EAAQA,EAAO,aAAcA,EAAO,MACvD,GAAI,CAACF,EAAM,OAAQ,MAAM,IAAI,MAAM,iEAAiE,EAEpG,MAAMG,EAAM,MAAMC,yBAAuB,CAAE,OAAQJ,EAAM,OAAQ,GAAGC,CAAA,EAAcD,EAAM,MAAO,CAC7F,SAAUF,EAAmBJ,CAAa,CAAA,CAC3C,EACD,OAAAQ,EAAS,CAAE,MAAOC,EAAI,aAAc,MAAO,KAAK,IAAA,IAAUA,EAAI,YAAc,KAAO,IAAM,GAAA,EAClFA,EAAI,YACb,CACF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { g as c } from "./oidc-CB0FqjFz.js";
|
|
2
|
+
function o(n) {
|
|
3
|
+
const e = n.trim();
|
|
4
|
+
let r = e;
|
|
5
|
+
try {
|
|
6
|
+
const t = new URL(e);
|
|
7
|
+
r = `${t.origin}${t.pathname}`;
|
|
8
|
+
} catch {
|
|
9
|
+
}
|
|
10
|
+
return r.replace(/\/+$/, "").replace(/\/(mgmt(\/v1)?|v1)$/, "");
|
|
11
|
+
}
|
|
12
|
+
function s(n) {
|
|
13
|
+
const e = n.trim();
|
|
14
|
+
try {
|
|
15
|
+
return new URL(e).origin;
|
|
16
|
+
} catch {
|
|
17
|
+
return e.replace(/\/+$/, "");
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function u(n) {
|
|
21
|
+
const { credential: e, managementUrl: r } = n;
|
|
22
|
+
let t;
|
|
23
|
+
return async () => {
|
|
24
|
+
if (typeof e == "string") return e;
|
|
25
|
+
if (typeof e == "function") return e();
|
|
26
|
+
if (t && Date.now() < t.until) return t.value;
|
|
27
|
+
if (!n.issuer) throw new Error("pontive: client credentials need the issuer to exchange them at");
|
|
28
|
+
const a = await c({ issuer: n.issuer, ...e }, n.fetch, {
|
|
29
|
+
resource: s(r)
|
|
30
|
+
});
|
|
31
|
+
return t = { value: a.access_token, until: Date.now() + ((a.expires_in ?? 300) - 60) * 1e3 }, a.access_token;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export {
|
|
35
|
+
u as a,
|
|
36
|
+
s as b,
|
|
37
|
+
o as m
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=management-credential-VhmMzGDl.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"management-credential-VhmMzGDl.js","sources":["../src/management-credential.ts"],"sourcesContent":["import { clientCredentialsToken } from \"./oidc\";\n\n/**\n * How a server gets a management API token: a token, a function returning\n * one, or the client credentials of a service account (exchanged at the\n * issuer for a management-audience token, and reused until it is about to\n * expire).\n */\nexport type ManagementCredential =\n | string\n | (() => string | Promise<string>)\n | { clientId: string; clientSecret: string };\n\n/**\n * The management API's base for a configured `managementUrl`: its origin and\n * any gateway path, without a trailing slash and without a `/v1`, `/mgmt` or\n * `/mgmt/v1` suffix (as pontkit-core and oidc-client read `apiBaseUrl`). The\n * routes are built on it (`{base}/v1/…`, api-route-review D12), so\n * `https://api.us.pontive.com` and `…/v1` configure the same API. Query and\n * fragment are dropped.\n */\nexport function managementBase(managementUrl: string): string {\n const raw = managementUrl.trim();\n let base = raw;\n try {\n const url = new URL(raw);\n base = `${url.origin}${url.pathname}`;\n } catch {\n // Not an absolute URL: trimmed as given.\n }\n return base.replace(/\\/+$/, \"\").replace(/\\/(mgmt(\\/v1)?|v1)$/, \"\");\n}\n\n/**\n * The management API's audience for a configured `managementUrl`: its origin,\n * `https://api.us.pontive.com`, with no path and no trailing slash, whatever\n * path the URL carries (api-route-review D51; pontive-core's\n * `directory.ManagementAudience` and oidc-client's `managementAudience()`\n * derive it the same way). A value that is not an absolute URL is returned\n * trimmed, so the token request fails visibly.\n */\nexport function managementAudience(managementUrl: string): string {\n const raw = managementUrl.trim();\n try {\n return new URL(raw).origin;\n } catch {\n return raw.replace(/\\/+$/, \"\");\n }\n}\n\n/**\n * A function that returns a management API bearer token for `credential`.\n * Client credentials are exchanged at `issuer` for the management API's\n * audience (`managementAudience(managementUrl)`) and the token is reused until\n * a minute before it expires.\n */\nexport function managementTokenSource(input: {\n credential: ManagementCredential;\n managementUrl: string;\n issuer?: string;\n fetch: typeof fetch;\n}): () => Promise<string> {\n const { credential, managementUrl } = input;\n let cached: { value: string; until: number } | undefined;\n\n return async () => {\n if (typeof credential === \"string\") return credential;\n if (typeof credential === \"function\") return credential();\n if (cached && Date.now() < cached.until) return cached.value;\n if (!input.issuer) throw new Error(\"pontive: client credentials need the issuer to exchange them at\");\n\n const res = await clientCredentialsToken({ issuer: input.issuer, ...credential }, input.fetch, {\n resource: managementAudience(managementUrl),\n });\n cached = { value: res.access_token, until: Date.now() + ((res.expires_in ?? 300) - 60) * 1000 };\n return res.access_token;\n };\n}\n"],"names":["managementBase","managementUrl","raw","base","url","managementAudience","managementTokenSource","input","credential","cached","res","clientCredentialsToken"],"mappings":";AAqBO,SAASA,EAAeC,GAA+B;AAC5D,QAAMC,IAAMD,EAAc,KAAA;AAC1B,MAAIE,IAAOD;AACX,MAAI;AACF,UAAME,IAAM,IAAI,IAAIF,CAAG;AACvB,IAAAC,IAAO,GAAGC,EAAI,MAAM,GAAGA,EAAI,QAAQ;AAAA,EACrC,QAAQ;AAAA,EAER;AACA,SAAOD,EAAK,QAAQ,QAAQ,EAAE,EAAE,QAAQ,uBAAuB,EAAE;AACnE;AAUO,SAASE,EAAmBJ,GAA+B;AAChE,QAAMC,IAAMD,EAAc,KAAA;AAC1B,MAAI;AACF,WAAO,IAAI,IAAIC,CAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAOA,EAAI,QAAQ,QAAQ,EAAE;AAAA,EAC/B;AACF;AAQO,SAASI,EAAsBC,GAKZ;AACxB,QAAM,EAAE,YAAAC,GAAY,eAAAP,EAAA,IAAkBM;AACtC,MAAIE;AAEJ,SAAO,YAAY;AACjB,QAAI,OAAOD,KAAe,SAAU,QAAOA;AAC3C,QAAI,OAAOA,KAAe,WAAY,QAAOA,EAAA;AAC7C,QAAIC,KAAU,KAAK,IAAA,IAAQA,EAAO,cAAcA,EAAO;AACvD,QAAI,CAACF,EAAM,OAAQ,OAAM,IAAI,MAAM,iEAAiE;AAEpG,UAAMG,IAAM,MAAMC,EAAuB,EAAE,QAAQJ,EAAM,QAAQ,GAAGC,EAAA,GAAcD,EAAM,OAAO;AAAA,MAC7F,UAAUF,EAAmBJ,CAAa;AAAA,IAAA,CAC3C;AACD,WAAAQ,IAAS,EAAE,OAAOC,EAAI,cAAc,OAAO,KAAK,IAAA,MAAUA,EAAI,cAAc,OAAO,MAAM,IAAA,GAClFA,EAAI;AAAA,EACb;AACF;"}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a server gets a management API token: a token, a function returning
|
|
3
|
+
* one, or the client credentials of a service account (exchanged at the
|
|
4
|
+
* issuer for a management-audience token, and reused until it is about to
|
|
5
|
+
* expire).
|
|
6
|
+
*/
|
|
7
|
+
export type ManagementCredential = string | (() => string | Promise<string>) | {
|
|
8
|
+
clientId: string;
|
|
9
|
+
clientSecret: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The management API's base for a configured `managementUrl`: its origin and
|
|
13
|
+
* any gateway path, without a trailing slash and without a `/v1`, `/mgmt` or
|
|
14
|
+
* `/mgmt/v1` suffix (as pontkit-core and oidc-client read `apiBaseUrl`). The
|
|
15
|
+
* routes are built on it (`{base}/v1/…`, api-route-review D12), so
|
|
16
|
+
* `https://api.us.pontive.com` and `…/v1` configure the same API. Query and
|
|
17
|
+
* fragment are dropped.
|
|
18
|
+
*/
|
|
19
|
+
export declare function managementBase(managementUrl: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* The management API's audience for a configured `managementUrl`: its origin,
|
|
22
|
+
* `https://api.us.pontive.com`, with no path and no trailing slash, whatever
|
|
23
|
+
* path the URL carries (api-route-review D51; pontive-core's
|
|
24
|
+
* `directory.ManagementAudience` and oidc-client's `managementAudience()`
|
|
25
|
+
* derive it the same way). A value that is not an absolute URL is returned
|
|
26
|
+
* trimmed, so the token request fails visibly.
|
|
27
|
+
*/
|
|
28
|
+
export declare function managementAudience(managementUrl: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* A function that returns a management API bearer token for `credential`.
|
|
31
|
+
* Client credentials are exchanged at `issuer` for the management API's
|
|
32
|
+
* audience (`managementAudience(managementUrl)`) and the token is reused until
|
|
33
|
+
* a minute before it expires.
|
|
34
|
+
*/
|
|
35
|
+
export declare function managementTokenSource(input: {
|
|
36
|
+
credential: ManagementCredential;
|
|
37
|
+
managementUrl: string;
|
|
38
|
+
issuer?: string;
|
|
39
|
+
fetch: typeof fetch;
|
|
40
|
+
}): () => Promise<string>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a server gets a management API token: a token, a function returning
|
|
3
|
+
* one, or the client credentials of a service account (exchanged at the
|
|
4
|
+
* issuer for a management-audience token, and reused until it is about to
|
|
5
|
+
* expire).
|
|
6
|
+
*/
|
|
7
|
+
export type ManagementCredential = string | (() => string | Promise<string>) | {
|
|
8
|
+
clientId: string;
|
|
9
|
+
clientSecret: string;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* The management API's base for a configured `managementUrl`: its origin and
|
|
13
|
+
* any gateway path, without a trailing slash and without a `/v1`, `/mgmt` or
|
|
14
|
+
* `/mgmt/v1` suffix (as pontkit-core and oidc-client read `apiBaseUrl`). The
|
|
15
|
+
* routes are built on it (`{base}/v1/…`, api-route-review D12), so
|
|
16
|
+
* `https://api.us.pontive.com` and `…/v1` configure the same API. Query and
|
|
17
|
+
* fragment are dropped.
|
|
18
|
+
*/
|
|
19
|
+
export declare function managementBase(managementUrl: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* The management API's audience for a configured `managementUrl`: its origin,
|
|
22
|
+
* `https://api.us.pontive.com`, with no path and no trailing slash, whatever
|
|
23
|
+
* path the URL carries (api-route-review D51; pontive-core's
|
|
24
|
+
* `directory.ManagementAudience` and oidc-client's `managementAudience()`
|
|
25
|
+
* derive it the same way). A value that is not an absolute URL is returned
|
|
26
|
+
* trimmed, so the token request fails visibly.
|
|
27
|
+
*/
|
|
28
|
+
export declare function managementAudience(managementUrl: string): string;
|
|
29
|
+
/**
|
|
30
|
+
* A function that returns a management API bearer token for `credential`.
|
|
31
|
+
* Client credentials are exchanged at `issuer` for the management API's
|
|
32
|
+
* audience (`managementAudience(managementUrl)`) and the token is reused until
|
|
33
|
+
* a minute before it expires.
|
|
34
|
+
*/
|
|
35
|
+
export declare function managementTokenSource(input: {
|
|
36
|
+
credential: ManagementCredential;
|
|
37
|
+
managementUrl: string;
|
|
38
|
+
issuer?: string;
|
|
39
|
+
fetch: typeof fetch;
|
|
40
|
+
}): () => Promise<string>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { decodeJwt as o } from "jose";
|
|
2
|
+
const n = "principal";
|
|
3
|
+
function c(t, e) {
|
|
4
|
+
return {
|
|
5
|
+
token: e.token,
|
|
6
|
+
clientId: e.clientId,
|
|
7
|
+
scopes: e.scopes,
|
|
8
|
+
// The SDK compares this with the clock with no leeway of its own, so the
|
|
9
|
+
// leeway the token was verified with is added to it.
|
|
10
|
+
expiresAt: (o(e.token).exp ?? 0) + t.leewaySeconds,
|
|
11
|
+
...t.metadataUrl ? { resource: new URL(t.resource) } : {},
|
|
12
|
+
extra: { [n]: e }
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export {
|
|
16
|
+
n as P,
|
|
17
|
+
c as t
|
|
18
|
+
};
|
|
19
|
+
//# sourceMappingURL=mcp-auth-info-BGyWua_9.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth-info-BGyWua_9.js","sources":["../src/mcp-auth-info.ts"],"sourcesContent":["import { decodeJwt } from \"jose\";\n\nimport type { Principal, ResourceServer } from \"./resource-server\";\n\n/**\n * The MCP TypeScript SDK's `AuthInfo`, structurally, so the adapters that set\n * it (Express's `req.auth`) need not import the SDK.\n */\nexport interface McpAuthInfo {\n token: string;\n clientId: string;\n scopes: string[];\n /** Seconds since the epoch. */\n expiresAt?: number;\n resource?: URL;\n extra?: Record<string, unknown>;\n}\n\n/** Where the principal goes in `AuthInfo.extra`. */\nexport const PRINCIPAL_KEY = \"principal\";\n\nexport function toMcpAuthInfo(rs: ResourceServer, principal: Principal): McpAuthInfo {\n return {\n token: principal.token,\n clientId: principal.clientId,\n scopes: principal.scopes,\n // The SDK compares this with the clock with no leeway of its own, so the\n // leeway the token was verified with is added to it.\n expiresAt: (decodeJwt(principal.token).exp ?? 0) + rs.leewaySeconds,\n ...(rs.metadataUrl ? { resource: new URL(rs.resource) } : {}),\n extra: { [PRINCIPAL_KEY]: principal },\n };\n}\n"],"names":["PRINCIPAL_KEY","toMcpAuthInfo","rs","principal","decodeJwt"],"mappings":";AAmBO,MAAMA,IAAgB;AAEtB,SAASC,EAAcC,GAAoBC,GAAmC;AACnF,SAAO;AAAA,IACL,OAAOA,EAAU;AAAA,IACjB,UAAUA,EAAU;AAAA,IACpB,QAAQA,EAAU;AAAA;AAAA;AAAA,IAGlB,YAAYC,EAAUD,EAAU,KAAK,EAAE,OAAO,KAAKD,EAAG;AAAA,IACtD,GAAIA,EAAG,cAAc,EAAE,UAAU,IAAI,IAAIA,EAAG,QAAQ,EAAA,IAAM,CAAA;AAAA,IAC1D,OAAO,EAAE,CAACF,CAAa,GAAGG,EAAA;AAAA,EAAU;AAExC;"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const c=require("jose"),o="principal";function n(t,e){return{token:e.token,clientId:e.clientId,scopes:e.scopes,expiresAt:(c.decodeJwt(e.token).exp??0)+t.leewaySeconds,...t.metadataUrl?{resource:new URL(t.resource)}:{},extra:{[o]:e}}}exports.PRINCIPAL_KEY=o;exports.toMcpAuthInfo=n;
|
|
2
|
+
//# sourceMappingURL=mcp-auth-info-jblMsSJo.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-auth-info-jblMsSJo.cjs","sources":["../src/mcp-auth-info.ts"],"sourcesContent":["import { decodeJwt } from \"jose\";\n\nimport type { Principal, ResourceServer } from \"./resource-server\";\n\n/**\n * The MCP TypeScript SDK's `AuthInfo`, structurally, so the adapters that set\n * it (Express's `req.auth`) need not import the SDK.\n */\nexport interface McpAuthInfo {\n token: string;\n clientId: string;\n scopes: string[];\n /** Seconds since the epoch. */\n expiresAt?: number;\n resource?: URL;\n extra?: Record<string, unknown>;\n}\n\n/** Where the principal goes in `AuthInfo.extra`. */\nexport const PRINCIPAL_KEY = \"principal\";\n\nexport function toMcpAuthInfo(rs: ResourceServer, principal: Principal): McpAuthInfo {\n return {\n token: principal.token,\n clientId: principal.clientId,\n scopes: principal.scopes,\n // The SDK compares this with the clock with no leeway of its own, so the\n // leeway the token was verified with is added to it.\n expiresAt: (decodeJwt(principal.token).exp ?? 0) + rs.leewaySeconds,\n ...(rs.metadataUrl ? { resource: new URL(rs.resource) } : {}),\n extra: { [PRINCIPAL_KEY]: principal },\n };\n}\n"],"names":["PRINCIPAL_KEY","toMcpAuthInfo","rs","principal","decodeJwt"],"mappings":"qCAmBaA,EAAgB,YAEtB,SAASC,EAAcC,EAAoBC,EAAmC,CACnF,MAAO,CACL,MAAOA,EAAU,MACjB,SAAUA,EAAU,SACpB,OAAQA,EAAU,OAGlB,WAAYC,EAAAA,UAAUD,EAAU,KAAK,EAAE,KAAO,GAAKD,EAAG,cACtD,GAAIA,EAAG,YAAc,CAAE,SAAU,IAAI,IAAIA,EAAG,QAAQ,CAAA,EAAM,CAAA,EAC1D,MAAO,CAAE,CAACF,CAAa,EAAGG,CAAA,CAAU,CAExC"}
|