@cboxdk/id-js 0.7.0 → 0.8.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.
- package/README.md +109 -0
- package/dist/{chunk-7HLUTJIN.js → chunk-3SRL7SIB.js} +15 -4
- package/dist/chunk-3SRL7SIB.js.map +1 -0
- package/dist/index.cjs +298 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +240 -2
- package/dist/index.d.ts +240 -2
- package/dist/index.js +281 -14
- package/dist/index.js.map +1 -1
- package/dist/nextjs.cjs +1 -1
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-7HLUTJIN.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,12 +1,266 @@
|
|
|
1
|
-
import { ConfigurationError, Discovery, AuthenticationError } from './chunk-
|
|
2
|
-
export { AuthenticationError, CboxIdClient, CboxIdError, ConfigurationError, InvalidStateError, VaultClient, challenge, createVerifier, randomToken, verifyWebhook } from './chunk-
|
|
1
|
+
import { ConfigurationError, FrontendApiError, Discovery, AuthenticationError } from './chunk-3SRL7SIB.js';
|
|
2
|
+
export { AuthenticationError, CboxIdClient, CboxIdError, ConfigurationError, FrontendApiError, InvalidStateError, VaultClient, challenge, createVerifier, randomToken, verifyWebhook } from './chunk-3SRL7SIB.js';
|
|
3
|
+
|
|
4
|
+
// src/legacy.ts
|
|
5
|
+
function createLegacyVerifier(options) {
|
|
6
|
+
if (!options.secret || options.secret.length < 32) {
|
|
7
|
+
throw new ConfigurationError(
|
|
8
|
+
"A legacy verifier secret must be at least 32 characters; it is the only thing proving a request came from Cbox ID."
|
|
9
|
+
);
|
|
10
|
+
}
|
|
11
|
+
const tolerance = options.toleranceSeconds ?? 300;
|
|
12
|
+
return async function handle(request) {
|
|
13
|
+
const raw = await request.text();
|
|
14
|
+
if (!await isSignedByCboxId(raw, request.headers.get("X-Cbox-Signature"), options.secret, tolerance)) {
|
|
15
|
+
return json({ error: "unauthorized" }, 401);
|
|
16
|
+
}
|
|
17
|
+
let payload;
|
|
18
|
+
try {
|
|
19
|
+
payload = JSON.parse(raw);
|
|
20
|
+
} catch {
|
|
21
|
+
return json({ error: "invalid_request" }, 400);
|
|
22
|
+
}
|
|
23
|
+
const { email, password } = payload;
|
|
24
|
+
if (typeof email !== "string" || email === "") {
|
|
25
|
+
return json({ error: "invalid_request" }, 400);
|
|
26
|
+
}
|
|
27
|
+
if (typeof password !== "string") {
|
|
28
|
+
return json({ user: null }, 200);
|
|
29
|
+
}
|
|
30
|
+
let user;
|
|
31
|
+
try {
|
|
32
|
+
user = await options.verify(email, password);
|
|
33
|
+
} catch {
|
|
34
|
+
return json({ error: "unavailable" }, 503);
|
|
35
|
+
}
|
|
36
|
+
if (!user) {
|
|
37
|
+
return json({ user: null }, 200);
|
|
38
|
+
}
|
|
39
|
+
return json(
|
|
40
|
+
{
|
|
41
|
+
email: user.email,
|
|
42
|
+
name: user.name ?? null,
|
|
43
|
+
email_verified: user.emailVerified === true,
|
|
44
|
+
...user.passwordHash ? { password_hash: user.passwordHash } : {}
|
|
45
|
+
},
|
|
46
|
+
200
|
|
47
|
+
);
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async function isSignedByCboxId(body, header, secret, toleranceSeconds) {
|
|
51
|
+
if (!header) {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
const parts = {};
|
|
55
|
+
for (const piece of header.split(",")) {
|
|
56
|
+
const [key2, value] = piece.split("=", 2);
|
|
57
|
+
if (key2 && value) {
|
|
58
|
+
parts[key2.trim()] = value.trim();
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const timestamp = parts["t"] ?? "";
|
|
62
|
+
const signature = parts["v1"] ?? "";
|
|
63
|
+
if (!/^\d+$/.test(timestamp) || signature === "") {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
if (Math.abs(Math.floor(Date.now() / 1e3) - Number(timestamp)) > toleranceSeconds) {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
const key = await crypto.subtle.importKey(
|
|
70
|
+
"raw",
|
|
71
|
+
new TextEncoder().encode(secret),
|
|
72
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
73
|
+
false,
|
|
74
|
+
["sign"]
|
|
75
|
+
);
|
|
76
|
+
const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${timestamp}.${body}`));
|
|
77
|
+
const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
78
|
+
return timingSafeEqual(expected, signature);
|
|
79
|
+
}
|
|
80
|
+
function timingSafeEqual(a, b) {
|
|
81
|
+
if (a.length !== b.length) {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
let diff = 0;
|
|
85
|
+
for (let i = 0; i < a.length; i++) {
|
|
86
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
87
|
+
}
|
|
88
|
+
return diff === 0;
|
|
89
|
+
}
|
|
90
|
+
function json(body, status) {
|
|
91
|
+
return new Response(JSON.stringify(body), {
|
|
92
|
+
status,
|
|
93
|
+
headers: { "Content-Type": "application/json" }
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/frontend.ts
|
|
98
|
+
var CboxIdFrontend = class {
|
|
99
|
+
issuer;
|
|
100
|
+
publishableKey;
|
|
101
|
+
timeoutMs;
|
|
102
|
+
retries;
|
|
103
|
+
fetchImpl;
|
|
104
|
+
/**
|
|
105
|
+
* The config document, and the in-flight promise for it.
|
|
106
|
+
*
|
|
107
|
+
* Deduplicated rather than merely cached: a page with a sign-in form, a user button and
|
|
108
|
+
* an organization switcher mounts three components in the same tick, and three parallel
|
|
109
|
+
* fetches of the same immutable document is a waste the SDK should absorb rather than
|
|
110
|
+
* ask every consumer to.
|
|
111
|
+
*/
|
|
112
|
+
configPromise = null;
|
|
113
|
+
constructor(options) {
|
|
114
|
+
if (!options.issuer) {
|
|
115
|
+
throw new ConfigurationError("issuer is required.");
|
|
116
|
+
}
|
|
117
|
+
if (!options.publishableKey?.startsWith("pk_")) {
|
|
118
|
+
throw new ConfigurationError(
|
|
119
|
+
"publishableKey must be a pk_test_\u2026 or pk_live_\u2026 key. Client secrets and API keys must never be put in a browser."
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
this.issuer = options.issuer.replace(/\/$/, "");
|
|
123
|
+
this.publishableKey = options.publishableKey;
|
|
124
|
+
this.timeoutMs = options.timeoutMs ?? 1e4;
|
|
125
|
+
this.retries = Math.max(0, options.retries ?? 2);
|
|
126
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
127
|
+
}
|
|
128
|
+
/** Whether this key drives real sign-ins. Handy for a "test mode" badge in your own UI. */
|
|
129
|
+
get isLive() {
|
|
130
|
+
return this.publishableKey.startsWith("pk_live_");
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The public sign-in configuration.
|
|
134
|
+
*
|
|
135
|
+
* Fetched once per client instance. The document is small and changes when somebody
|
|
136
|
+
* edits it in the console, so a long-lived page picks changes up on its next full load
|
|
137
|
+
* rather than mid-session — which is the right trade for something that decides layout.
|
|
138
|
+
*/
|
|
139
|
+
async config() {
|
|
140
|
+
this.configPromise ??= this.get("/frontend/v1/config", {}, isFrontendConfig).catch((error) => {
|
|
141
|
+
this.configPromise = null;
|
|
142
|
+
throw error;
|
|
143
|
+
});
|
|
144
|
+
return this.configPromise;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Who is signed in, given an access token your app already holds.
|
|
148
|
+
*
|
|
149
|
+
* Returns `{ user: null }` rather than throwing when nobody is signed in. That is a
|
|
150
|
+
* state, not an error: a user button renders on pages nobody has signed in on, and
|
|
151
|
+
* making callers treat a rejection as a state is how flash-of-signed-out bugs happen.
|
|
152
|
+
*
|
|
153
|
+
* The publishable key grants nothing here — the token is the entire authority.
|
|
154
|
+
*/
|
|
155
|
+
async session(accessToken) {
|
|
156
|
+
if (!accessToken) {
|
|
157
|
+
return { user: null };
|
|
158
|
+
}
|
|
159
|
+
return this.get(
|
|
160
|
+
"/frontend/v1/session",
|
|
161
|
+
{ Authorization: `Bearer ${accessToken}` },
|
|
162
|
+
isFrontendSession
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
async get(path, extraHeaders = {}, validate) {
|
|
166
|
+
let lastError;
|
|
167
|
+
for (let attempt = 0; attempt <= this.retries; attempt++) {
|
|
168
|
+
if (attempt > 0) {
|
|
169
|
+
await new Promise((resolve) => setTimeout(resolve, 150 * attempt));
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
return await this.attempt(path, extraHeaders, validate);
|
|
173
|
+
} catch (error) {
|
|
174
|
+
lastError = error;
|
|
175
|
+
if (!(error instanceof FrontendApiError) || error.code !== "unavailable") {
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
throw lastError;
|
|
181
|
+
}
|
|
182
|
+
async attempt(path, extraHeaders, validate) {
|
|
183
|
+
const controller = new AbortController();
|
|
184
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
185
|
+
let response;
|
|
186
|
+
try {
|
|
187
|
+
response = await this.fetchImpl(`${this.issuer}${path}`, {
|
|
188
|
+
headers: {
|
|
189
|
+
// A header, never a query string: a query string puts the key in server logs,
|
|
190
|
+
// in `Referer` on every outbound link, and in browser history.
|
|
191
|
+
"X-Cbox-Publishable-Key": this.publishableKey,
|
|
192
|
+
Accept: "application/json",
|
|
193
|
+
...extraHeaders
|
|
194
|
+
},
|
|
195
|
+
signal: controller.signal
|
|
196
|
+
});
|
|
197
|
+
} catch (cause) {
|
|
198
|
+
throw new FrontendApiError(
|
|
199
|
+
`Could not reach Cbox ID at ${this.issuer}. If this is a browser, check that this page's origin is on the key's allow-list \u2014 a refused request fails as a network error by design.`,
|
|
200
|
+
"unavailable"
|
|
201
|
+
);
|
|
202
|
+
} finally {
|
|
203
|
+
clearTimeout(timer);
|
|
204
|
+
}
|
|
205
|
+
if (response.status === 429) {
|
|
206
|
+
const retryAfter = Number(response.headers.get("Retry-After") ?? "");
|
|
207
|
+
throw new FrontendApiError(
|
|
208
|
+
"Cbox ID is rate limiting this key.",
|
|
209
|
+
"rate_limited",
|
|
210
|
+
429,
|
|
211
|
+
Number.isFinite(retryAfter) ? retryAfter : void 0
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
if (response.status === 401 || response.status === 403) {
|
|
215
|
+
throw new FrontendApiError(
|
|
216
|
+
`Cbox ID refused the request (${response.status}). Check that this page's origin is on the key's allow-list, and that the key is not revoked.`,
|
|
217
|
+
"origin_not_allowed",
|
|
218
|
+
response.status
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
if (!response.ok) {
|
|
222
|
+
throw new FrontendApiError(
|
|
223
|
+
`Cbox ID returned ${response.status}.`,
|
|
224
|
+
"unavailable",
|
|
225
|
+
response.status
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
let body;
|
|
229
|
+
try {
|
|
230
|
+
body = await response.json();
|
|
231
|
+
} catch {
|
|
232
|
+
throw new FrontendApiError("Cbox ID returned a body that is not JSON.", "malformed", response.status);
|
|
233
|
+
}
|
|
234
|
+
if (validate && !validate(body)) {
|
|
235
|
+
throw new FrontendApiError(
|
|
236
|
+
"Cbox ID returned a body that is not the expected document.",
|
|
237
|
+
"malformed",
|
|
238
|
+
response.status
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
return body;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
function isFrontendConfig(body) {
|
|
245
|
+
if (typeof body !== "object" || body === null) {
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
const doc = body;
|
|
249
|
+
return typeof doc.issuer === "string" && typeof doc.endpoints === "object" && doc.endpoints !== null;
|
|
250
|
+
}
|
|
251
|
+
function isFrontendSession(body) {
|
|
252
|
+
return typeof body === "object" && body !== null && "user" in body;
|
|
253
|
+
}
|
|
3
254
|
|
|
4
255
|
// src/authz.ts
|
|
5
256
|
function defineAuthz(declaration) {
|
|
6
257
|
const permissions = declaration.permissions ?? [];
|
|
7
258
|
const roles = declaration.roles ?? [];
|
|
8
259
|
assertDeclaration(permissions, roles);
|
|
9
|
-
|
|
260
|
+
if (declaration.legacyLogin) {
|
|
261
|
+
assertLegacyLogin(declaration.legacyLogin);
|
|
262
|
+
}
|
|
263
|
+
return { ...declaration, permissions, roles };
|
|
10
264
|
}
|
|
11
265
|
async function buildManifest(declaration) {
|
|
12
266
|
const permissions = (declaration.permissions ?? []).map(canonicalPermission);
|
|
@@ -15,7 +269,12 @@ async function buildManifest(declaration) {
|
|
|
15
269
|
permissions.sort((a, b) => byteCompare(a.key, b.key));
|
|
16
270
|
roles.sort((a, b) => byteCompare(a.key, b.key));
|
|
17
271
|
const version = (await sha256Hex(canonicalManifestJson(permissions, roles))).slice(0, 16);
|
|
18
|
-
|
|
272
|
+
const manifest = { version, permissions, roles };
|
|
273
|
+
if (declaration.legacyLogin) {
|
|
274
|
+
assertLegacyLogin(declaration.legacyLogin);
|
|
275
|
+
manifest.legacy_login = declaration.legacyLogin;
|
|
276
|
+
}
|
|
277
|
+
return manifest;
|
|
19
278
|
}
|
|
20
279
|
async function publishManifest(config, declaration) {
|
|
21
280
|
if (!config.issuer || !config.clientId || !config.clientSecret) {
|
|
@@ -41,8 +300,8 @@ async function publishManifest(config, declaration) {
|
|
|
41
300
|
if (!response.ok) {
|
|
42
301
|
throw new AuthenticationError(`Manifest push failed: HTTP ${response.status} ${await response.text()}`);
|
|
43
302
|
}
|
|
44
|
-
const
|
|
45
|
-
return
|
|
303
|
+
const json2 = await response.json();
|
|
304
|
+
return json2 !== null && typeof json2 === "object" ? json2 : {};
|
|
46
305
|
}
|
|
47
306
|
async function mintToken(config, discovery, timeoutMs) {
|
|
48
307
|
const response = await fetchWithTimeout(
|
|
@@ -59,13 +318,13 @@ async function mintToken(config, discovery, timeoutMs) {
|
|
|
59
318
|
},
|
|
60
319
|
timeoutMs
|
|
61
320
|
);
|
|
62
|
-
const
|
|
63
|
-
if (typeof
|
|
321
|
+
const json2 = await response.json().catch(() => ({}));
|
|
322
|
+
if (typeof json2.access_token !== "string" || json2.access_token === "") {
|
|
64
323
|
throw new AuthenticationError(
|
|
65
324
|
"Could not obtain an apps.manifest access token \u2014 check the client credentials and that the client holds the apps.manifest scope."
|
|
66
325
|
);
|
|
67
326
|
}
|
|
68
|
-
return
|
|
327
|
+
return json2.access_token;
|
|
69
328
|
}
|
|
70
329
|
function assertDeclaration(permissions, roles) {
|
|
71
330
|
const permissionKeys = /* @__PURE__ */ new Set();
|
|
@@ -124,11 +383,11 @@ function emptyToNull(value) {
|
|
|
124
383
|
function byteCompare(a, b) {
|
|
125
384
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
126
385
|
}
|
|
127
|
-
function escapeLikePhp(
|
|
386
|
+
function escapeLikePhp(json2) {
|
|
128
387
|
let out = "";
|
|
129
|
-
for (let i = 0; i <
|
|
130
|
-
const char =
|
|
131
|
-
const code =
|
|
388
|
+
for (let i = 0; i < json2.length; i++) {
|
|
389
|
+
const char = json2.charAt(i);
|
|
390
|
+
const code = json2.charCodeAt(i);
|
|
132
391
|
if (char === "/") {
|
|
133
392
|
out += "\\/";
|
|
134
393
|
} else if (code > 127) {
|
|
@@ -152,7 +411,15 @@ async function fetchWithTimeout(url, init, timeoutMs) {
|
|
|
152
411
|
clearTimeout(timer);
|
|
153
412
|
}
|
|
154
413
|
}
|
|
414
|
+
function assertLegacyLogin(legacy) {
|
|
415
|
+
if (!legacy.url.startsWith("https://")) {
|
|
416
|
+
throw new ConfigurationError("legacyLogin.url must be https \u2014 a password must never cross the network in the clear.");
|
|
417
|
+
}
|
|
418
|
+
if (!legacy.secret || legacy.secret.length < 32) {
|
|
419
|
+
throw new ConfigurationError("legacyLogin.secret must be at least 32 characters; it is what proves a request came from Cbox ID.");
|
|
420
|
+
}
|
|
421
|
+
}
|
|
155
422
|
|
|
156
|
-
export { buildManifest, defineAuthz, publishManifest };
|
|
423
|
+
export { CboxIdFrontend, buildManifest, createLegacyVerifier, defineAuthz, publishManifest };
|
|
157
424
|
//# sourceMappingURL=index.js.map
|
|
158
425
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authz.ts"],"names":[],"mappings":";;;;AA4EO,SAAS,YAAY,WAAA,EAA2D;AACrF,EAAA,MAAM,WAAA,GAAc,WAAA,CAAY,WAAA,IAAe,EAAC;AAChD,EAAA,MAAM,KAAA,GAAQ,WAAA,CAAY,KAAA,IAAS,EAAC;AACpC,EAAA,iBAAA,CAAkB,aAAa,KAAK,CAAA;AACpC,EAAA,OAAO,EAAE,aAAa,KAAA,EAAM;AAC9B;AAOA,eAAsB,cAAc,WAAA,EAAuD;AACzF,EAAA,MAAM,eAAe,WAAA,CAAY,WAAA,IAAe,EAAC,EAAG,IAAI,mBAAmB,CAAA;AAC3E,EAAA,MAAM,SAAS,WAAA,CAAY,KAAA,IAAS,EAAC,EAAG,IAAI,aAAa,CAAA;AACzD,EAAA,iBAAA,CAAkB,aAAa,KAAK,CAAA;AAEpC,EAAA,WAAA,CAAY,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,YAAY,CAAA,CAAE,GAAA,EAAK,CAAA,CAAE,GAAG,CAAC,CAAA;AACpD,EAAA,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAM,YAAY,CAAA,CAAE,GAAA,EAAK,CAAA,CAAE,GAAG,CAAC,CAAA;AAE9C,EAAA,MAAM,OAAA,GAAA,CAAW,MAAM,SAAA,CAAU,qBAAA,CAAsB,WAAA,EAAa,KAAK,CAAC,CAAA,EAAG,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AACxF,EAAA,OAAO,EAAE,OAAA,EAAS,WAA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EAAgB;AACvC,EAAA,MAAM,QAAQ,UAAA,CAAW,MAAM,UAAA,CAAW,KAAA,IAAS,SAAS,CAAA;AAC5D,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,MAAM,GAAA,EAAK,EAAE,GAAG,IAAA,EAAM,MAAA,EAAQ,UAAA,CAAW,MAAA,EAAQ,CAAA;AAAA,EAChE,CAAA,SAAE;AACA,IAAA,YAAA,CAAa,KAAK,CAAA;AAAA,EACpB;AACF","file":"index.js","sourcesContent":["import { Discovery } from './discovery.js';\nimport { AuthenticationError, ConfigurationError } from './errors.js';\n\n/**\n * A permission your app declares. `key` is a `feature:action` slug (e.g.\n * `invoices:create`); `description` is human-facing copy for the Cbox ID console.\n */\nexport interface PermissionDefinition {\n key: string;\n description?: string;\n}\n\n/**\n * A role your app declares. `permissions` lists the permission keys the role\n * grants — each must reference a declared {@link PermissionDefinition}.\n */\nexport interface RoleDefinition {\n key: string;\n name: string;\n description?: string;\n permissions: string[];\n}\n\n/**\n * The roles + permissions an app declares in code. Either list may be omitted.\n * Pass this to {@link defineAuthz} (to validate up front) or straight to\n * {@link buildManifest} / {@link publishManifest}.\n */\nexport interface AuthzDeclaration {\n permissions?: PermissionDefinition[];\n roles?: RoleDefinition[];\n}\n\n/**\n * The manifest as it is sent to Cbox ID: the declared permissions + roles plus a\n * content-derived `version`, so republishing an unchanged catalog is a no-op.\n */\nexport interface AuthzManifest {\n version: string;\n permissions: PermissionDefinition[];\n roles: RoleDefinition[];\n}\n\n/** What {@link publishManifest} needs to authenticate the push. */\nexport interface ManifestPublisherConfig {\n /** Base URL (issuer) of the Cbox ID instance — the `token_endpoint` is discovered from it. */\n issuer: string;\n /** Your OAuth client id. The client must hold the `apps.manifest` scope. */\n clientId: string;\n /** Your OAuth client secret. The push uses the client-credentials grant. */\n clientSecret: string;\n /** Timeout (ms) for back-channel HTTP calls. Defaults to `10000`. */\n timeoutMs?: number;\n}\n\n/**\n * The server's sync summary. The named fields are the ones the SDK/CLI reads;\n * the index signature keeps any extra fields the server returns.\n */\nexport interface ManifestSyncSummary {\n unchanged?: boolean;\n roles_declared?: number;\n permissions_declared?: number;\n version?: string;\n [key: string]: unknown;\n}\n\n/**\n * Validate a roles/permissions declaration and return it normalized (both lists\n * always present). Call this where you declare your catalog so mistakes — a role\n * that grants an undeclared permission, a duplicate key — surface immediately\n * rather than on deploy.\n *\n * @throws ConfigurationError on a missing key/name, a duplicate, or a role that\n * references a permission that was never declared.\n */\nexport function defineAuthz(declaration: AuthzDeclaration): Required<AuthzDeclaration> {\n const permissions = declaration.permissions ?? [];\n const roles = declaration.roles ?? [];\n assertDeclaration(permissions, roles);\n return { permissions, roles };\n}\n\n/**\n * Build the manifest — the declared catalog plus a stable content hash `version`\n * (first 16 hex chars of the sha256 of the canonicalized catalog). The catalog is\n * sorted by key first, so declaration order never changes the version.\n */\nexport async function buildManifest(declaration: AuthzDeclaration): Promise<AuthzManifest> {\n const permissions = (declaration.permissions ?? []).map(canonicalPermission);\n const roles = (declaration.roles ?? []).map(canonicalRole);\n assertDeclaration(permissions, roles);\n\n permissions.sort((a, b) => byteCompare(a.key, b.key));\n roles.sort((a, b) => byteCompare(a.key, b.key));\n\n const version = (await sha256Hex(canonicalManifestJson(permissions, roles))).slice(0, 16);\n return { version, permissions, roles };\n}\n\n/**\n * Publish this app's authorization manifest (its declared roles + permissions) to\n * Cbox ID. The app owns what a role means; Cbox ID owns identity and who holds it.\n *\n * It mints a client-credentials token with the `apps.manifest` scope (token\n * endpoint discovered from the issuer's OIDC configuration), then POSTs the\n * manifest to `{issuer}/api/v1/apps/manifest`. Run it on deploy or from a script;\n * an unchanged catalog is a server-side no-op.\n *\n * @returns the server's sync summary (`unchanged`, `roles_declared`, …).\n * @throws ConfigurationError when config or the declaration is invalid.\n * @throws AuthenticationError when the token cannot be minted or the push fails.\n */\nexport async function publishManifest(\n config: ManifestPublisherConfig,\n declaration: AuthzDeclaration,\n): Promise<ManifestSyncSummary> {\n if (!config.issuer || !config.clientId || !config.clientSecret) {\n throw new ConfigurationError('Publishing a manifest needs issuer, clientId and clientSecret.');\n }\n\n const timeoutMs = config.timeoutMs ?? 10_000;\n const manifest = await buildManifest(declaration);\n const discovery = new Discovery(config.issuer, timeoutMs, 3_600_000);\n\n const token = await mintToken(config, discovery, timeoutMs);\n\n const response = await fetchWithTimeout(\n `${config.issuer.replace(/\\/$/, '')}/api/v1/apps/manifest`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n accept: 'application/json',\n 'content-type': 'application/json',\n },\n body: JSON.stringify(manifest),\n },\n timeoutMs,\n );\n\n if (!response.ok) {\n throw new AuthenticationError(`Manifest push failed: HTTP ${response.status} ${await response.text()}`);\n }\n\n const json = (await response.json()) as unknown;\n return json !== null && typeof json === 'object' ? (json as ManifestSyncSummary) : {};\n}\n\nasync function mintToken(\n config: ManifestPublisherConfig,\n discovery: Discovery,\n timeoutMs: number,\n): Promise<string> {\n const response = await fetchWithTimeout(\n await discovery.endpoint('token_endpoint'),\n {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n scope: 'apps.manifest',\n }),\n },\n timeoutMs,\n );\n\n const json = (await response.json().catch(() => ({}))) as { access_token?: unknown };\n if (typeof json.access_token !== 'string' || json.access_token === '') {\n throw new AuthenticationError(\n 'Could not obtain an apps.manifest access token — check the client credentials and that the client holds the apps.manifest scope.',\n );\n }\n return json.access_token;\n}\n\nfunction assertDeclaration(permissions: PermissionDefinition[], roles: RoleDefinition[]): void {\n const permissionKeys = new Set<string>();\n for (const permission of permissions) {\n if (!permission.key) {\n throw new ConfigurationError('Every permission needs a non-empty `key`.');\n }\n if (permissionKeys.has(permission.key)) {\n throw new ConfigurationError(`Permission \"${permission.key}\" is declared more than once.`);\n }\n permissionKeys.add(permission.key);\n }\n\n const roleKeys = new Set<string>();\n for (const role of roles) {\n if (!role.key) {\n throw new ConfigurationError('Every role needs a non-empty `key`.');\n }\n if (!role.name) {\n throw new ConfigurationError(`Role \"${role.key}\" needs a non-empty \\`name\\`.`);\n }\n if (roleKeys.has(role.key)) {\n throw new ConfigurationError(`Role \"${role.key}\" is declared more than once.`);\n }\n roleKeys.add(role.key);\n for (const reference of role.permissions) {\n if (!permissionKeys.has(reference)) {\n throw new ConfigurationError(\n `Role \"${role.key}\" references permission \"${reference}\", which is not declared.`,\n );\n }\n }\n }\n}\n\n/** A permission with keys in a fixed order and no `undefined` fields (stable to hash). */\nfunction canonicalPermission(permission: PermissionDefinition): PermissionDefinition {\n return permission.description === undefined\n ? { key: permission.key }\n : { key: permission.key, description: permission.description };\n}\n\n/** A role with keys in a fixed order, sorted permission refs, and no `undefined` fields. */\nfunction canonicalRole(role: RoleDefinition): RoleDefinition {\n const permissions = [...role.permissions].sort(byteCompare);\n return role.description === undefined\n ? { key: role.key, name: role.name, permissions }\n : { key: role.key, name: role.name, description: role.description, permissions };\n}\n\n/**\n * Serialize {permissions, roles} to the exact canonical JSON the PHP reference hashes,\n * so the `version` is byte-for-byte identical across every Cbox ID SDK. Matches PHP\n * `json_encode` defaults: object keys in insertion order, permissions and roles sorted\n * by key, each role's permission refs sorted, an absent-or-empty description emitted as\n * `null`, forward slashes escaped as `\\/`, and every non-ASCII code unit as `\\uXXXX`.\n */\nexport function canonicalManifestJson(\n permissions: PermissionDefinition[],\n roles: RoleDefinition[],\n): string {\n const canonical = {\n permissions: [...permissions]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((p) => ({ key: p.key, description: emptyToNull(p.description) })),\n roles: [...roles]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((r) => ({\n key: r.key,\n name: r.name,\n description: emptyToNull(r.description),\n permissions: [...r.permissions].sort(byteCompare),\n })),\n };\n return escapeLikePhp(JSON.stringify(canonical));\n}\n\n/** PHP treats an absent or empty description as `null` in the hashed catalog. */\nfunction emptyToNull(value: string | undefined): string | null {\n return value === undefined || value === '' ? null : value;\n}\n\n/** Byte-wise (code-unit) comparison — matches PHP `strcmp` on the ASCII-only keys. */\nfunction byteCompare(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Apply PHP `json_encode`'s default `\\/` slash and `\\uXXXX` non-ASCII escaping. */\nfunction escapeLikePhp(json: string): string {\n let out = '';\n for (let i = 0; i < json.length; i++) {\n const char = json.charAt(i);\n const code = json.charCodeAt(i);\n if (char === '/') {\n out += '\\\\/';\n } else if (code > 0x7f) {\n out += '\\\\u' + code.toString(16).padStart(4, '0');\n } else {\n out += char;\n }\n }\n return out;\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n}\n\nasync function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/legacy.ts","../src/frontend.ts","../src/authz.ts"],"names":["key","json"],"mappings":";;;;AAwEO,SAAS,qBAAqB,OAAA,EAAyE;AAC5G,EAAA,IAAI,CAAC,OAAA,CAAQ,MAAA,IAAU,OAAA,CAAQ,MAAA,CAAO,SAAS,EAAA,EAAI;AACjD,IAAA,MAAM,IAAI,kBAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AAEA,EAAA,MAAM,SAAA,GAAY,QAAQ,gBAAA,IAAoB,GAAA;AAE9C,EAAA,OAAO,eAAe,OAAO,OAAA,EAAqC;AAGhE,IAAA,MAAM,GAAA,GAAM,MAAM,OAAA,CAAQ,IAAA,EAAK;AAE/B,IAAA,IAAI,CAAE,MAAM,gBAAA,CAAiB,GAAA,EAAK,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,kBAAkB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EAChE,CAAA,SAAE;AACA,IAAA,YAAA,CAAa,KAAK,CAAA;AAAA,EACpB;AACF;AAWA,SAAS,kBAAkB,MAAA,EAAsC;AAC/D,EAAA,IAAI,CAAC,MAAA,CAAO,GAAA,CAAI,UAAA,CAAW,UAAU,CAAA,EAAG;AACtC,IAAA,MAAM,IAAI,mBAAmB,4FAAuF,CAAA;AAAA,EACtH;AAEA,EAAA,IAAI,CAAC,MAAA,CAAO,MAAA,IAAU,MAAA,CAAO,MAAA,CAAO,SAAS,EAAA,EAAI;AAC/C,IAAA,MAAM,IAAI,mBAAmB,mGAAmG,CAAA;AAAA,EAClI;AACF","file":"index.js","sourcesContent":["import { ConfigurationError } from './errors.js';\n\n/**\n * The handler on YOUR side of a legacy migration.\n *\n * Cbox ID offers it an email and a password it has never seen, and your code answers with\n * the person or with nothing. On a yes they are created in Cbox ID as a result of the\n * login that just succeeded, and from their next sign-in the old system is never asked\n * again.\n *\n * WHY THIS IS A FACTORY AND NOT A DOCUMENT. The wire format is simple enough to describe\n * in a paragraph — a signed POST, JSON in, JSON out — and describing it would mean every\n * customer writes the signature check themselves. That check is exactly the part people\n * get wrong: `===` instead of a constant-time compare, no freshness window, no thought\n * about replay. So the factory owns all of it and you write the one function that knows\n * your own database.\n *\n * It is deliberately framework-agnostic: it takes a `Request` and returns a `Response`,\n * which is what Next.js route handlers, Remix, Hono, Bun and Deno all speak natively.\n */\n\n/** What your handler answers with. Returning `null` means \"no\", and is not an error. */\nexport interface LegacyUser {\n email: string;\n name?: string | null;\n emailVerified?: boolean;\n /**\n * Your stored hash, when you can expose it.\n *\n * Passing it lets the person keep their password in Cbox ID verbatim — it is stored as\n * is and upgraded to the platform hasher on their next login, exactly like a\n * bulk-imported user. Omit it and Cbox ID hashes the password they just proved they\n * know, which is the honest option when your store cannot hand a hash over.\n */\n passwordHash?: string;\n}\n\nexport interface LegacyVerifierOptions {\n /** The same secret you declared in your manifest, or configured in the console. */\n secret: string;\n /**\n * Decide whether these credentials are good, and say who they belong to.\n *\n * Return `null` for no. THROWING IS NOT THE SAME as returning null: a throw means your\n * store could not decide, and is answered with a 503 so Cbox ID refuses the sign-in\n * rather than treating an outage as a wrong password.\n */\n verify: (email: string, password: string) => Promise<LegacyUser | null>;\n /**\n * How far out of date a request may be, in seconds. Defaults to 300.\n *\n * A window is what makes a captured request stop working. Too wide and a recording is\n * useful for hours; too narrow and ordinary clock skew starts refusing real traffic.\n */\n toleranceSeconds?: number;\n}\n\n/**\n * Build the request handler.\n *\n * ```ts\n * // app/api/cbox-legacy/route.ts\n * export const POST = createLegacyVerifier({\n * secret: process.env.CBOX_LEGACY_SECRET!,\n * async verify(email, password) {\n * const row = await db.users.findByEmail(email)\n * if (!row || !(await argon2.verify(row.password, password))) return null\n * return { email: row.email, name: row.name, emailVerified: !!row.confirmedAt }\n * },\n * })\n * ```\n */\nexport function createLegacyVerifier(options: LegacyVerifierOptions): (request: Request) => Promise<Response> {\n if (!options.secret || options.secret.length < 32) {\n throw new ConfigurationError(\n 'A legacy verifier secret must be at least 32 characters; it is the only thing proving a request came from Cbox ID.',\n );\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n\n return async function handle(request: Request): Promise<Response> {\n // Read once. The signature covers the RAW body, so re-serializing parsed JSON would\n // produce different bytes and every valid request would be refused.\n const raw = await request.text();\n\n if (!(await isSignedByCboxId(raw, request.headers.get('X-Cbox-Signature'), options.secret, tolerance))) {\n // No detail. A caller who cannot sign is not owed help distinguishing \"bad\n // signature\" from \"stale timestamp\" — both mean the same thing to anyone\n // legitimate, and the difference is a hint to anyone else.\n return json({ error: 'unauthorized' }, 401);\n }\n\n let payload: { email?: unknown; password?: unknown };\n\n try {\n payload = JSON.parse(raw) as typeof payload;\n } catch {\n return json({ error: 'invalid_request' }, 400);\n }\n\n const { email, password } = payload;\n\n if (typeof email !== 'string' || email === '') {\n return json({ error: 'invalid_request' }, 400);\n }\n\n // No password means Cbox ID is asking \"do you know this address\" — the tooling path,\n // used for a dry run before cutover. It never reaches here from a sign-in.\n if (typeof password !== 'string') {\n return json({ user: null }, 200);\n }\n\n let user: LegacyUser | null;\n\n try {\n user = await options.verify(email, password);\n } catch {\n // 503, not 401. Your store could not decide, and Cbox ID must refuse the sign-in\n // rather than read an outage as a wrong password — but it should also be able to\n // tell the two apart in its own logs, which a 401 would hide.\n return json({ error: 'unavailable' }, 503);\n }\n\n if (!user) {\n return json({ user: null }, 200);\n }\n\n return json(\n {\n email: user.email,\n name: user.name ?? null,\n email_verified: user.emailVerified === true,\n ...(user.passwordHash ? { password_hash: user.passwordHash } : {}),\n },\n 200,\n );\n };\n}\n\n/**\n * Whether this body was signed by Cbox ID, recently.\n *\n * Both halves matter. The HMAC proves it came from something holding the secret; the\n * freshness window is what stops a captured request working forever. Compared in constant\n * time, because a comparison that returns early leaks how much of a guess was right.\n */\nasync function isSignedByCboxId(\n body: string,\n header: string | null,\n secret: string,\n toleranceSeconds: number,\n): Promise<boolean> {\n if (!header) {\n return false;\n }\n\n const parts: Record<string, string> = {};\n\n for (const piece of header.split(',')) {\n const [key, value] = piece.split('=', 2);\n if (key && value) {\n parts[key.trim()] = value.trim();\n }\n }\n\n const timestamp = parts['t'] ?? '';\n const signature = parts['v1'] ?? '';\n\n if (!/^\\d+$/.test(timestamp) || signature === '') {\n return false;\n }\n\n if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > toleranceSeconds) {\n return false;\n }\n\n const key = await crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n\n const mac = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${timestamp}.${body}`));\n const expected = [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, '0')).join('');\n\n return timingSafeEqual(expected, signature);\n}\n\n/** Constant-time string compare. Length is not secret; content is. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n let diff = 0;\n\n for (let i = 0; i < a.length; i++) {\n diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n\n return diff === 0;\n}\n\nfunction json(body: unknown, status: number): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: { 'Content-Type': 'application/json' },\n });\n}\n","import { ConfigurationError, FrontendApiError } from './errors.js';\n\n/**\n * The browser-safe half of the SDK.\n *\n * Everything else in this package assumes a server: it holds a client secret, it exchanges\n * codes, it verifies webhooks. None of that may run in a page, which is why the UI\n * components have always been redirect shells — a page that cannot authenticate itself to\n * the identity provider cannot ask it anything, so it sends the person away and waits.\n *\n * A publishable key changes that. It is public on purpose: it ships in your bundle, it is\n * visible in devtools, and it is safe there because it only works from the origins you\n * registered. What it buys is that a page can read its OWN sign-in configuration — the\n * endpoints, the social buttons, your theme — and render a form itself.\n *\n * This client deliberately has no secret, no token storage and no crypto. It reads two\n * documents. Anything that mints or holds a credential still belongs on your server.\n */\n\n/** How a page identifies itself. Public — put it in your bundle. */\nexport interface FrontendClientOptions {\n /** Your identity provider's origin, e.g. `https://id.acme.com`. */\n issuer: string;\n /** `pk_live_…` or `pk_test_…`. Safe to publish. */\n publishableKey: string;\n /** Abort after this long. Defaults to 10s. */\n timeoutMs?: number;\n /**\n * How many times to retry a transient failure. Defaults to 2 (so three attempts).\n *\n * Only the network and 5xx are retried. A refusal is a configuration problem and\n * retrying it just delays the developer finding out; a 429 is honoured rather than\n * hammered.\n */\n retries?: number;\n /** Injectable for tests and for runtimes with a non-global fetch. */\n fetch?: typeof globalThis.fetch;\n}\n\n/** A social button to draw. Name and provider only — never an internal id. */\nexport interface SocialProvider {\n provider: string;\n name: string;\n}\n\n/** The customer's theme, when they have set one. Absent means \"use your own defaults\". */\nexport interface Appearance {\n preset: string;\n radius: string;\n font: string;\n light: Record<string, string>;\n dark: Record<string, string>;\n}\n\n/** Everything needed to draw a sign-in box, and nothing that identifies anybody. */\nexport interface FrontendConfig {\n mode: 'test' | 'live' | null;\n issuer: string;\n endpoints: {\n authorization: string;\n token: string;\n userinfo: string;\n end_session: string;\n jwks: string;\n };\n social: SocialProvider[];\n appearance?: Appearance;\n}\n\n/** Who the browser is signed in as, or nobody. */\nexport interface FrontendSession {\n user: { id: string; email: string; name: string | null } | null;\n}\n\n/**\n * Reads the public configuration and the current session from a browser.\n *\n * ```ts\n * const frontend = new CboxIdFrontend({\n * issuer: 'https://id.acme.com',\n * publishableKey: 'pk_live_…',\n * })\n *\n * const config = await frontend.config() // cached for you; safe to call per component\n * const { user } = await frontend.session(accessToken)\n * ```\n */\nexport class CboxIdFrontend {\n private readonly issuer: string;\n private readonly publishableKey: string;\n private readonly timeoutMs: number;\n private readonly retries: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n /**\n * The config document, and the in-flight promise for it.\n *\n * Deduplicated rather than merely cached: a page with a sign-in form, a user button and\n * an organization switcher mounts three components in the same tick, and three parallel\n * fetches of the same immutable document is a waste the SDK should absorb rather than\n * ask every consumer to.\n */\n private configPromise: Promise<FrontendConfig> | null = null;\n\n constructor(options: FrontendClientOptions) {\n if (!options.issuer) {\n throw new ConfigurationError('issuer is required.');\n }\n\n // Caught here rather than at the first request, because the failure otherwise arrives\n // as an opaque 401 from the network tab and the cause — a secret key pasted into a\n // browser bundle — is exactly the mistake worth naming out loud.\n if (!options.publishableKey?.startsWith('pk_')) {\n throw new ConfigurationError(\n 'publishableKey must be a pk_test_… or pk_live_… key. Client secrets and API keys must never be put in a browser.',\n );\n }\n\n this.issuer = options.issuer.replace(/\\/$/, '');\n this.publishableKey = options.publishableKey;\n this.timeoutMs = options.timeoutMs ?? 10_000;\n this.retries = Math.max(0, options.retries ?? 2);\n this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);\n }\n\n /** Whether this key drives real sign-ins. Handy for a \"test mode\" badge in your own UI. */\n get isLive(): boolean {\n return this.publishableKey.startsWith('pk_live_');\n }\n\n /**\n * The public sign-in configuration.\n *\n * Fetched once per client instance. The document is small and changes when somebody\n * edits it in the console, so a long-lived page picks changes up on its next full load\n * rather than mid-session — which is the right trade for something that decides layout.\n */\n async config(): Promise<FrontendConfig> {\n this.configPromise ??= this.get<FrontendConfig>('/frontend/v1/config', {}, isFrontendConfig).catch((error: unknown) => {\n // Cleared so a transient network failure does not poison the instance for the\n // lifetime of the page.\n this.configPromise = null;\n throw error;\n });\n\n return this.configPromise;\n }\n\n /**\n * Who is signed in, given an access token your app already holds.\n *\n * Returns `{ user: null }` rather than throwing when nobody is signed in. That is a\n * state, not an error: a user button renders on pages nobody has signed in on, and\n * making callers treat a rejection as a state is how flash-of-signed-out bugs happen.\n *\n * The publishable key grants nothing here — the token is the entire authority.\n */\n async session(accessToken?: string): Promise<FrontendSession> {\n if (!accessToken) {\n return { user: null };\n }\n\n return this.get<FrontendSession>(\n '/frontend/v1/session',\n { Authorization: `Bearer ${accessToken}` },\n isFrontendSession,\n );\n }\n\n private async get<T>(\n path: string,\n extraHeaders: Record<string, string> = {},\n validate?: (body: unknown) => body is T,\n ): Promise<T> {\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= this.retries; attempt++) {\n // Linear, not exponential, and only between attempts. This sits inside a page\n // render: a caller waiting on their sign-in box would rather fail in a second than\n // succeed in eight.\n if (attempt > 0) {\n await new Promise((resolve) => setTimeout(resolve, 150 * attempt));\n }\n\n try {\n return await this.attempt<T>(path, extraHeaders, validate);\n } catch (error) {\n lastError = error;\n\n // Retry only what a retry can fix. A refusal is a configuration problem and\n // retrying it delays the developer finding out; a rate limit is honoured rather\n // than hammered; a malformed body will be malformed again.\n if (!(error instanceof FrontendApiError) || error.code !== 'unavailable') {\n throw error;\n }\n }\n }\n\n throw lastError;\n }\n\n private async attempt<T>(\n path: string,\n extraHeaders: Record<string, string>,\n validate?: (body: unknown) => body is T,\n ): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n\n try {\n response = await this.fetchImpl(`${this.issuer}${path}`, {\n headers: {\n // A header, never a query string: a query string puts the key in server logs,\n // in `Referer` on every outbound link, and in browser history.\n 'X-Cbox-Publishable-Key': this.publishableKey,\n Accept: 'application/json',\n ...extraHeaders,\n },\n signal: controller.signal,\n });\n } catch (cause) {\n // Includes the abort on timeout, and — in a browser — a refusal, because a refused\n // request deliberately carries no CORS headers and so never becomes a Response.\n throw new FrontendApiError(\n `Could not reach Cbox ID at ${this.issuer}. If this is a browser, check that this page's origin is on the key's allow-list — a refused request fails as a network error by design.`,\n 'unavailable',\n );\n } finally {\n clearTimeout(timer);\n }\n\n if (response.status === 429) {\n const retryAfter = Number(response.headers.get('Retry-After') ?? '');\n\n throw new FrontendApiError(\n 'Cbox ID is rate limiting this key.',\n 'rate_limited',\n 429,\n Number.isFinite(retryAfter) ? retryAfter : undefined,\n );\n }\n\n if (response.status === 401 || response.status === 403) {\n throw new FrontendApiError(\n `Cbox ID refused the request (${response.status}). Check that this page's origin is on the key's allow-list, and that the key is not revoked.`,\n 'origin_not_allowed',\n response.status,\n );\n }\n\n if (!response.ok) {\n throw new FrontendApiError(\n `Cbox ID returned ${response.status}.`,\n 'unavailable',\n response.status,\n );\n }\n\n let body: unknown;\n\n try {\n body = await response.json();\n } catch {\n throw new FrontendApiError('Cbox ID returned a body that is not JSON.', 'malformed', response.status);\n }\n\n // A 200 whose body is not the document we expect means something between the page and\n // us is rewriting responses — a proxy, an extension, a captive portal. Caught here so\n // it surfaces as that, rather than as `undefined` deep inside somebody's component.\n if (validate && !validate(body)) {\n throw new FrontendApiError(\n 'Cbox ID returned a body that is not the expected document.',\n 'malformed',\n response.status,\n );\n }\n\n return body as T;\n }\n}\n\n/** The shape check for the config document. Structural, not exhaustive. */\nfunction isFrontendConfig(body: unknown): body is FrontendConfig {\n if (typeof body !== 'object' || body === null) {\n return false;\n }\n\n const doc = body as Partial<FrontendConfig>;\n\n return typeof doc.issuer === 'string' && typeof doc.endpoints === 'object' && doc.endpoints !== null;\n}\n\n/** The shape check for the session document. `user: null` is valid and expected. */\nfunction isFrontendSession(body: unknown): body is FrontendSession {\n return typeof body === 'object' && body !== null && 'user' in body;\n}\n","import { Discovery } from './discovery.js';\nimport { AuthenticationError, ConfigurationError } from './errors.js';\n\n/**\n * A permission your app declares. `key` is a `feature:action` slug (e.g.\n * `invoices:create`); `description` is human-facing copy for the Cbox ID console.\n */\nexport interface PermissionDefinition {\n key: string;\n description?: string;\n}\n\n/**\n * A role your app declares. `permissions` lists the permission keys the role\n * grants — each must reference a declared {@link PermissionDefinition}.\n */\nexport interface RoleDefinition {\n key: string;\n name: string;\n description?: string;\n permissions: string[];\n}\n\n/**\n * The roles + permissions an app declares in code. Either list may be omitted.\n * Pass this to {@link defineAuthz} (to validate up front) or straight to\n * {@link buildManifest} / {@link publishManifest}.\n */\nexport interface AuthzDeclaration {\n permissions?: PermissionDefinition[];\n roles?: RoleDefinition[];\n /**\n * Where this app's OLD login lives, while you are migrating off it.\n *\n * Declared here for the same reason roles are: it is a fact about the app, it belongs\n * with the deploy, and the alternative is a URL pasted into a console and a secret\n * pasted into an env file that quietly disagree six weeks later.\n *\n * IT DOES NOT TAKE EFFECT ON ITS OWN. Unlike a role — which affects only the app that\n * declared it — this names a URL that every unknown email and the password typed with\n * it will be offered to, on the environment's whole sign-in path. So it arrives as a\n * proposal and an operator has to approve it in the console. Changing the url later\n * drops that approval, on purpose.\n */\n legacyLogin?: LegacyLoginDeclaration;\n}\n\n/** Where an app's old login lives. See {@link AuthzDeclaration.legacyLogin}. */\nexport interface LegacyLoginDeclaration {\n /** Must be https — a password in the clear is readable by everything on the path. */\n url: string;\n /** At least 32 characters. It is the only thing proving a request came from Cbox ID. */\n secret: string;\n}\n\n/**\n * The manifest as it is sent to Cbox ID: the declared permissions + roles plus a\n * content-derived `version`, so republishing an unchanged catalog is a no-op.\n */\nexport interface AuthzManifest {\n version: string;\n permissions: PermissionDefinition[];\n roles: RoleDefinition[];\n legacy_login?: LegacyLoginDeclaration;\n}\n\n/** What {@link publishManifest} needs to authenticate the push. */\nexport interface ManifestPublisherConfig {\n /** Base URL (issuer) of the Cbox ID instance — the `token_endpoint` is discovered from it. */\n issuer: string;\n /** Your OAuth client id. The client must hold the `apps.manifest` scope. */\n clientId: string;\n /** Your OAuth client secret. The push uses the client-credentials grant. */\n clientSecret: string;\n /** Timeout (ms) for back-channel HTTP calls. Defaults to `10000`. */\n timeoutMs?: number;\n}\n\n/**\n * The server's sync summary. The named fields are the ones the SDK/CLI reads;\n * the index signature keeps any extra fields the server returns.\n */\nexport interface ManifestSyncSummary {\n unchanged?: boolean;\n roles_declared?: number;\n permissions_declared?: number;\n version?: string;\n [key: string]: unknown;\n}\n\n/**\n * Validate a roles/permissions declaration and return it normalized (both lists\n * always present). Call this where you declare your catalog so mistakes — a role\n * that grants an undeclared permission, a duplicate key — surface immediately\n * rather than on deploy.\n *\n * @throws ConfigurationError on a missing key/name, a duplicate, or a role that\n * references a permission that was never declared.\n */\nexport function defineAuthz(\n declaration: AuthzDeclaration,\n): AuthzDeclaration & { permissions: PermissionDefinition[]; roles: RoleDefinition[] } {\n const permissions = declaration.permissions ?? [];\n const roles = declaration.roles ?? [];\n assertDeclaration(permissions, roles);\n\n // The legacy login is validated here too, so a bad one fails in the deploy that\n // introduced it rather than as a 4xx from a manifest push somebody has to go and read.\n if (declaration.legacyLogin) {\n assertLegacyLogin(declaration.legacyLogin);\n }\n\n // `Required<>` no longer fits: the catalog is always present after this, and the legacy\n // login legitimately is not. Returning the declaration's own optionality keeps a caller\n // from having to invent an empty one.\n return { ...declaration, permissions, roles };\n}\n\n/**\n * Build the manifest — the declared catalog plus a stable content hash `version`\n * (first 16 hex chars of the sha256 of the canonicalized catalog). The catalog is\n * sorted by key first, so declaration order never changes the version.\n */\nexport async function buildManifest(declaration: AuthzDeclaration): Promise<AuthzManifest> {\n const permissions = (declaration.permissions ?? []).map(canonicalPermission);\n const roles = (declaration.roles ?? []).map(canonicalRole);\n assertDeclaration(permissions, roles);\n\n permissions.sort((a, b) => byteCompare(a.key, b.key));\n roles.sort((a, b) => byteCompare(a.key, b.key));\n\n // The version hashes the CATALOG only, and the legacy login is deliberately outside it:\n // this canonicalization is a cross-SDK contract — id-js, id-python, id-go and the PHP\n // reference all produce the same bytes, and a shared fixture exists to keep them from\n // drifting. The server compares a declared url separately for the same reason.\n const version = (await sha256Hex(canonicalManifestJson(permissions, roles))).slice(0, 16);\n\n const manifest: AuthzManifest = { version, permissions, roles };\n\n if (declaration.legacyLogin) {\n assertLegacyLogin(declaration.legacyLogin);\n manifest.legacy_login = declaration.legacyLogin;\n }\n\n return manifest;\n}\n\n/**\n * Publish this app's authorization manifest (its declared roles + permissions) to\n * Cbox ID. The app owns what a role means; Cbox ID owns identity and who holds it.\n *\n * It mints a client-credentials token with the `apps.manifest` scope (token\n * endpoint discovered from the issuer's OIDC configuration), then POSTs the\n * manifest to `{issuer}/api/v1/apps/manifest`. Run it on deploy or from a script;\n * an unchanged catalog is a server-side no-op.\n *\n * @returns the server's sync summary (`unchanged`, `roles_declared`, …).\n * @throws ConfigurationError when config or the declaration is invalid.\n * @throws AuthenticationError when the token cannot be minted or the push fails.\n */\nexport async function publishManifest(\n config: ManifestPublisherConfig,\n declaration: AuthzDeclaration,\n): Promise<ManifestSyncSummary> {\n if (!config.issuer || !config.clientId || !config.clientSecret) {\n throw new ConfigurationError('Publishing a manifest needs issuer, clientId and clientSecret.');\n }\n\n const timeoutMs = config.timeoutMs ?? 10_000;\n const manifest = await buildManifest(declaration);\n const discovery = new Discovery(config.issuer, timeoutMs, 3_600_000);\n\n const token = await mintToken(config, discovery, timeoutMs);\n\n const response = await fetchWithTimeout(\n `${config.issuer.replace(/\\/$/, '')}/api/v1/apps/manifest`,\n {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n accept: 'application/json',\n 'content-type': 'application/json',\n },\n body: JSON.stringify(manifest),\n },\n timeoutMs,\n );\n\n if (!response.ok) {\n throw new AuthenticationError(`Manifest push failed: HTTP ${response.status} ${await response.text()}`);\n }\n\n const json = (await response.json()) as unknown;\n return json !== null && typeof json === 'object' ? (json as ManifestSyncSummary) : {};\n}\n\nasync function mintToken(\n config: ManifestPublisherConfig,\n discovery: Discovery,\n timeoutMs: number,\n): Promise<string> {\n const response = await fetchWithTimeout(\n await discovery.endpoint('token_endpoint'),\n {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n scope: 'apps.manifest',\n }),\n },\n timeoutMs,\n );\n\n const json = (await response.json().catch(() => ({}))) as { access_token?: unknown };\n if (typeof json.access_token !== 'string' || json.access_token === '') {\n throw new AuthenticationError(\n 'Could not obtain an apps.manifest access token — check the client credentials and that the client holds the apps.manifest scope.',\n );\n }\n return json.access_token;\n}\n\nfunction assertDeclaration(permissions: PermissionDefinition[], roles: RoleDefinition[]): void {\n const permissionKeys = new Set<string>();\n for (const permission of permissions) {\n if (!permission.key) {\n throw new ConfigurationError('Every permission needs a non-empty `key`.');\n }\n if (permissionKeys.has(permission.key)) {\n throw new ConfigurationError(`Permission \"${permission.key}\" is declared more than once.`);\n }\n permissionKeys.add(permission.key);\n }\n\n const roleKeys = new Set<string>();\n for (const role of roles) {\n if (!role.key) {\n throw new ConfigurationError('Every role needs a non-empty `key`.');\n }\n if (!role.name) {\n throw new ConfigurationError(`Role \"${role.key}\" needs a non-empty \\`name\\`.`);\n }\n if (roleKeys.has(role.key)) {\n throw new ConfigurationError(`Role \"${role.key}\" is declared more than once.`);\n }\n roleKeys.add(role.key);\n for (const reference of role.permissions) {\n if (!permissionKeys.has(reference)) {\n throw new ConfigurationError(\n `Role \"${role.key}\" references permission \"${reference}\", which is not declared.`,\n );\n }\n }\n }\n}\n\n/** A permission with keys in a fixed order and no `undefined` fields (stable to hash). */\nfunction canonicalPermission(permission: PermissionDefinition): PermissionDefinition {\n return permission.description === undefined\n ? { key: permission.key }\n : { key: permission.key, description: permission.description };\n}\n\n/** A role with keys in a fixed order, sorted permission refs, and no `undefined` fields. */\nfunction canonicalRole(role: RoleDefinition): RoleDefinition {\n const permissions = [...role.permissions].sort(byteCompare);\n return role.description === undefined\n ? { key: role.key, name: role.name, permissions }\n : { key: role.key, name: role.name, description: role.description, permissions };\n}\n\n/**\n * Serialize {permissions, roles} to the exact canonical JSON the PHP reference hashes,\n * so the `version` is byte-for-byte identical across every Cbox ID SDK. Matches PHP\n * `json_encode` defaults: object keys in insertion order, permissions and roles sorted\n * by key, each role's permission refs sorted, an absent-or-empty description emitted as\n * `null`, forward slashes escaped as `\\/`, and every non-ASCII code unit as `\\uXXXX`.\n */\nexport function canonicalManifestJson(\n permissions: PermissionDefinition[],\n roles: RoleDefinition[],\n): string {\n const canonical = {\n permissions: [...permissions]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((p) => ({ key: p.key, description: emptyToNull(p.description) })),\n roles: [...roles]\n .sort((a, b) => byteCompare(a.key, b.key))\n .map((r) => ({\n key: r.key,\n name: r.name,\n description: emptyToNull(r.description),\n permissions: [...r.permissions].sort(byteCompare),\n })),\n };\n return escapeLikePhp(JSON.stringify(canonical));\n}\n\n/** PHP treats an absent or empty description as `null` in the hashed catalog. */\nfunction emptyToNull(value: string | undefined): string | null {\n return value === undefined || value === '' ? null : value;\n}\n\n/** Byte-wise (code-unit) comparison — matches PHP `strcmp` on the ASCII-only keys. */\nfunction byteCompare(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Apply PHP `json_encode`'s default `\\/` slash and `\\uXXXX` non-ASCII escaping. */\nfunction escapeLikePhp(json: string): string {\n let out = '';\n for (let i = 0; i < json.length; i++) {\n const char = json.charAt(i);\n const code = json.charCodeAt(i);\n if (char === '/') {\n out += '\\\\/';\n } else if (code > 0x7f) {\n out += '\\\\u' + code.toString(16).padStart(4, '0');\n } else {\n out += char;\n }\n }\n return out;\n}\n\nasync function sha256Hex(input: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));\n return Array.from(new Uint8Array(digest))\n .map((byte) => byte.toString(16).padStart(2, '0'))\n .join('');\n}\n\nasync function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Refuse a legacy login declaration the server would refuse anyway.\n *\n * Checked in the SDK so it fails at build time, in the deploy that introduced it, rather\n * than as a 4xx from a manifest push somebody has to go and read. Both rules are the\n * server's and are restated here rather than inferred: https because a password in the\n * clear is readable by everything on the path, and a real secret because it is the only\n * thing proving a request came from Cbox ID.\n */\nfunction assertLegacyLogin(legacy: LegacyLoginDeclaration): void {\n if (!legacy.url.startsWith('https://')) {\n throw new ConfigurationError('legacyLogin.url must be https — a password must never cross the network in the clear.');\n }\n\n if (!legacy.secret || legacy.secret.length < 32) {\n throw new ConfigurationError('legacyLogin.secret must be at least 32 characters; it is what proves a request came from Cbox ID.');\n }\n}\n"]}
|
package/dist/nextjs.cjs
CHANGED
|
@@ -565,7 +565,7 @@ var CboxIdClient = class {
|
|
|
565
565
|
}
|
|
566
566
|
accountPath() {
|
|
567
567
|
const path = this.config.accountPath;
|
|
568
|
-
return path && path !== "" ? `/${path.replace(/^\//, "")}` : "/
|
|
568
|
+
return path && path !== "" ? `/${path.replace(/^\//, "")}` : "/account";
|
|
569
569
|
}
|
|
570
570
|
requireSecret() {
|
|
571
571
|
if (!this.config.clientSecret) {
|