@cboxdk/id-js 0.18.0 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +185 -0
- package/README.md +121 -4
- package/RELEASE-CANDIDATE.md +11 -0
- package/dist/api-keys-BE3R3q_A.d.ts +105 -0
- package/dist/api-keys-C8-Q4eFA.d.cts +105 -0
- package/dist/chunk-EVZ6RB3K.js +98 -0
- package/dist/chunk-EVZ6RB3K.js.map +1 -0
- package/dist/{chunk-CXGKOJRJ.js → chunk-YGLMLIKL.js} +144 -9
- package/dist/chunk-YGLMLIKL.js.map +1 -0
- package/dist/{client-BxUHm5hX.d.cts → client-BT-jOm0p.d.cts} +126 -2
- package/dist/{client-BSZASrMo.d.ts → client-xlEJalu8.d.ts} +126 -2
- package/dist/decisions-C84Fzah4.d.ts +23 -0
- package/dist/decisions-DNd9UXwi.d.cts +23 -0
- package/dist/index.cjs +338 -28
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +84 -6
- package/dist/index.d.ts +84 -6
- package/dist/index.js +87 -15
- package/dist/index.js.map +1 -1
- package/dist/management.cjs +1115 -62
- package/dist/management.cjs.map +1 -1
- package/dist/management.d.cts +3618 -135
- package/dist/management.d.ts +3618 -135
- package/dist/management.js +1115 -63
- package/dist/management.js.map +1 -1
- package/dist/nextjs.cjs +136 -5
- package/dist/nextjs.cjs.map +1 -1
- package/dist/nextjs.d.cts +4 -3
- package/dist/nextjs.d.ts +4 -3
- package/dist/nextjs.js +1 -1
- package/dist/server.cjs +103 -9
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +3 -105
- package/dist/server.d.ts +3 -105
- package/dist/server.js +1 -0
- package/dist/{types-BYZldock.d.cts → types-CC1bz68x.d.cts} +30 -1
- package/dist/{types-BYZldock.d.ts → types-CC1bz68x.d.ts} +30 -1
- package/package.json +8 -3
- package/dist/chunk-CXGKOJRJ.js.map +0 -1
package/dist/nextjs.d.cts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { NextResponse, NextRequest } from 'next/server';
|
|
2
|
-
import { ApiKeyVerification } from './
|
|
3
|
-
import { C as CboxIdClient } from './client-
|
|
4
|
-
import { A as AuthorizationRequestOptions, C as CboxUser, a as CboxIdConfig } from './types-
|
|
2
|
+
import { a as ApiKeyVerification } from './api-keys-C8-Q4eFA.cjs';
|
|
3
|
+
import { C as CboxIdClient } from './client-BT-jOm0p.cjs';
|
|
4
|
+
import { A as AuthorizationRequestOptions, C as CboxUser, a as CboxIdConfig } from './types-CC1bz68x.cjs';
|
|
5
|
+
import './errors-D61xljZE.cjs';
|
|
5
6
|
|
|
6
7
|
interface CboxIdNext {
|
|
7
8
|
/** The underlying framework-agnostic client. */
|
package/dist/nextjs.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { NextResponse, NextRequest } from 'next/server';
|
|
2
|
-
import { ApiKeyVerification } from './
|
|
3
|
-
import { C as CboxIdClient } from './client-
|
|
4
|
-
import { A as AuthorizationRequestOptions, C as CboxUser, a as CboxIdConfig } from './types-
|
|
2
|
+
import { a as ApiKeyVerification } from './api-keys-BE3R3q_A.js';
|
|
3
|
+
import { C as CboxIdClient } from './client-xlEJalu8.js';
|
|
4
|
+
import { A as AuthorizationRequestOptions, C as CboxUser, a as CboxIdConfig } from './types-CC1bz68x.js';
|
|
5
|
+
import './errors-D61xljZE.js';
|
|
5
6
|
|
|
6
7
|
interface CboxIdNext {
|
|
7
8
|
/** The underlying framework-agnostic client. */
|
package/dist/nextjs.js
CHANGED
package/dist/server.cjs
CHANGED
|
@@ -158,16 +158,16 @@ var ApiKeyVerifier = class {
|
|
|
158
158
|
if (typeof body !== "object" || body === null) {
|
|
159
159
|
throw new AuthenticationError("API key verification returned a body that is not a JSON object.");
|
|
160
160
|
}
|
|
161
|
-
const
|
|
162
|
-
if (
|
|
161
|
+
const record2 = body;
|
|
162
|
+
if (record2["active"] !== true) {
|
|
163
163
|
return { active: false };
|
|
164
164
|
}
|
|
165
|
-
const keyId =
|
|
166
|
-
const sub =
|
|
167
|
-
const org =
|
|
168
|
-
const clientId =
|
|
169
|
-
const expiresAt =
|
|
170
|
-
const permissions =
|
|
165
|
+
const keyId = record2["key_id"];
|
|
166
|
+
const sub = record2["sub"];
|
|
167
|
+
const org = record2["org"];
|
|
168
|
+
const clientId = record2["client_id"];
|
|
169
|
+
const expiresAt = record2["expires_at"];
|
|
170
|
+
const permissions = record2["permissions"];
|
|
171
171
|
if (!nonEmpty(keyId) || !nonEmpty(sub) || !nonEmpty(org) || !nonEmpty(clientId) || !Array.isArray(permissions) || expiresAt !== null && expiresAt !== void 0 && typeof expiresAt !== "string") {
|
|
172
172
|
throw new AuthenticationError("API key verification returned an active answer without the promised fields.");
|
|
173
173
|
}
|
|
@@ -182,7 +182,7 @@ var ApiKeyVerifier = class {
|
|
|
182
182
|
return { active: false };
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
|
-
const role =
|
|
185
|
+
const role = record2["org_role"];
|
|
186
186
|
return {
|
|
187
187
|
active: true,
|
|
188
188
|
key_id: keyId,
|
|
@@ -214,7 +214,101 @@ async function digest(key) {
|
|
|
214
214
|
return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
215
215
|
}
|
|
216
216
|
|
|
217
|
+
// src/decisions.ts
|
|
218
|
+
var PermissionDecision = class {
|
|
219
|
+
constructor(subject, organization, clientId, organizationRole, organizationActive, permissions) {
|
|
220
|
+
this.subject = subject;
|
|
221
|
+
this.organization = organization;
|
|
222
|
+
this.clientId = clientId;
|
|
223
|
+
this.organizationRole = organizationRole;
|
|
224
|
+
this.organizationActive = organizationActive;
|
|
225
|
+
this.permissions = permissions;
|
|
226
|
+
}
|
|
227
|
+
subject;
|
|
228
|
+
organization;
|
|
229
|
+
clientId;
|
|
230
|
+
organizationRole;
|
|
231
|
+
organizationActive;
|
|
232
|
+
permissions;
|
|
233
|
+
allows(permission) {
|
|
234
|
+
return this.organizationActive && this.permissions[permission] === true;
|
|
235
|
+
}
|
|
236
|
+
allowed() {
|
|
237
|
+
const values = Object.values(this.permissions);
|
|
238
|
+
return this.organizationActive && values.length > 0 && values.every((value) => value === true);
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
async function checkPermissions(config, accessToken, subject, organization, permissions) {
|
|
242
|
+
assertSecureIssuer(config.issuer);
|
|
243
|
+
const issuer = new URL(config.issuer);
|
|
244
|
+
if (issuer.username || issuer.password || issuer.search || issuer.hash || !config.clientId || !subject || organization === "" || !accessToken || accessToken.length > 32768 || /[\x00-\x20\x7f]/.test(accessToken) || !permissions.length || permissions.length > 50 || permissions.some((permission) => !permission.trim() || new TextEncoder().encode(permission).length > 255)) {
|
|
245
|
+
throw new ConfigurationError("Permission decision request is not configured or valid.");
|
|
246
|
+
}
|
|
247
|
+
const requested = [...new Set(permissions)];
|
|
248
|
+
try {
|
|
249
|
+
const response = await fetch(`${config.issuer.replace(/\/$/, "")}/oauth/decisions`, {
|
|
250
|
+
method: "POST",
|
|
251
|
+
redirect: "error",
|
|
252
|
+
cache: "no-store",
|
|
253
|
+
signal: AbortSignal.timeout(Math.max(1, config.timeoutMs ?? 1e4)),
|
|
254
|
+
headers: { authorization: `Bearer ${accessToken}`, accept: "application/json", "content-type": "application/json" },
|
|
255
|
+
body: JSON.stringify({ subject, org: organization, permission: requested })
|
|
256
|
+
});
|
|
257
|
+
if (response.status !== 200) {
|
|
258
|
+
await response.body?.cancel();
|
|
259
|
+
throw new AuthenticationError("Permission decision could not be verified.", void 0, void 0, response.status);
|
|
260
|
+
}
|
|
261
|
+
const reader = response.body?.getReader();
|
|
262
|
+
if (!reader) throw new AuthenticationError("Permission decision response is invalid.");
|
|
263
|
+
let size = 0;
|
|
264
|
+
let raw = "";
|
|
265
|
+
const decoder = new TextDecoder();
|
|
266
|
+
try {
|
|
267
|
+
for (; ; ) {
|
|
268
|
+
const { value, done } = await reader.read();
|
|
269
|
+
if (done) break;
|
|
270
|
+
size += value.byteLength;
|
|
271
|
+
if (size > 65536) throw new AuthenticationError("Permission decision response exceeded its limit.");
|
|
272
|
+
raw += decoder.decode(value, { stream: true });
|
|
273
|
+
}
|
|
274
|
+
raw += decoder.decode();
|
|
275
|
+
} finally {
|
|
276
|
+
await reader.cancel();
|
|
277
|
+
reader.releaseLock();
|
|
278
|
+
}
|
|
279
|
+
const data = JSON.parse(raw);
|
|
280
|
+
if (!record(data) || !record(data.subject) || data.mode !== "rbac" || data.subject.type !== "user" || data.subject.id !== subject || data.organization !== organization || data.client_id !== config.clientId || typeof data.organization_active !== "boolean" || typeof data.allowed !== "boolean" || !(data.org_role === null || typeof data.org_role === "string" && ["owner", "admin", "developer", "member", "viewer"].includes(data.org_role)) || !Array.isArray(data.results) || data.results.length !== requested.length) {
|
|
281
|
+
throw new AuthenticationError("Permission decision response binding is invalid.");
|
|
282
|
+
}
|
|
283
|
+
const checks = /* @__PURE__ */ Object.create(null);
|
|
284
|
+
for (const result of data.results) {
|
|
285
|
+
if (!record(result) || typeof result.permission !== "string" || typeof result.allowed !== "boolean" || !requested.includes(result.permission) || Object.hasOwn(checks, result.permission)) {
|
|
286
|
+
throw new AuthenticationError("Permission decision result is invalid.");
|
|
287
|
+
}
|
|
288
|
+
checks[result.permission] = result.allowed;
|
|
289
|
+
}
|
|
290
|
+
const decision = new PermissionDecision(
|
|
291
|
+
subject,
|
|
292
|
+
organization,
|
|
293
|
+
config.clientId,
|
|
294
|
+
data.org_role,
|
|
295
|
+
data.organization_active,
|
|
296
|
+
Object.freeze(checks)
|
|
297
|
+
);
|
|
298
|
+
if (data.allowed !== decision.allowed()) throw new AuthenticationError("Permission decision result is inconsistent.");
|
|
299
|
+
return decision;
|
|
300
|
+
} catch (error) {
|
|
301
|
+
if (error instanceof AuthenticationError) throw error;
|
|
302
|
+
throw new AuthenticationError("Permission decision could not be verified.");
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function record(value) {
|
|
306
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
307
|
+
}
|
|
308
|
+
|
|
217
309
|
exports.ApiKeyVerifier = ApiKeyVerifier;
|
|
218
310
|
exports.MAX_API_KEY_CACHE_TTL_MS = MAX_API_KEY_CACHE_TTL_MS;
|
|
311
|
+
exports.PermissionDecision = PermissionDecision;
|
|
312
|
+
exports.checkPermissions = checkPermissions;
|
|
219
313
|
//# sourceMappingURL=server.cjs.map
|
|
220
314
|
//# sourceMappingURL=server.cjs.map
|
package/dist/server.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/issuer.ts","../src/api-keys.ts"],"names":[],"mappings":";;;AAIO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAAA,EACzB;AACF,CAAA;AAGO,IAAM,kBAAA,GAAN,cAAiC,WAAA,CAAY;AAAC,CAAA;AAmB9C,IAAM,mBAAA,GAAN,cAAkC,WAAA,CAAY;AAAA,EACnD,WAAA,CACE,OAAA,EAES,KAAA,EAEA,gBAAA,EAEA,QAUA,UAAA,EACT;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAhBJ,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAEA,IAAA,IAAA,CAAA,gBAAA,GAAA,gBAAA;AAEA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAUA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAGX;AAAA,EAjBW,KAAA;AAAA,EAEA,gBAAA;AAAA,EAEA,MAAA;AAAA,EAUA,UAAA;AAAA;AAAA,EAMX,IAAI,aAAA,GAAyB;AAC3B,IAAA,OAAO,KAAK,MAAA,KAAW,GAAA;AAAA,EACzB;AACF,CAAA;AAUA,eAAsB,UAAA,CAAW,UAA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,MAAA,IAAI,CAAC,OAAO,IAAA,EAAM;AAChB,QAAA,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,MAAA,CAAO,KAAK,CAAA;AAAA,MAChC;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,MAAM,GAAA,CAAI,QAAA,EAAU,EAAE,MAAA,EAAQ,OAAO,CAAA;AAAA,EAC5C;AACF;AAEA,SAAS,SAAS,KAAA,EAAiC;AACjD,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,EAAA;AAChD;AAGA,eAAe,OAAO,GAAA,EAA8B;AAClD,EAAA,MAAM,KAAA,GAAQ,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,GAAG,CAAC,CAAA;AACjF,EAAA,OAAO,MAAM,IAAA,CAAK,IAAI,WAAW,KAAK,CAAA,EAAG,CAAC,IAAA,KAAS,IAAA,CAAK,QAAA,CAAS,EAAE,EAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAChG","file":"server.cjs","sourcesContent":["/**\n * Base class for every error this SDK throws, so callers can `catch (e) { if (e\n * instanceof CboxIdError) ... }` in one branch.\n */\nexport class CboxIdError extends Error {\n constructor(message: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\n/** The client is misconfigured (a required option is missing or empty). */\nexport class ConfigurationError extends CboxIdError {}\n\n/**\n * The login `state` did not match what was stored — the callback is forged or\n * stale. Treat as a fresh start, not an error to surface to the user.\n */\nexport class InvalidStateError extends CboxIdError {}\n\n/**\n * Login could not be completed: the provider returned an error, the callback was\n * missing a code, or a token / id_token failed verification.\n *\n * `error` carries the RFC 6749 §5.2 code the authorization server sent, when it sent one.\n * It used to be discarded at every back-channel boundary, leaving a single message string\n * for outcomes that need opposite responses: `invalid_grant` on a refresh means the\n * session is over and the person has to sign in again, while `temporarily_unavailable`\n * means try the same token in a moment. A caller reduced to matching on prose either\n * retries what can never succeed, or signs out somebody who did not need to be.\n */\nexport class AuthenticationError extends CboxIdError {\n constructor(\n message: string,\n /** RFC 6749 §5.2 error code, when the server sent a parseable one. */\n readonly error?: string,\n /** The server's `error_description`, verbatim. Not end-user copy. */\n readonly errorDescription?: string,\n /** HTTP status, for the cases where the body says nothing useful. */\n readonly status?: number,\n /**\n * Seconds to wait, off the `Retry-After` header — set only on a 429.\n *\n * The distinction it carries is the one a caller most needs and could least infer:\n * a 429 is the ONLY back-channel failure where the same request will succeed\n * unchanged if you simply wait. Every other one needs a different request, or a new\n * sign-in. Without this the SDK reported \"token refresh failed\" and a caller with a\n * retry loop hammered a limiter that was already telling it exactly how long to stop.\n */\n readonly retryAfter?: number,\n ) {\n super(message);\n }\n\n /** Whether waiting `retryAfter` seconds and repeating the same request is worth it. */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\n/**\n * Read an OAuth error out of a failed token-endpoint response.\n *\n * Best-effort by design: a 502 from a proxy is HTML, a captive portal is worse, and the\n * caller still needs an error rather than a parse exception. What it must never do is\n * invent a code — an absent or unparseable `error` stays undefined, so\n * `e.error === 'invalid_grant'` is true only because the server said so.\n */\nexport async function oauthError(response: Response, fallback: string): Promise<AuthenticationError> {\n const body = await response.text().catch(() => '');\n\n let code: string | undefined;\n let description: string | undefined;\n\n try {\n const parsed: unknown = JSON.parse(body);\n\n if (typeof parsed === 'object' && parsed !== null) {\n const { error, error_description: errorDescription } = parsed as Record<string, unknown>;\n code = typeof error === 'string' ? error : undefined;\n description = typeof errorDescription === 'string' ? errorDescription : undefined;\n }\n } catch {\n // Not JSON. The status and the truncated body below are all there is to report.\n }\n\n // THE BODY IS NEVER ECHOED. These calls carry `client_secret`, `code_verifier` and\n // refresh tokens in their REQUEST, and a debug proxy, a captive portal or an upstream\n // error page that reflects what it received puts those straight into a thrown message\n // — which production apps log. Only the server's own OAuth error code travels, and\n // failing that, the status alone.\n const detail = code ?? `HTTP ${response.status}`;\n\n // `Retry-After` is seconds here — Laravel's throttler writes the integer form. The\n // HTTP-date form is legal too and is deliberately NOT parsed: guessing at a clock\n // skew is worse than saying nothing, and `status === 429` still tells the caller to\n // back off.\n const retryAfterHeader = response.headers.get('retry-after');\n const retryAfter = retryAfterHeader !== null && /^\\d+$/.test(retryAfterHeader.trim())\n ? Number(retryAfterHeader.trim())\n : undefined;\n\n return new AuthenticationError(`${fallback}: ${detail}`, code, description, response.status, retryAfter);\n}\n\n/**\n * The Frontend API refused, or could not be reached.\n *\n * Carries a `code` because the four ways this goes wrong need four different responses\n * from the caller, and telling them apart from a message string is the kind of thing\n * that works until somebody rewords the message:\n *\n * - `origin_not_allowed` — the overwhelmingly likely cause of a refusal, and a\n * configuration problem the developer fixes once in the console.\n * - `rate_limited` — back off; `retryAfter` says for how long, when the server said.\n * - `unavailable` — the network, or a 5xx. Transient by assumption; already retried.\n * - `malformed` — a 200 whose body is not the document we expect, which means something\n * between the page and us is rewriting responses (a proxy, an extension, a captive\n * portal). Worth distinguishing, because retrying it never helps.\n */\nexport class FrontendApiError extends CboxIdError {\n constructor(\n message: string,\n readonly code: 'origin_not_allowed' | 'rate_limited' | 'unavailable' | 'malformed',\n readonly status?: number,\n readonly retryAfter?: number,\n ) {\n super(message);\n }\n}\n","import { ConfigurationError } from './errors.js';\n\n/**\n * An issuer must be HTTPS.\n *\n * Everything this SDK does with it carries a credential: the authorization code, the PKCE\n * verifier, the client secret, the refresh token. Over `http://` a network attacker reads\n * all of them — and, worse, replaces the discovery document and JWKS, at which point a\n * forged id_token verifies cleanly and the whole verification chain proves nothing.\n *\n * Loopback is allowed because a native app's own callback listener is loopback by\n * definition (RFC 8252) and a dev instance runs there.\n */\nexport function assertSecureIssuer(issuer: string): void {\n let url: URL;\n\n try {\n url = new URL(issuer);\n } catch {\n throw new ConfigurationError('Cbox ID config `issuer` is not a valid URL.');\n }\n\n if (url.protocol === 'https:') {\n return;\n }\n\n const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]' || url.hostname === '::1';\n\n if (url.protocol === 'http:' && loopback) {\n return;\n }\n\n throw new ConfigurationError(\n `Cbox ID config \\`issuer\\` must be https (got ${url.protocol}//${url.hostname}).`,\n );\n}\n","import type { OrganizationRole } from './claims.js';\nimport { AuthenticationError, ConfigurationError, oauthError } from './errors.js';\nimport { assertSecureIssuer } from './issuer.js';\n\n/**\n * A customer API key Cbox ID vouches for: live, bound to YOUR app, and held by an active\n * member of `org`.\n *\n * The field names are the endpoint's own, so the claim helpers read it like a token —\n * `hasPermission(answer, 'invoices:create')`, `organization(answer)?.role`. (A type\n * alias rather than an interface for that reason: only an alias is assignable to the\n * helpers' record type.)\n */\nexport type ActiveApiKey = {\n active: true;\n /** The key's id — log this, never the key. */\n key_id: string;\n /** The person who holds the key (their subject id). */\n sub: string;\n /** The organization the key acts in. */\n org: string;\n /** The holder's membership tier in `org`; null for a tier this SDK does not know. */\n org_role: OrganizationRole | null;\n /**\n * What the key may do, already re-capped by Cbox ID: the key's own list intersected\n * with what the holder holds for your app right now. A demoted holder's key loses the\n * permission on the next verification, not at the next reissue.\n */\n permissions: string[];\n /** Your app's client id — always, or the answer is refused. */\n client_id: string;\n /** ISO 8601 UTC expiry, or null for a key that does not expire. */\n expires_at: string | null;\n};\n\n/**\n * Every refusal: unknown, malformed, revoked, expired, another app's key, a holder who\n * left. Cbox ID never says which, so the endpoint cannot be used to probe keys — and\n * neither does this.\n */\nexport interface InactiveApiKey {\n active: false;\n}\n\n/** What {@link ApiKeyVerifier.verifyApiKey} returns. Narrow on `active`. */\nexport type ApiKeyVerification = ActiveApiKey | InactiveApiKey;\n\n/** Configuration for an {@link ApiKeyVerifier}. */\nexport interface ApiKeyVerifierConfig {\n /** Base URL (issuer) of the Cbox ID instance. */\n issuer: string;\n /** Your app's OAuth client id — the app the keys were issued for. */\n clientId: string;\n /** Your app's client secret. Verification is a confidential-client call. */\n clientSecret: string;\n /** Timeout (ms) for the verification request. Defaults to `10000`. */\n timeoutMs?: number;\n /**\n * Cache an ACTIVE answer for this long (ms), so a burst of requests with one key costs\n * one round-trip. Off (`0`) by default and at most {@link MAX_API_KEY_CACHE_TTL_MS}:\n * while an answer is cached, a revoked key keeps working, and a demoted holder keeps\n * the permissions they lost. Never cached past the key's `expires_at`. Refusals are\n * never cached, so a key issued a moment ago works on its first request.\n */\n cacheTtlMs?: number;\n}\n\n/** The longest {@link ApiKeyVerifierConfig.cacheTtlMs} allowed: one minute. */\nexport const MAX_API_KEY_CACHE_TTL_MS = 60_000;\n\n/** Enough for a busy API's working set; oldest entries go first beyond it. */\nconst MAX_CACHE_ENTRIES = 1_000;\n\nconst ORGANIZATION_ROLES: ReadonlySet<string> = new Set<OrganizationRole>([\n 'owner',\n 'admin',\n 'developer',\n 'member',\n 'viewer',\n]);\n\n/**\n * Verifies customer API keys presented to your API: `POST {issuer}/oauth/api-keys/verify`,\n * authenticated with your app's own client credentials.\n *\n * SERVER-SIDE ONLY. It holds your client secret, so it lives in the\n * `@cboxdk/id-js/server` entry and the Next.js adapter, never in the main entry that a\n * browser bundle pulls in — and it refuses to be constructed in a browser at all.\n *\n * ```ts\n * import { ApiKeyVerifier } from '@cboxdk/id-js/server';\n * import { hasPermission } from '@cboxdk/id-js';\n *\n * const keys = new ApiKeyVerifier({ issuer, clientId, clientSecret, cacheTtlMs: 10_000 });\n *\n * const answer = await keys.verifyApiKey(request.headers.get('x-api-key') ?? '');\n * if (!answer.active) return unauthorized();\n * if (!hasPermission(answer, 'invoices:create')) return forbidden();\n * ```\n */\nexport class ApiKeyVerifier {\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly cacheTtlMs: number;\n private readonly cache = new Map<string, { answer: ActiveApiKey; until: number }>();\n\n constructor(private readonly config: ApiKeyVerifierConfig) {\n // A heuristic, and enough of one: a page has a `document`, and no server runtime\n // this SDK supports (Node, Deno, Bun, edge workers) defines one.\n if (typeof (globalThis as { document?: unknown }).document !== 'undefined') {\n throw new ConfigurationError(\n 'API key verification uses your client secret and must run on your server, never in a browser.',\n );\n }\n if (!config.issuer || !config.clientId || !config.clientSecret) {\n throw new ConfigurationError('Verifying API keys needs issuer, clientId and clientSecret.');\n }\n assertSecureIssuer(config.issuer);\n\n const cacheTtlMs = config.cacheTtlMs ?? 0;\n if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0 || cacheTtlMs > MAX_API_KEY_CACHE_TTL_MS) {\n throw new ConfigurationError(\n `cacheTtlMs must be between 0 and ${MAX_API_KEY_CACHE_TTL_MS}: a cached answer keeps a revoked key working for that long.`,\n );\n }\n\n this.endpoint = `${config.issuer.replace(/\\/$/, '')}/oauth/api-keys/verify`;\n this.timeoutMs = config.timeoutMs ?? 10_000;\n this.cacheTtlMs = cacheTtlMs;\n }\n\n /**\n * Ask Cbox ID whether `key` is good for this app, and what it may do.\n *\n * Resolves `{ active: false }` for every kind of bad key, without a request for an empty\n * one. Throws `AuthenticationError` when the call itself fails (wrong client\n * credentials, an unreachable instance) or when the answer cannot be trusted — one that\n * names another app's `client_id`, or does not have the promised shape. Both mean \"do\n * not let this request in\"; the difference is that a throw is something to look at.\n */\n async verifyApiKey(key: string): Promise<ApiKeyVerification> {\n if (typeof key !== 'string' || key.trim() === '') {\n return { active: false };\n }\n\n const cacheKey = this.cacheTtlMs > 0 ? await digest(key) : null;\n if (cacheKey !== null) {\n const hit = this.cache.get(cacheKey);\n if (hit && hit.until > Date.now()) {\n return hit.answer;\n }\n this.cache.delete(cacheKey);\n }\n\n const answer = this.parse(await this.request(key));\n\n if (cacheKey !== null && answer.active) {\n this.remember(cacheKey, answer);\n }\n\n return answer;\n }\n\n private async request(key: string): Promise<unknown> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await fetch(this.endpoint, {\n method: 'POST',\n headers: {\n authorization: `Basic ${btoa(`${this.config.clientId}:${this.config.clientSecret}`)}`,\n accept: 'application/json',\n 'content-type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ key }),\n signal: controller.signal,\n });\n } catch (error) {\n throw new AuthenticationError(`API key verification request failed: ${String(error)}`);\n } finally {\n clearTimeout(timer);\n }\n\n if (!response.ok) {\n throw await oauthError(response, 'API key verification failed');\n }\n\n return response.json().catch(() => null);\n }\n\n private parse(body: unknown): ApiKeyVerification {\n if (typeof body !== 'object' || body === null) {\n throw new AuthenticationError('API key verification returned a body that is not a JSON object.');\n }\n\n const record = body as Record<string, unknown>;\n\n // Only a literal `true` lets anybody in.\n if (record['active'] !== true) {\n return { active: false };\n }\n\n const keyId = record['key_id'];\n const sub = record['sub'];\n const org = record['org'];\n const clientId = record['client_id'];\n const expiresAt = record['expires_at'];\n const permissions = record['permissions'];\n\n if (\n !nonEmpty(keyId) ||\n !nonEmpty(sub) ||\n !nonEmpty(org) ||\n !nonEmpty(clientId) ||\n !Array.isArray(permissions) ||\n (expiresAt !== null && expiresAt !== undefined && typeof expiresAt !== 'string')\n ) {\n throw new AuthenticationError('API key verification returned an active answer without the promised fields.');\n }\n\n // THE BINDING, CHECKED AGAIN HERE. Cbox ID only ever finds a key bound to the calling\n // client, so this cannot fire against a correct instance — which is exactly when a\n // check that it holds is worth having: a proxy, a misrouted base URL, or a shared\n // secret between two apps would otherwise let one app's customers into another's API.\n if (clientId !== this.config.clientId) {\n throw new AuthenticationError(\n `API key verification answered for client ${clientId}, not this app (${this.config.clientId}); refusing it.`,\n );\n }\n\n // Past its expiry by our clock is expired, whatever the instance thought a moment ago.\n if (typeof expiresAt === 'string') {\n const expiry = Date.parse(expiresAt);\n if (Number.isNaN(expiry) || expiry <= Date.now()) {\n return { active: false };\n }\n }\n\n const role = record['org_role'];\n\n return {\n active: true,\n key_id: keyId,\n sub,\n org,\n org_role: typeof role === 'string' && ORGANIZATION_ROLES.has(role) ? (role as OrganizationRole) : null,\n permissions: permissions.filter((value): value is string => nonEmpty(value)),\n client_id: clientId,\n expires_at: typeof expiresAt === 'string' ? expiresAt : null,\n };\n }\n\n private remember(cacheKey: string, answer: ActiveApiKey): void {\n const expiry = answer.expires_at === null ? Number.POSITIVE_INFINITY : Date.parse(answer.expires_at);\n const until = Math.min(Date.now() + this.cacheTtlMs, expiry);\n\n if (this.cache.size >= MAX_CACHE_ENTRIES) {\n const oldest = this.cache.keys().next();\n if (!oldest.done) {\n this.cache.delete(oldest.value);\n }\n }\n\n this.cache.set(cacheKey, { answer, until });\n }\n}\n\nfunction nonEmpty(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\n/** The cache is keyed by a hash, so live keys are not sitting in memory as plaintext. */\nasync function digest(key: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/issuer.ts","../src/api-keys.ts","../src/decisions.ts"],"names":["record"],"mappings":";;;AAIO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAAA,EACzB;AACF,CAAA;AAGO,IAAM,kBAAA,GAAN,cAAiC,WAAA,CAAY;AAAC,CAAA;AAmB9C,IAAM,mBAAA,GAAN,cAAkC,WAAA,CAAY;AAAA,EACnD,WAAA,CACE,OAAA,EAES,KAAA,EAEA,gBAAA,EAEA,QAUA,UAAA,EACT;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAhBJ,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AAEA,IAAA,IAAA,CAAA,gBAAA,GAAA,gBAAA;AAEA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAUA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAGX;AAAA,EAjBW,KAAA;AAAA,EAEA,gBAAA;AAAA,EAEA,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e\n * instanceof CboxIdError) ... }` in one branch.\n */\nexport class CboxIdError extends Error {\n constructor(message: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\n/** The client is misconfigured (a required option is missing or empty). */\nexport class ConfigurationError extends CboxIdError {}\n\n/**\n * The login `state` did not match what was stored — the callback is forged or\n * stale. Treat as a fresh start, not an error to surface to the user.\n */\nexport class InvalidStateError extends CboxIdError {}\n\n/**\n * Login could not be completed: the provider returned an error, the callback was\n * missing a code, or a token / id_token failed verification.\n *\n * `error` carries the RFC 6749 §5.2 code the authorization server sent, when it sent one.\n * It used to be discarded at every back-channel boundary, leaving a single message string\n * for outcomes that need opposite responses: `invalid_grant` on a refresh means the\n * session is over and the person has to sign in again, while `temporarily_unavailable`\n * means try the same token in a moment. A caller reduced to matching on prose either\n * retries what can never succeed, or signs out somebody who did not need to be.\n */\nexport class AuthenticationError extends CboxIdError {\n constructor(\n message: string,\n /** RFC 6749 §5.2 error code, when the server sent a parseable one. */\n readonly error?: string,\n /** The server's `error_description`, verbatim. Not end-user copy. */\n readonly errorDescription?: string,\n /** HTTP status, for the cases where the body says nothing useful. */\n readonly status?: number,\n /**\n * Seconds to wait, off the `Retry-After` header — set only on a 429.\n *\n * The distinction it carries is the one a caller most needs and could least infer:\n * a 429 is the ONLY back-channel failure where the same request will succeed\n * unchanged if you simply wait. Every other one needs a different request, or a new\n * sign-in. Without this the SDK reported \"token refresh failed\" and a caller with a\n * retry loop hammered a limiter that was already telling it exactly how long to stop.\n */\n readonly retryAfter?: number,\n ) {\n super(message);\n }\n\n /** Whether waiting `retryAfter` seconds and repeating the same request is worth it. */\n get isRateLimited(): boolean {\n return this.status === 429;\n }\n}\n\n/**\n * Read an OAuth error out of a failed token-endpoint response.\n *\n * Best-effort by design: a 502 from a proxy is HTML, a captive portal is worse, and the\n * caller still needs an error rather than a parse exception. What it must never do is\n * invent a code — an absent or unparseable `error` stays undefined, so\n * `e.error === 'invalid_grant'` is true only because the server said so.\n */\nexport async function oauthError(response: Response, fallback: string): Promise<AuthenticationError> {\n const body = await response.text().catch(() => '');\n\n let code: string | undefined;\n let description: string | undefined;\n\n try {\n const parsed: unknown = JSON.parse(body);\n\n if (typeof parsed === 'object' && parsed !== null) {\n const { error, error_description: errorDescription } = parsed as Record<string, unknown>;\n code = typeof error === 'string' ? error : undefined;\n description = typeof errorDescription === 'string' ? errorDescription : undefined;\n }\n } catch {\n // Not JSON. The status and the truncated body below are all there is to report.\n }\n\n // THE BODY IS NEVER ECHOED. These calls carry `client_secret`, `code_verifier` and\n // refresh tokens in their REQUEST, and a debug proxy, a captive portal or an upstream\n // error page that reflects what it received puts those straight into a thrown message\n // — which production apps log. Only the server's own OAuth error code travels, and\n // failing that, the status alone.\n const detail = code ?? `HTTP ${response.status}`;\n\n // `Retry-After` is seconds here — Laravel's throttler writes the integer form. The\n // HTTP-date form is legal too and is deliberately NOT parsed: guessing at a clock\n // skew is worse than saying nothing, and `status === 429` still tells the caller to\n // back off.\n const retryAfterHeader = response.headers.get('retry-after');\n const retryAfter = retryAfterHeader !== null && /^\\d+$/.test(retryAfterHeader.trim())\n ? Number(retryAfterHeader.trim())\n : undefined;\n\n return new AuthenticationError(`${fallback}: ${detail}`, code, description, response.status, retryAfter);\n}\n\n/**\n * The Frontend API refused, or could not be reached.\n *\n * Carries a `code` because the four ways this goes wrong need four different responses\n * from the caller, and telling them apart from a message string is the kind of thing\n * that works until somebody rewords the message:\n *\n * - `origin_not_allowed` — the overwhelmingly likely cause of a refusal, and a\n * configuration problem the developer fixes once in the console.\n * - `rate_limited` — back off; `retryAfter` says for how long, when the server said.\n * - `unavailable` — the network, or a 5xx. Transient by assumption; already retried.\n * - `malformed` — a 200 whose body is not the document we expect, which means something\n * between the page and us is rewriting responses (a proxy, an extension, a captive\n * portal). Worth distinguishing, because retrying it never helps.\n */\nexport class FrontendApiError extends CboxIdError {\n constructor(\n message: string,\n readonly code: 'origin_not_allowed' | 'rate_limited' | 'unavailable' | 'malformed',\n readonly status?: number,\n readonly retryAfter?: number,\n ) {\n super(message);\n }\n}\n","import { ConfigurationError } from './errors.js';\n\n/**\n * An issuer must be HTTPS.\n *\n * Everything this SDK does with it carries a credential: the authorization code, the PKCE\n * verifier, the client secret, the refresh token. Over `http://` a network attacker reads\n * all of them — and, worse, replaces the discovery document and JWKS, at which point a\n * forged id_token verifies cleanly and the whole verification chain proves nothing.\n *\n * Loopback is allowed because a native app's own callback listener is loopback by\n * definition (RFC 8252) and a dev instance runs there.\n */\nexport function assertSecureIssuer(issuer: string): void {\n let url: URL;\n\n try {\n url = new URL(issuer);\n } catch {\n throw new ConfigurationError('Cbox ID config `issuer` is not a valid URL.');\n }\n\n if (url.protocol === 'https:') {\n return;\n }\n\n const loopback = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]' || url.hostname === '::1';\n\n if (url.protocol === 'http:' && loopback) {\n return;\n }\n\n throw new ConfigurationError(\n `Cbox ID config \\`issuer\\` must be https (got ${url.protocol}//${url.hostname}).`,\n );\n}\n","import type { OrganizationRole } from './claims.js';\nimport { AuthenticationError, ConfigurationError, oauthError } from './errors.js';\nimport { assertSecureIssuer } from './issuer.js';\n\n/**\n * A customer API key Cbox ID vouches for: live, bound to YOUR app, and held by an active\n * member of `org`.\n *\n * The field names are the endpoint's own, so the claim helpers read it like a token —\n * `hasPermission(answer, 'invoices:create')`, `organization(answer)?.role`. (A type\n * alias rather than an interface for that reason: only an alias is assignable to the\n * helpers' record type.)\n */\nexport type ActiveApiKey = {\n active: true;\n /** The key's id — log this, never the key. */\n key_id: string;\n /** The person who holds the key (their subject id). */\n sub: string;\n /** The organization the key acts in. */\n org: string;\n /** The holder's membership tier in `org`; null for a tier this SDK does not know. */\n org_role: OrganizationRole | null;\n /**\n * What the key may do, already re-capped by Cbox ID: the key's own list intersected\n * with what the holder holds for your app right now. A demoted holder's key loses the\n * permission on the next verification, not at the next reissue.\n */\n permissions: string[];\n /** Your app's client id — always, or the answer is refused. */\n client_id: string;\n /** ISO 8601 UTC expiry, or null for a key that does not expire. */\n expires_at: string | null;\n};\n\n/**\n * Every refusal: unknown, malformed, revoked, expired, another app's key, a holder who\n * left. Cbox ID never says which, so the endpoint cannot be used to probe keys — and\n * neither does this.\n */\nexport interface InactiveApiKey {\n active: false;\n}\n\n/** What {@link ApiKeyVerifier.verifyApiKey} returns. Narrow on `active`. */\nexport type ApiKeyVerification = ActiveApiKey | InactiveApiKey;\n\n/** Configuration for an {@link ApiKeyVerifier}. */\nexport interface ApiKeyVerifierConfig {\n /** Base URL (issuer) of the Cbox ID instance. */\n issuer: string;\n /** Your app's OAuth client id — the app the keys were issued for. */\n clientId: string;\n /** Your app's client secret. Verification is a confidential-client call. */\n clientSecret: string;\n /** Timeout (ms) for the verification request. Defaults to `10000`. */\n timeoutMs?: number;\n /**\n * Cache an ACTIVE answer for this long (ms), so a burst of requests with one key costs\n * one round-trip. Off (`0`) by default and at most {@link MAX_API_KEY_CACHE_TTL_MS}:\n * while an answer is cached, a revoked key keeps working, and a demoted holder keeps\n * the permissions they lost. Never cached past the key's `expires_at`. Refusals are\n * never cached, so a key issued a moment ago works on its first request.\n */\n cacheTtlMs?: number;\n}\n\n/** The longest {@link ApiKeyVerifierConfig.cacheTtlMs} allowed: one minute. */\nexport const MAX_API_KEY_CACHE_TTL_MS = 60_000;\n\n/** Enough for a busy API's working set; oldest entries go first beyond it. */\nconst MAX_CACHE_ENTRIES = 1_000;\n\nconst ORGANIZATION_ROLES: ReadonlySet<string> = new Set<OrganizationRole>([\n 'owner',\n 'admin',\n 'developer',\n 'member',\n 'viewer',\n]);\n\n/**\n * Verifies customer API keys presented to your API: `POST {issuer}/oauth/api-keys/verify`,\n * authenticated with your app's own client credentials.\n *\n * SERVER-SIDE ONLY. It holds your client secret, so it lives in the\n * `@cboxdk/id-js/server` entry and the Next.js adapter, never in the main entry that a\n * browser bundle pulls in — and it refuses to be constructed in a browser at all.\n *\n * ```ts\n * import { ApiKeyVerifier } from '@cboxdk/id-js/server';\n * import { hasPermission } from '@cboxdk/id-js';\n *\n * const keys = new ApiKeyVerifier({ issuer, clientId, clientSecret, cacheTtlMs: 10_000 });\n *\n * const answer = await keys.verifyApiKey(request.headers.get('x-api-key') ?? '');\n * if (!answer.active) return unauthorized();\n * if (!hasPermission(answer, 'invoices:create')) return forbidden();\n * ```\n */\nexport class ApiKeyVerifier {\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly cacheTtlMs: number;\n private readonly cache = new Map<string, { answer: ActiveApiKey; until: number }>();\n\n constructor(private readonly config: ApiKeyVerifierConfig) {\n // A heuristic, and enough of one: a page has a `document`, and no server runtime\n // this SDK supports (Node, Deno, Bun, edge workers) defines one.\n if (typeof (globalThis as { document?: unknown }).document !== 'undefined') {\n throw new ConfigurationError(\n 'API key verification uses your client secret and must run on your server, never in a browser.',\n );\n }\n if (!config.issuer || !config.clientId || !config.clientSecret) {\n throw new ConfigurationError('Verifying API keys needs issuer, clientId and clientSecret.');\n }\n assertSecureIssuer(config.issuer);\n\n const cacheTtlMs = config.cacheTtlMs ?? 0;\n if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0 || cacheTtlMs > MAX_API_KEY_CACHE_TTL_MS) {\n throw new ConfigurationError(\n `cacheTtlMs must be between 0 and ${MAX_API_KEY_CACHE_TTL_MS}: a cached answer keeps a revoked key working for that long.`,\n );\n }\n\n this.endpoint = `${config.issuer.replace(/\\/$/, '')}/oauth/api-keys/verify`;\n this.timeoutMs = config.timeoutMs ?? 10_000;\n this.cacheTtlMs = cacheTtlMs;\n }\n\n /**\n * Ask Cbox ID whether `key` is good for this app, and what it may do.\n *\n * Resolves `{ active: false }` for every kind of bad key, without a request for an empty\n * one. Throws `AuthenticationError` when the call itself fails (wrong client\n * credentials, an unreachable instance) or when the answer cannot be trusted — one that\n * names another app's `client_id`, or does not have the promised shape. Both mean \"do\n * not let this request in\"; the difference is that a throw is something to look at.\n */\n async verifyApiKey(key: string): Promise<ApiKeyVerification> {\n if (typeof key !== 'string' || key.trim() === '') {\n return { active: false };\n }\n\n const cacheKey = this.cacheTtlMs > 0 ? await digest(key) : null;\n if (cacheKey !== null) {\n const hit = this.cache.get(cacheKey);\n if (hit && hit.until > Date.now()) {\n return hit.answer;\n }\n this.cache.delete(cacheKey);\n }\n\n const answer = this.parse(await this.request(key));\n\n if (cacheKey !== null && answer.active) {\n this.remember(cacheKey, answer);\n }\n\n return answer;\n }\n\n private async request(key: string): Promise<unknown> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let response: Response;\n try {\n response = await fetch(this.endpoint, {\n method: 'POST',\n headers: {\n authorization: `Basic ${btoa(`${this.config.clientId}:${this.config.clientSecret}`)}`,\n accept: 'application/json',\n 'content-type': 'application/x-www-form-urlencoded',\n },\n body: new URLSearchParams({ key }),\n signal: controller.signal,\n });\n } catch (error) {\n throw new AuthenticationError(`API key verification request failed: ${String(error)}`);\n } finally {\n clearTimeout(timer);\n }\n\n if (!response.ok) {\n throw await oauthError(response, 'API key verification failed');\n }\n\n return response.json().catch(() => null);\n }\n\n private parse(body: unknown): ApiKeyVerification {\n if (typeof body !== 'object' || body === null) {\n throw new AuthenticationError('API key verification returned a body that is not a JSON object.');\n }\n\n const record = body as Record<string, unknown>;\n\n // Only a literal `true` lets anybody in.\n if (record['active'] !== true) {\n return { active: false };\n }\n\n const keyId = record['key_id'];\n const sub = record['sub'];\n const org = record['org'];\n const clientId = record['client_id'];\n const expiresAt = record['expires_at'];\n const permissions = record['permissions'];\n\n if (\n !nonEmpty(keyId) ||\n !nonEmpty(sub) ||\n !nonEmpty(org) ||\n !nonEmpty(clientId) ||\n !Array.isArray(permissions) ||\n (expiresAt !== null && expiresAt !== undefined && typeof expiresAt !== 'string')\n ) {\n throw new AuthenticationError('API key verification returned an active answer without the promised fields.');\n }\n\n // THE BINDING, CHECKED AGAIN HERE. Cbox ID only ever finds a key bound to the calling\n // client, so this cannot fire against a correct instance — which is exactly when a\n // check that it holds is worth having: a proxy, a misrouted base URL, or a shared\n // secret between two apps would otherwise let one app's customers into another's API.\n if (clientId !== this.config.clientId) {\n throw new AuthenticationError(\n `API key verification answered for client ${clientId}, not this app (${this.config.clientId}); refusing it.`,\n );\n }\n\n // Past its expiry by our clock is expired, whatever the instance thought a moment ago.\n if (typeof expiresAt === 'string') {\n const expiry = Date.parse(expiresAt);\n if (Number.isNaN(expiry) || expiry <= Date.now()) {\n return { active: false };\n }\n }\n\n const role = record['org_role'];\n\n return {\n active: true,\n key_id: keyId,\n sub,\n org,\n org_role: typeof role === 'string' && ORGANIZATION_ROLES.has(role) ? (role as OrganizationRole) : null,\n permissions: permissions.filter((value): value is string => nonEmpty(value)),\n client_id: clientId,\n expires_at: typeof expiresAt === 'string' ? expiresAt : null,\n };\n }\n\n private remember(cacheKey: string, answer: ActiveApiKey): void {\n const expiry = answer.expires_at === null ? Number.POSITIVE_INFINITY : Date.parse(answer.expires_at);\n const until = Math.min(Date.now() + this.cacheTtlMs, expiry);\n\n if (this.cache.size >= MAX_CACHE_ENTRIES) {\n const oldest = this.cache.keys().next();\n if (!oldest.done) {\n this.cache.delete(oldest.value);\n }\n }\n\n this.cache.set(cacheKey, { answer, until });\n }\n}\n\nfunction nonEmpty(value: unknown): value is string {\n return typeof value === 'string' && value !== '';\n}\n\n/** The cache is keyed by a hash, so live keys are not sitting in memory as plaintext. */\nasync function digest(key: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(key));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n","import { AuthenticationError, ConfigurationError } from './errors.js';\nimport { assertSecureIssuer } from './issuer.js';\nimport type { OrganizationRole } from './claims.js';\n\nexport interface PermissionDecisionConfig {\n issuer: string;\n clientId: string;\n timeoutMs?: number;\n}\n\n/** A current server decision; shared membership tiers are not app grants. */\nexport class PermissionDecision {\n constructor(\n readonly subject: string,\n readonly organization: string | null,\n readonly clientId: string,\n readonly organizationRole: OrganizationRole | null,\n readonly organizationActive: boolean,\n readonly permissions: Readonly<Record<string, boolean>>,\n ) {}\n\n allows(permission: string): boolean {\n return this.organizationActive && this.permissions[permission] === true;\n }\n\n allowed(): boolean {\n const values = Object.values(this.permissions);\n return this.organizationActive && values.length > 0 && values.every(value => value === true);\n }\n}\n\n/** No positive cache: check each request and again when queued work starts. */\nexport async function checkPermissions(\n config: PermissionDecisionConfig,\n accessToken: string,\n subject: string,\n organization: string | null,\n permissions: readonly string[],\n): Promise<PermissionDecision> {\n assertSecureIssuer(config.issuer);\n const issuer = new URL(config.issuer);\n if (issuer.username || issuer.password || issuer.search || issuer.hash || !config.clientId\n || !subject || organization === '' || !accessToken || accessToken.length > 32768\n || /[\\x00-\\x20\\x7f]/.test(accessToken) || !permissions.length || permissions.length > 50\n || permissions.some(permission => !permission.trim() || new TextEncoder().encode(permission).length > 255)) {\n throw new ConfigurationError('Permission decision request is not configured or valid.');\n }\n const requested = [...new Set(permissions)];\n try {\n const response = await fetch(`${config.issuer.replace(/\\/$/, '')}/oauth/decisions`, {\n method: 'POST', redirect: 'error', cache: 'no-store',\n signal: AbortSignal.timeout(Math.max(1, config.timeoutMs ?? 10_000)),\n headers: { authorization: `Bearer ${accessToken}`, accept: 'application/json', 'content-type': 'application/json' },\n body: JSON.stringify({ subject, org: organization, permission: requested }),\n });\n if (response.status !== 200) {\n await response.body?.cancel();\n throw new AuthenticationError('Permission decision could not be verified.', undefined, undefined, response.status);\n }\n const reader = response.body?.getReader();\n if (!reader) throw new AuthenticationError('Permission decision response is invalid.');\n let size = 0;\n let raw = '';\n const decoder = new TextDecoder();\n try {\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > 65536) throw new AuthenticationError('Permission decision response exceeded its limit.');\n raw += decoder.decode(value, { stream: true });\n }\n raw += decoder.decode();\n } finally {\n await reader.cancel();\n reader.releaseLock();\n }\n const data: unknown = JSON.parse(raw);\n if (!record(data) || !record(data.subject) || data.mode !== 'rbac'\n || data.subject.type !== 'user' || data.subject.id !== subject\n || data.organization !== organization || data.client_id !== config.clientId\n || typeof data.organization_active !== 'boolean' || typeof data.allowed !== 'boolean'\n || !(data.org_role === null || (typeof data.org_role === 'string'\n && ['owner', 'admin', 'developer', 'member', 'viewer'].includes(data.org_role)))\n || !Array.isArray(data.results) || data.results.length !== requested.length) {\n throw new AuthenticationError('Permission decision response binding is invalid.');\n }\n const checks: Record<string, boolean> = Object.create(null) as Record<string, boolean>;\n for (const result of data.results as unknown[]) {\n if (!record(result) || typeof result.permission !== 'string' || typeof result.allowed !== 'boolean'\n || !requested.includes(result.permission) || Object.hasOwn(checks, result.permission)) {\n throw new AuthenticationError('Permission decision result is invalid.');\n }\n checks[result.permission] = result.allowed;\n }\n const decision = new PermissionDecision(subject, organization, config.clientId,\n data.org_role as OrganizationRole | null, data.organization_active, Object.freeze(checks));\n if (data.allowed !== decision.allowed()) throw new AuthenticationError('Permission decision result is inconsistent.');\n return decision;\n } catch (error) {\n if (error instanceof AuthenticationError) throw error;\n throw new AuthenticationError('Permission decision could not be verified.');\n }\n}\n\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n"]}
|
package/dist/server.d.cts
CHANGED
|
@@ -1,105 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* A customer API key Cbox ID vouches for: live, bound to YOUR app, and held by an active
|
|
5
|
-
* member of `org`.
|
|
6
|
-
*
|
|
7
|
-
* The field names are the endpoint's own, so the claim helpers read it like a token —
|
|
8
|
-
* `hasPermission(answer, 'invoices:create')`, `organization(answer)?.role`. (A type
|
|
9
|
-
* alias rather than an interface for that reason: only an alias is assignable to the
|
|
10
|
-
* helpers' record type.)
|
|
11
|
-
*/
|
|
12
|
-
type ActiveApiKey = {
|
|
13
|
-
active: true;
|
|
14
|
-
/** The key's id — log this, never the key. */
|
|
15
|
-
key_id: string;
|
|
16
|
-
/** The person who holds the key (their subject id). */
|
|
17
|
-
sub: string;
|
|
18
|
-
/** The organization the key acts in. */
|
|
19
|
-
org: string;
|
|
20
|
-
/** The holder's membership tier in `org`; null for a tier this SDK does not know. */
|
|
21
|
-
org_role: OrganizationRole | null;
|
|
22
|
-
/**
|
|
23
|
-
* What the key may do, already re-capped by Cbox ID: the key's own list intersected
|
|
24
|
-
* with what the holder holds for your app right now. A demoted holder's key loses the
|
|
25
|
-
* permission on the next verification, not at the next reissue.
|
|
26
|
-
*/
|
|
27
|
-
permissions: string[];
|
|
28
|
-
/** Your app's client id — always, or the answer is refused. */
|
|
29
|
-
client_id: string;
|
|
30
|
-
/** ISO 8601 UTC expiry, or null for a key that does not expire. */
|
|
31
|
-
expires_at: string | null;
|
|
32
|
-
};
|
|
33
|
-
/**
|
|
34
|
-
* Every refusal: unknown, malformed, revoked, expired, another app's key, a holder who
|
|
35
|
-
* left. Cbox ID never says which, so the endpoint cannot be used to probe keys — and
|
|
36
|
-
* neither does this.
|
|
37
|
-
*/
|
|
38
|
-
interface InactiveApiKey {
|
|
39
|
-
active: false;
|
|
40
|
-
}
|
|
41
|
-
/** What {@link ApiKeyVerifier.verifyApiKey} returns. Narrow on `active`. */
|
|
42
|
-
type ApiKeyVerification = ActiveApiKey | InactiveApiKey;
|
|
43
|
-
/** Configuration for an {@link ApiKeyVerifier}. */
|
|
44
|
-
interface ApiKeyVerifierConfig {
|
|
45
|
-
/** Base URL (issuer) of the Cbox ID instance. */
|
|
46
|
-
issuer: string;
|
|
47
|
-
/** Your app's OAuth client id — the app the keys were issued for. */
|
|
48
|
-
clientId: string;
|
|
49
|
-
/** Your app's client secret. Verification is a confidential-client call. */
|
|
50
|
-
clientSecret: string;
|
|
51
|
-
/** Timeout (ms) for the verification request. Defaults to `10000`. */
|
|
52
|
-
timeoutMs?: number;
|
|
53
|
-
/**
|
|
54
|
-
* Cache an ACTIVE answer for this long (ms), so a burst of requests with one key costs
|
|
55
|
-
* one round-trip. Off (`0`) by default and at most {@link MAX_API_KEY_CACHE_TTL_MS}:
|
|
56
|
-
* while an answer is cached, a revoked key keeps working, and a demoted holder keeps
|
|
57
|
-
* the permissions they lost. Never cached past the key's `expires_at`. Refusals are
|
|
58
|
-
* never cached, so a key issued a moment ago works on its first request.
|
|
59
|
-
*/
|
|
60
|
-
cacheTtlMs?: number;
|
|
61
|
-
}
|
|
62
|
-
/** The longest {@link ApiKeyVerifierConfig.cacheTtlMs} allowed: one minute. */
|
|
63
|
-
declare const MAX_API_KEY_CACHE_TTL_MS = 60000;
|
|
64
|
-
/**
|
|
65
|
-
* Verifies customer API keys presented to your API: `POST {issuer}/oauth/api-keys/verify`,
|
|
66
|
-
* authenticated with your app's own client credentials.
|
|
67
|
-
*
|
|
68
|
-
* SERVER-SIDE ONLY. It holds your client secret, so it lives in the
|
|
69
|
-
* `@cboxdk/id-js/server` entry and the Next.js adapter, never in the main entry that a
|
|
70
|
-
* browser bundle pulls in — and it refuses to be constructed in a browser at all.
|
|
71
|
-
*
|
|
72
|
-
* ```ts
|
|
73
|
-
* import { ApiKeyVerifier } from '@cboxdk/id-js/server';
|
|
74
|
-
* import { hasPermission } from '@cboxdk/id-js';
|
|
75
|
-
*
|
|
76
|
-
* const keys = new ApiKeyVerifier({ issuer, clientId, clientSecret, cacheTtlMs: 10_000 });
|
|
77
|
-
*
|
|
78
|
-
* const answer = await keys.verifyApiKey(request.headers.get('x-api-key') ?? '');
|
|
79
|
-
* if (!answer.active) return unauthorized();
|
|
80
|
-
* if (!hasPermission(answer, 'invoices:create')) return forbidden();
|
|
81
|
-
* ```
|
|
82
|
-
*/
|
|
83
|
-
declare class ApiKeyVerifier {
|
|
84
|
-
private readonly config;
|
|
85
|
-
private readonly endpoint;
|
|
86
|
-
private readonly timeoutMs;
|
|
87
|
-
private readonly cacheTtlMs;
|
|
88
|
-
private readonly cache;
|
|
89
|
-
constructor(config: ApiKeyVerifierConfig);
|
|
90
|
-
/**
|
|
91
|
-
* Ask Cbox ID whether `key` is good for this app, and what it may do.
|
|
92
|
-
*
|
|
93
|
-
* Resolves `{ active: false }` for every kind of bad key, without a request for an empty
|
|
94
|
-
* one. Throws `AuthenticationError` when the call itself fails (wrong client
|
|
95
|
-
* credentials, an unreachable instance) or when the answer cannot be trusted — one that
|
|
96
|
-
* names another app's `client_id`, or does not have the promised shape. Both mean "do
|
|
97
|
-
* not let this request in"; the difference is that a throw is something to look at.
|
|
98
|
-
*/
|
|
99
|
-
verifyApiKey(key: string): Promise<ApiKeyVerification>;
|
|
100
|
-
private request;
|
|
101
|
-
private parse;
|
|
102
|
-
private remember;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
export { type ActiveApiKey, type ApiKeyVerification, ApiKeyVerifier, type ApiKeyVerifierConfig, type InactiveApiKey, MAX_API_KEY_CACHE_TTL_MS };
|
|
1
|
+
export { A as ActiveApiKey, a as ApiKeyVerification, b as ApiKeyVerifier, c as ApiKeyVerifierConfig, I as InactiveApiKey, M as MAX_API_KEY_CACHE_TTL_MS } from './api-keys-C8-Q4eFA.cjs';
|
|
2
|
+
export { P as PermissionDecision, a as PermissionDecisionConfig, c as checkPermissions } from './decisions-DNd9UXwi.cjs';
|
|
3
|
+
import './types-CC1bz68x.cjs';
|
package/dist/server.d.ts
CHANGED
|
@@ -1,105 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
* A customer API key Cbox ID vouches for: live, bound to YOUR app, and held by an active
|
|
5
|
-
* member of `org`.
|
|
6
|
-
*
|
|
7
|
-
* The field names are the endpoint's own, so the claim helpers read it like a token —
|
|
8
|
-
* `hasPermission(answer, 'invoices:create')`, `organization(answer)?.role`. (A type
|
|
9
|
-
* alias rather than an interface for that reason: only an alias is assignable to the
|
|
10
|
-
* helpers' record type.)
|
|
11
|
-
*/
|
|
12
|
-
type ActiveApiKey = {
|
|
13
|
-
active: true;
|
|
14
|
-
/** The key's id — log this, never the key. */
|
|
15
|
-
key_id: string;
|
|
16
|
-
/** The person who holds the key (their subject id). */
|
|
17
|
-
sub: string;
|
|
18
|
-
/** The organization the key acts in. */
|
|
19
|
-
org: string;
|
|
20
|
-
/** The holder's membership tier in `org`; null for a tier this SDK does not know. */
|
|
21
|
-
org_role: OrganizationRole | null;
|
|
22
|
-
/**
|
|
23
|
-
* What the key may do, already re-capped by Cbox ID: the key's own list intersected
|
|
24
|
-
* with what the holder holds for your app right now. A demoted holder's key loses the
|
|
25
|
-
* permission on the next verification, not at the next reissue.
|
|
26
|
-
*/
|
|
27
|
-
permissions: string[];
|
|
28
|
-
/** Your app's client id — always, or the answer is refused. */
|
|
29
|
-
client_id: string;
|
|
30
|
-
/** ISO 8601 UTC expiry, or null for a key that does not expire. */
|
|
31
|
-
expires_at: string | null;
|
|
32
|
-
};
|
|
33
|
-
/**
|
|
34
|
-
* Every refusal: unknown, malformed, revoked, expired, another app's key, a holder who
|
|
35
|
-
* left. Cbox ID never says which, so the endpoint cannot be used to probe keys — and
|
|
36
|
-
* neither does this.
|
|
37
|
-
*/
|
|
38
|
-
interface InactiveApiKey {
|
|
39
|
-
active: false;
|
|
40
|
-
}
|
|
41
|
-
/** What {@link ApiKeyVerifier.verifyApiKey} returns. Narrow on `active`. */
|
|
42
|
-
type ApiKeyVerification = ActiveApiKey | InactiveApiKey;
|
|
43
|
-
/** Configuration for an {@link ApiKeyVerifier}. */
|
|
44
|
-
interface ApiKeyVerifierConfig {
|
|
45
|
-
/** Base URL (issuer) of the Cbox ID instance. */
|
|
46
|
-
issuer: string;
|
|
47
|
-
/** Your app's OAuth client id — the app the keys were issued for. */
|
|
48
|
-
clientId: string;
|
|
49
|
-
/** Your app's client secret. Verification is a confidential-client call. */
|
|
50
|
-
clientSecret: string;
|
|
51
|
-
/** Timeout (ms) for the verification request. Defaults to `10000`. */
|
|
52
|
-
timeoutMs?: number;
|
|
53
|
-
/**
|
|
54
|
-
* Cache an ACTIVE answer for this long (ms), so a burst of requests with one key costs
|
|
55
|
-
* one round-trip. Off (`0`) by default and at most {@link MAX_API_KEY_CACHE_TTL_MS}:
|
|
56
|
-
* while an answer is cached, a revoked key keeps working, and a demoted holder keeps
|
|
57
|
-
* the permissions they lost. Never cached past the key's `expires_at`. Refusals are
|
|
58
|
-
* never cached, so a key issued a moment ago works on its first request.
|
|
59
|
-
*/
|
|
60
|
-
cacheTtlMs?: number;
|
|
61
|
-
}
|
|
62
|
-
/** The longest {@link ApiKeyVerifierConfig.cacheTtlMs} allowed: one minute. */
|
|
63
|
-
declare const MAX_API_KEY_CACHE_TTL_MS = 60000;
|
|
64
|
-
/**
|
|
65
|
-
* Verifies customer API keys presented to your API: `POST {issuer}/oauth/api-keys/verify`,
|
|
66
|
-
* authenticated with your app's own client credentials.
|
|
67
|
-
*
|
|
68
|
-
* SERVER-SIDE ONLY. It holds your client secret, so it lives in the
|
|
69
|
-
* `@cboxdk/id-js/server` entry and the Next.js adapter, never in the main entry that a
|
|
70
|
-
* browser bundle pulls in — and it refuses to be constructed in a browser at all.
|
|
71
|
-
*
|
|
72
|
-
* ```ts
|
|
73
|
-
* import { ApiKeyVerifier } from '@cboxdk/id-js/server';
|
|
74
|
-
* import { hasPermission } from '@cboxdk/id-js';
|
|
75
|
-
*
|
|
76
|
-
* const keys = new ApiKeyVerifier({ issuer, clientId, clientSecret, cacheTtlMs: 10_000 });
|
|
77
|
-
*
|
|
78
|
-
* const answer = await keys.verifyApiKey(request.headers.get('x-api-key') ?? '');
|
|
79
|
-
* if (!answer.active) return unauthorized();
|
|
80
|
-
* if (!hasPermission(answer, 'invoices:create')) return forbidden();
|
|
81
|
-
* ```
|
|
82
|
-
*/
|
|
83
|
-
declare class ApiKeyVerifier {
|
|
84
|
-
private readonly config;
|
|
85
|
-
private readonly endpoint;
|
|
86
|
-
private readonly timeoutMs;
|
|
87
|
-
private readonly cacheTtlMs;
|
|
88
|
-
private readonly cache;
|
|
89
|
-
constructor(config: ApiKeyVerifierConfig);
|
|
90
|
-
/**
|
|
91
|
-
* Ask Cbox ID whether `key` is good for this app, and what it may do.
|
|
92
|
-
*
|
|
93
|
-
* Resolves `{ active: false }` for every kind of bad key, without a request for an empty
|
|
94
|
-
* one. Throws `AuthenticationError` when the call itself fails (wrong client
|
|
95
|
-
* credentials, an unreachable instance) or when the answer cannot be trusted — one that
|
|
96
|
-
* names another app's `client_id`, or does not have the promised shape. Both mean "do
|
|
97
|
-
* not let this request in"; the difference is that a throw is something to look at.
|
|
98
|
-
*/
|
|
99
|
-
verifyApiKey(key: string): Promise<ApiKeyVerification>;
|
|
100
|
-
private request;
|
|
101
|
-
private parse;
|
|
102
|
-
private remember;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
export { type ActiveApiKey, type ApiKeyVerification, ApiKeyVerifier, type ApiKeyVerifierConfig, type InactiveApiKey, MAX_API_KEY_CACHE_TTL_MS };
|
|
1
|
+
export { A as ActiveApiKey, a as ApiKeyVerification, b as ApiKeyVerifier, c as ApiKeyVerifierConfig, I as InactiveApiKey, M as MAX_API_KEY_CACHE_TTL_MS } from './api-keys-BE3R3q_A.js';
|
|
2
|
+
export { P as PermissionDecision, a as PermissionDecisionConfig, c as checkPermissions } from './decisions-C84Fzah4.js';
|
|
3
|
+
import './types-CC1bz68x.js';
|
package/dist/server.js
CHANGED
|
@@ -85,6 +85,29 @@ declare function hasRole(source: ClaimSource, role: string): boolean;
|
|
|
85
85
|
* issuing side ever mints one.
|
|
86
86
|
*/
|
|
87
87
|
declare function hasPermission(source: ClaimSource, permission: string): boolean;
|
|
88
|
+
/**
|
|
89
|
+
* The scope that puts the `feature_flags` claim on the ID token, the access token and
|
|
90
|
+
* UserInfo. Request it at sign-in (`scopes: ['openid', 'profile', FEATURE_FLAGS_SCOPE]`)
|
|
91
|
+
* and give the app the scope on its Scopes tab.
|
|
92
|
+
*/
|
|
93
|
+
declare const FEATURE_FLAGS_SCOPE = "feature_flags";
|
|
94
|
+
/**
|
|
95
|
+
* The keys of the feature flags that are on for this person, in the organization the
|
|
96
|
+
* session is bound to — the `feature_flags` claim, sorted as the server sent it.
|
|
97
|
+
*
|
|
98
|
+
* NULL IS NOT EMPTY. `null` means the claim is absent: the `feature_flags` scope was not
|
|
99
|
+
* requested, or the instance predates it. `[]` means it was asked and nothing is on. A
|
|
100
|
+
* token carries the flags as they were when it was issued; the next refresh, or UserInfo,
|
|
101
|
+
* picks up a change.
|
|
102
|
+
*/
|
|
103
|
+
declare function featureFlags(source: ClaimSource): string[] | null;
|
|
104
|
+
/**
|
|
105
|
+
* Whether the feature flag `key` is on for this session. Exact match on the key.
|
|
106
|
+
*
|
|
107
|
+
* False when the claim is absent — an app that forgot to request the scope sees every
|
|
108
|
+
* feature off, never every feature on. Use {@link featureFlags} to tell the two apart.
|
|
109
|
+
*/
|
|
110
|
+
declare function hasFeature(source: ClaimSource, key: string): boolean;
|
|
88
111
|
|
|
89
112
|
/** Configuration for a {@link CboxIdClient}. */
|
|
90
113
|
interface CboxIdConfig {
|
|
@@ -289,6 +312,12 @@ interface CboxUser {
|
|
|
289
312
|
roles: string[];
|
|
290
313
|
/** Permissions held in this session (`permissions` claim); empty when there are none. */
|
|
291
314
|
permissions: string[];
|
|
315
|
+
/**
|
|
316
|
+
* The keys of the feature flags on for this person in this organization (the
|
|
317
|
+
* `feature_flags` claim), or null when the claim is absent — the `feature_flags` scope
|
|
318
|
+
* was not requested. See `featureFlags()` / `hasFeature()`.
|
|
319
|
+
*/
|
|
320
|
+
featureFlags: string[] | null;
|
|
292
321
|
/**
|
|
293
322
|
* Set when this is a SUPPORT SESSION — a staff member acting as this person (the RFC
|
|
294
323
|
* 8693 `act` claim). Null for an ordinary sign-in. Show it: see `isSupportSession()`.
|
|
@@ -313,4 +342,4 @@ interface CboxUser {
|
|
|
313
342
|
expiresIn: number;
|
|
314
343
|
}
|
|
315
344
|
|
|
316
|
-
export { type AuthorizationRequestOptions as A, type CboxUser as C, type DeviceAuthorization as D, type OrganizationRole as O, type RefreshedTokens as R, type TokenTypeHint as T, type CboxIdConfig as a, type AuthorizationRequest as b, type AuthorizationPrompt as c, type CboxActiveOrganization as d, type CboxActor as e, type CboxOrganization as f, type ClaimSource as g, type DiscoveryDocument as h, type TokenResponse as i, actor as j,
|
|
345
|
+
export { type AuthorizationRequestOptions as A, type CboxUser as C, type DeviceAuthorization as D, FEATURE_FLAGS_SCOPE as F, type OrganizationRole as O, type RefreshedTokens as R, type TokenTypeHint as T, type CboxIdConfig as a, type AuthorizationRequest as b, type AuthorizationPrompt as c, type CboxActiveOrganization as d, type CboxActor as e, type CboxOrganization as f, type ClaimSource as g, type DiscoveryDocument as h, type TokenResponse as i, actor as j, featureFlags as k, hasFeature as l, hasPermission as m, hasRole as n, isSupportSession as o, organization as p, permissions as q, roles as r, sessionId as s };
|
|
@@ -85,6 +85,29 @@ declare function hasRole(source: ClaimSource, role: string): boolean;
|
|
|
85
85
|
* issuing side ever mints one.
|
|
86
86
|
*/
|
|
87
87
|
declare function hasPermission(source: ClaimSource, permission: string): boolean;
|
|
88
|
+
/**
|
|
89
|
+
* The scope that puts the `feature_flags` claim on the ID token, the access token and
|
|
90
|
+
* UserInfo. Request it at sign-in (`scopes: ['openid', 'profile', FEATURE_FLAGS_SCOPE]`)
|
|
91
|
+
* and give the app the scope on its Scopes tab.
|
|
92
|
+
*/
|
|
93
|
+
declare const FEATURE_FLAGS_SCOPE = "feature_flags";
|
|
94
|
+
/**
|
|
95
|
+
* The keys of the feature flags that are on for this person, in the organization the
|
|
96
|
+
* session is bound to — the `feature_flags` claim, sorted as the server sent it.
|
|
97
|
+
*
|
|
98
|
+
* NULL IS NOT EMPTY. `null` means the claim is absent: the `feature_flags` scope was not
|
|
99
|
+
* requested, or the instance predates it. `[]` means it was asked and nothing is on. A
|
|
100
|
+
* token carries the flags as they were when it was issued; the next refresh, or UserInfo,
|
|
101
|
+
* picks up a change.
|
|
102
|
+
*/
|
|
103
|
+
declare function featureFlags(source: ClaimSource): string[] | null;
|
|
104
|
+
/**
|
|
105
|
+
* Whether the feature flag `key` is on for this session. Exact match on the key.
|
|
106
|
+
*
|
|
107
|
+
* False when the claim is absent — an app that forgot to request the scope sees every
|
|
108
|
+
* feature off, never every feature on. Use {@link featureFlags} to tell the two apart.
|
|
109
|
+
*/
|
|
110
|
+
declare function hasFeature(source: ClaimSource, key: string): boolean;
|
|
88
111
|
|
|
89
112
|
/** Configuration for a {@link CboxIdClient}. */
|
|
90
113
|
interface CboxIdConfig {
|
|
@@ -289,6 +312,12 @@ interface CboxUser {
|
|
|
289
312
|
roles: string[];
|
|
290
313
|
/** Permissions held in this session (`permissions` claim); empty when there are none. */
|
|
291
314
|
permissions: string[];
|
|
315
|
+
/**
|
|
316
|
+
* The keys of the feature flags on for this person in this organization (the
|
|
317
|
+
* `feature_flags` claim), or null when the claim is absent — the `feature_flags` scope
|
|
318
|
+
* was not requested. See `featureFlags()` / `hasFeature()`.
|
|
319
|
+
*/
|
|
320
|
+
featureFlags: string[] | null;
|
|
292
321
|
/**
|
|
293
322
|
* Set when this is a SUPPORT SESSION — a staff member acting as this person (the RFC
|
|
294
323
|
* 8693 `act` claim). Null for an ordinary sign-in. Show it: see `isSupportSession()`.
|
|
@@ -313,4 +342,4 @@ interface CboxUser {
|
|
|
313
342
|
expiresIn: number;
|
|
314
343
|
}
|
|
315
344
|
|
|
316
|
-
export { type AuthorizationRequestOptions as A, type CboxUser as C, type DeviceAuthorization as D, type OrganizationRole as O, type RefreshedTokens as R, type TokenTypeHint as T, type CboxIdConfig as a, type AuthorizationRequest as b, type AuthorizationPrompt as c, type CboxActiveOrganization as d, type CboxActor as e, type CboxOrganization as f, type ClaimSource as g, type DiscoveryDocument as h, type TokenResponse as i, actor as j,
|
|
345
|
+
export { type AuthorizationRequestOptions as A, type CboxUser as C, type DeviceAuthorization as D, FEATURE_FLAGS_SCOPE as F, type OrganizationRole as O, type RefreshedTokens as R, type TokenTypeHint as T, type CboxIdConfig as a, type AuthorizationRequest as b, type AuthorizationPrompt as c, type CboxActiveOrganization as d, type CboxActor as e, type CboxOrganization as f, type ClaimSource as g, type DiscoveryDocument as h, type TokenResponse as i, actor as j, featureFlags as k, hasFeature as l, hasPermission as m, hasRole as n, isSupportSession as o, organization as p, permissions as q, roles as r, sessionId as s };
|