@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/README.md
CHANGED
|
@@ -90,6 +90,62 @@ const user = await client.authenticate({
|
|
|
90
90
|
});
|
|
91
91
|
```
|
|
92
92
|
|
|
93
|
+
## In the browser (publishable keys)
|
|
94
|
+
|
|
95
|
+
Everything above needs a server: it holds your client secret. A **publishable key** is the
|
|
96
|
+
opposite — it is public on purpose, it ships in your bundle, and it lets a page read its
|
|
97
|
+
own sign-in configuration without routing that through your backend.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { CboxIdFrontend } from '@cboxdk/id-js'
|
|
101
|
+
|
|
102
|
+
const frontend = new CboxIdFrontend({
|
|
103
|
+
issuer: 'https://id.acme.com',
|
|
104
|
+
publishableKey: 'pk_live_…', // safe in your bundle
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
const config = await frontend.config()
|
|
108
|
+
// → endpoints, social buttons, and the customer's theme
|
|
109
|
+
|
|
110
|
+
const { user } = await frontend.session(accessToken)
|
|
111
|
+
// → { id, email, name } or null
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
**What makes a public key safe:** every key carries an allow-list of origins, and a request
|
|
115
|
+
from anywhere else is refused. A key that leaks still only works from the sites you
|
|
116
|
+
registered — the same shape as a Stripe publishable key plus registered domains. Add your
|
|
117
|
+
origins when you create the key in the console; exact matches only, so `https://acme.com`
|
|
118
|
+
does not cover `https://www.acme.com`.
|
|
119
|
+
|
|
120
|
+
`config()` is fetched once per instance and shared between however many components ask for
|
|
121
|
+
it at the same time. `session()` returns `{ user: null }` rather than throwing when nobody
|
|
122
|
+
is signed in — signed-out is a state, not an error, and a user button renders on pages
|
|
123
|
+
nobody has signed in on.
|
|
124
|
+
|
|
125
|
+
The publishable key grants nothing on its own: the access token is the entire authority for
|
|
126
|
+
`session()`. Pasting a client secret here throws immediately rather than failing later as an
|
|
127
|
+
opaque 401.
|
|
128
|
+
|
|
129
|
+
Failures are typed, because the four ways this goes wrong need four different responses and
|
|
130
|
+
telling them apart from a message string breaks the moment somebody rewords it:
|
|
131
|
+
|
|
132
|
+
```ts
|
|
133
|
+
import { FrontendApiError } from '@cboxdk/id-js'
|
|
134
|
+
|
|
135
|
+
try {
|
|
136
|
+
await frontend.config()
|
|
137
|
+
} catch (e) {
|
|
138
|
+
if (e instanceof FrontendApiError) {
|
|
139
|
+
e.code // 'origin_not_allowed' | 'rate_limited' | 'unavailable' | 'malformed'
|
|
140
|
+
e.retryAfter // seconds, when the server said
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Transient failures are retried twice by default (`retries`). A refusal is not — it is a
|
|
146
|
+
configuration problem, and retrying it only delays you finding out. A rate limit is
|
|
147
|
+
surfaced rather than hammered.
|
|
148
|
+
|
|
93
149
|
## Back-channel calls
|
|
94
150
|
|
|
95
151
|
```ts
|
|
@@ -104,6 +160,59 @@ everywhere" needs. `machineToken`, `introspect` and `revoke` authenticate as the
|
|
|
104
160
|
client, so they require a `clientSecret`; `userinfo` authenticates with the user's
|
|
105
161
|
own access token and does not.
|
|
106
162
|
|
|
163
|
+
## Migrating off an old login
|
|
164
|
+
|
|
165
|
+
Bulk-importing users with their existing hashes is the first answer, and the better one.
|
|
166
|
+
When you cannot export those hashes, Cbox ID can ask your old system instead — and import
|
|
167
|
+
each person at the moment they sign in.
|
|
168
|
+
|
|
169
|
+
Declare where it lives, alongside your roles:
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
export default defineAuthz({
|
|
173
|
+
roles: [...],
|
|
174
|
+
legacyLogin: {
|
|
175
|
+
url: 'https://acme.com/api/cbox-legacy',
|
|
176
|
+
secret: process.env.CBOX_LEGACY_SECRET!, // 32+ chars
|
|
177
|
+
},
|
|
178
|
+
})
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
It rides the manifest because it is the same kind of fact as a role — something your app
|
|
182
|
+
knows about itself, deployed with the code. **It does not take effect on its own:** unlike
|
|
183
|
+
a role, this names a URL that every unknown email and the password typed with it will be
|
|
184
|
+
offered to, so an operator approves it once in the console. Changing the URL later drops
|
|
185
|
+
that approval, deliberately.
|
|
186
|
+
|
|
187
|
+
Then write the handler — one function, no signature code:
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
// app/api/cbox-legacy/route.ts
|
|
191
|
+
import { createLegacyVerifier } from '@cboxdk/id-js'
|
|
192
|
+
|
|
193
|
+
export const POST = createLegacyVerifier({
|
|
194
|
+
secret: process.env.CBOX_LEGACY_SECRET!,
|
|
195
|
+
async verify(email, password) {
|
|
196
|
+
const row = await db.users.findByEmail(email)
|
|
197
|
+
if (!row || !(await argon2.verify(row.password, password))) return null
|
|
198
|
+
|
|
199
|
+
return { email: row.email, name: row.name, emailVerified: !!row.confirmedAt }
|
|
200
|
+
},
|
|
201
|
+
})
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
The factory owns the HMAC check, the freshness window, the constant-time compare and the
|
|
205
|
+
response shape — the parts that are easy to get subtly wrong. You own the one function
|
|
206
|
+
that knows your database.
|
|
207
|
+
|
|
208
|
+
Return `null` for "wrong password". **Throwing is different:** it means your store could
|
|
209
|
+
not decide, and is answered with a 503 so Cbox ID refuses the sign-in rather than reading
|
|
210
|
+
an outage as a bad password. Returning `passwordHash` lets the person keep their password
|
|
211
|
+
verbatim; omit it and Cbox ID hashes the one they just proved they know.
|
|
212
|
+
|
|
213
|
+
It returns a `Request → Response` handler, so it drops into Next.js route handlers, Remix,
|
|
214
|
+
Hono, Bun and Deno unchanged.
|
|
215
|
+
|
|
107
216
|
## Verify webhooks
|
|
108
217
|
|
|
109
218
|
```ts
|
|
@@ -13,6 +13,17 @@ var InvalidStateError = class extends CboxIdError {
|
|
|
13
13
|
};
|
|
14
14
|
var AuthenticationError = class extends CboxIdError {
|
|
15
15
|
};
|
|
16
|
+
var FrontendApiError = class extends CboxIdError {
|
|
17
|
+
constructor(message, code, status, retryAfter) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.retryAfter = retryAfter;
|
|
22
|
+
}
|
|
23
|
+
code;
|
|
24
|
+
status;
|
|
25
|
+
retryAfter;
|
|
26
|
+
};
|
|
16
27
|
|
|
17
28
|
// src/pkce.ts
|
|
18
29
|
function base64url(bytes) {
|
|
@@ -560,7 +571,7 @@ var CboxIdClient = class {
|
|
|
560
571
|
}
|
|
561
572
|
accountPath() {
|
|
562
573
|
const path = this.config.accountPath;
|
|
563
|
-
return path && path !== "" ? `/${path.replace(/^\//, "")}` : "/
|
|
574
|
+
return path && path !== "" ? `/${path.replace(/^\//, "")}` : "/account";
|
|
564
575
|
}
|
|
565
576
|
requireSecret() {
|
|
566
577
|
if (!this.config.clientSecret) {
|
|
@@ -614,6 +625,6 @@ function parseOrganizations(claim) {
|
|
|
614
625
|
return orgs;
|
|
615
626
|
}
|
|
616
627
|
|
|
617
|
-
export { AuthenticationError, CboxIdClient, CboxIdError, ConfigurationError, Discovery, InvalidStateError, VaultClient, challenge, createVerifier, randomToken, verifyWebhook };
|
|
618
|
-
//# sourceMappingURL=chunk-
|
|
619
|
-
//# sourceMappingURL=chunk-
|
|
628
|
+
export { AuthenticationError, CboxIdClient, CboxIdError, ConfigurationError, Discovery, FrontendApiError, InvalidStateError, VaultClient, challenge, createVerifier, randomToken, verifyWebhook };
|
|
629
|
+
//# sourceMappingURL=chunk-3SRL7SIB.js.map
|
|
630
|
+
//# sourceMappingURL=chunk-3SRL7SIB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/pkce.ts","../src/vault.ts","../src/webhook.ts","../src/discovery.ts","../src/client.ts"],"names":["key"],"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;AAGO,IAAM,kBAAA,GAAN,cAAiC,WAAA,CAAY;AAAC;AAM9C,IAAM,iBAAA,GAAN,cAAgC,WAAA,CAAY;AAAC;AAM7C,IAAM,mBAAA,GAAN,cAAkC,WAAA,CAAY;AAAC;AAiB/C,IAAM,gBAAA,GAAN,cAA+B,WAAA,CAAY;AAAA,EAChD,WAAA,CACE,OAAA,EACS,IAAA,EACA,MAAA,EACA,UAAA,EACT;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAJJ,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAAA,EAGX;AAAA,EALW,IAAA;AAAA,EACA,MAAA;AAAA,EACA,UAAA;AAIb;;;AC7CA,SAAS,UAAU,KAAA,EAA2B;AAC5C,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAAA,EACpC;AACA,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG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CAAO,MAAM,CAAA,KAAM,QAAA,GAAW,MAAA,CAAO,MAAM,CAAA,GAAI,MAAM,CAAA;AAAA,IAC1F;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-3SRL7SIB.js","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 */\nexport class AuthenticationError extends CboxIdError {}\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","/**\n * PKCE (RFC 7636) and the random values the login flow needs, built on Web Crypto\n * (`globalThis.crypto`) so the same code runs on Node, edge runtimes and browsers.\n */\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n/** A URL-safe random token of `bytes` bytes (default 32), for state and nonce. */\nexport function randomToken(bytes = 32): string {\n return base64url(crypto.getRandomValues(new Uint8Array(bytes)));\n}\n\n/** A high-entropy PKCE code verifier. */\nexport function createVerifier(): string {\n return randomToken(32);\n}\n\n/** The S256 code challenge for a verifier. */\nexport async function challenge(verifier: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));\n return base64url(new Uint8Array(digest));\n}\n","import { AuthenticationError } from './errors.js';\n\n/** A stored vault secret's metadata (never its plaintext). */\nexport interface VaultSecretRef {\n id: string;\n name: string;\n provider: string;\n ownerType: string | null;\n ownerId: string | null;\n expiresAt: string | null;\n revoked: boolean;\n}\n\n/** A brokered credential — the plaintext, for immediate use. */\nexport interface VaultLease {\n secretId: string;\n provider: string;\n secret: string;\n expiresAt: string;\n}\n\nexport interface StoreSecretInput {\n name: string;\n provider: string;\n secret: string;\n ownerType?: 'organization' | 'user';\n ownerId?: string;\n expiresAt?: string;\n}\n\n/**\n * Client for a Cbox ID instance's Token Vault API. Bind it to an access token\n * (obtain one with {@link CboxIdClient.machineToken}, scoped `vault.manage` for\n * provisioning or `vault.lease` for redeeming). All calls are server-to-server.\n */\nexport class VaultClient {\n private readonly base: string;\n\n constructor(\n issuer: string,\n private readonly token: string,\n private readonly timeoutMs = 10_000,\n ) {\n this.base = `${issuer.replace(/\\/$/, '')}/api/v1/vault`;\n }\n\n /** Ingest a downstream credential, sealed at rest (scope `vault.manage`). */\n store(input: StoreSecretInput): Promise<VaultSecretRef> {\n return this.json<VaultSecretRef>('POST', '/secrets', {\n name: input.name,\n provider: input.provider,\n secret: input.secret,\n owner_type: input.ownerType,\n owner_id: input.ownerId,\n expires_at: input.expiresAt,\n });\n }\n\n /** Rotate a secret's value, keeping its id and grants (scope `vault.manage`). */\n rotate(secretId: string, secret: string): Promise<VaultSecretRef> {\n return this.json<VaultSecretRef>('POST', `/secrets/${encodeURIComponent(secretId)}/rotate`, { secret });\n }\n\n /** Revoke a secret permanently (scope `vault.manage`). */\n async revoke(secretId: string): Promise<void> {\n await this.request('DELETE', `/secrets/${encodeURIComponent(secretId)}`);\n }\n\n /** Authorize an agent client to lease a secret (scope `vault.manage`). */\n grant(\n secretId: string,\n clientId: string,\n maxTtlSeconds?: number,\n ): Promise<{ secretId: string; clientId: string; maxTtlSeconds: number | null }> {\n return this.json('POST', `/secrets/${encodeURIComponent(secretId)}/grants`, {\n client_id: clientId,\n max_ttl_seconds: maxTtlSeconds,\n }).then((raw) => {\n const r = raw as { secret_id: string; client_id: string; max_ttl_seconds: number | null };\n return { secretId: r.secret_id, clientId: r.client_id, maxTtlSeconds: r.max_ttl_seconds };\n });\n }\n\n /** Revoke an agent's authorization (scope `vault.manage`). */\n async revokeGrant(secretId: string, clientId: string): Promise<void> {\n await this.request(\n 'DELETE',\n `/secrets/${encodeURIComponent(secretId)}/grants/${encodeURIComponent(clientId)}`,\n );\n }\n\n /**\n * Redeem a leased credential for immediate use (scope `vault.lease`). The caller\n * is identified by the token's client; a lease with no live grant is refused.\n */\n lease(secretId: string, purpose: string): Promise<VaultLease> {\n return this.json('POST', `/secrets/${encodeURIComponent(secretId)}/lease`, { purpose }).then((raw) => {\n const r = raw as { secret_id: string; provider: string; secret: string; expires_at: string };\n return { secretId: r.secret_id, provider: r.provider, secret: r.secret, expiresAt: r.expires_at };\n });\n }\n\n private async json<T>(method: string, path: string, body: Record<string, unknown>): Promise<T> {\n const response = await this.request(method, path, body);\n return (await response.json()) as T;\n }\n\n private async request(method: string, path: string, body?: Record<string, unknown>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n const init: RequestInit = {\n method,\n headers: {\n authorization: `Bearer ${this.token}`,\n ...(body ? { 'content-type': 'application/json' } : {}),\n },\n signal: controller.signal,\n };\n if (body) {\n init.body = JSON.stringify(body);\n }\n const response = await fetch(`${this.base}${path}`, init);\n if (!response.ok) {\n throw new AuthenticationError(`Vault ${method} ${path} failed with status ${response.status}.`);\n }\n return response;\n } finally {\n clearTimeout(timer);\n }\n }\n}\n","/**\n * Verify a Cbox ID webhook / inline-action signature. The header is\n * `X-Cbox-Signature: t={unix},v1={hex hmac}` — an HMAC-SHA256 over\n * `\"{timestamp}.{raw body}\"`, valid within a freshness window. Built on Web Crypto\n * so it runs on Node, edge and the browser.\n */\n\n/** Constant-time compare of two hex strings. */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\nfunction toHex(bytes: ArrayBuffer): string {\n return Array.from(new Uint8Array(bytes))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\nexport interface VerifyWebhookOptions {\n /** The RAW request body — the exact bytes received, not a re-encoded copy. */\n payload: string;\n /** The value of the `X-Cbox-Signature` header. */\n signatureHeader: string | null | undefined;\n /** The signing secret issued when the webhook/action endpoint was registered. */\n secret: string;\n /** Freshness window in seconds. Defaults to 300 (5 minutes). */\n toleranceSeconds?: number;\n /** Injectable clock (unix seconds), for tests. Defaults to `Date.now()`. */\n now?: number;\n}\n\n/** Returns `true` only when the signature is present, fresh and valid. Never throws. */\nexport async function verifyWebhook(options: VerifyWebhookOptions): Promise<boolean> {\n const { payload, signatureHeader, secret } = options;\n const toleranceSeconds = options.toleranceSeconds ?? 300;\n const now = options.now ?? Math.floor(Date.now() / 1000);\n\n if (!signatureHeader) {\n return false;\n }\n\n const parts: Record<string, string> = {};\n for (const segment of signatureHeader.split(',')) {\n const [key, value] = segment.trim().split('=', 2);\n if (key) {\n parts[key] = value ?? '';\n }\n }\n\n const timestamp = parts['t'] ?? '';\n const signature = parts['v1'] ?? '';\n\n if (timestamp === '' || signature === '' || !/^\\d+$/.test(timestamp)) {\n return false;\n }\n\n if (Math.abs(now - 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 const expected = toHex(\n await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${timestamp}.${payload}`)),\n );\n\n return timingSafeEqual(expected, signature);\n}\n","import { AuthenticationError, ConfigurationError } from './errors.js';\nimport type { DiscoveryDocument } from './types.js';\n\n/**\n * Fetches and caches an instance's OIDC discovery document. One instance of this\n * lives per {@link CboxIdClient}; the document is refetched only after the TTL.\n */\nexport class Discovery {\n private cached: { doc: DiscoveryDocument; expiresAt: number } | null = null;\n\n constructor(\n private readonly issuer: string,\n private readonly timeoutMs: number,\n private readonly cacheTtlMs: number,\n private readonly now: () => number = Date.now,\n ) {}\n\n async document(): Promise<DiscoveryDocument> {\n if (this.cached && this.cached.expiresAt > this.now()) {\n return this.cached.doc;\n }\n\n const url = `${this.issuer.replace(/\\/$/, '')}/.well-known/openid-configuration`;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n let doc: DiscoveryDocument;\n try {\n const response = await fetch(url, { signal: controller.signal });\n if (!response.ok) {\n throw new AuthenticationError(`Discovery request failed with status ${response.status}.`);\n }\n doc = (await response.json()) as DiscoveryDocument;\n } catch (error) {\n if (error instanceof AuthenticationError) {\n throw error;\n }\n throw new AuthenticationError(`Discovery request failed: ${String(error)}`);\n } finally {\n clearTimeout(timer);\n }\n\n if (typeof doc.issuer !== 'string' || doc.issuer === '') {\n throw new AuthenticationError('The discovery document was missing an issuer.');\n }\n\n this.cached = { doc, expiresAt: this.now() + this.cacheTtlMs };\n return doc;\n }\n\n /** A required endpoint from the discovery document. */\n async endpoint(name: keyof DiscoveryDocument): Promise<string> {\n const value = (await this.document())[name];\n if (typeof value !== 'string' || value === '') {\n throw new ConfigurationError(`The instance does not advertise a ${name}.`);\n }\n return value;\n }\n\n /** An optional endpoint, or null when the instance advertises none. */\n async optionalEndpoint(name: keyof DiscoveryDocument): Promise<string | null> {\n const value = (await this.document())[name];\n return typeof value === 'string' && value !== '' ? value : null;\n }\n}\n","import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'jose';\nimport { Discovery } from './discovery.js';\nimport { AuthenticationError, ConfigurationError, InvalidStateError } from './errors.js';\nimport { challenge, createVerifier, randomToken } from './pkce.js';\nimport type {\n AuthorizationRequest,\n CboxIdConfig,\n CboxOrganization,\n CboxUser,\n RefreshedTokens,\n TokenResponse,\n TokenTypeHint,\n} from './types.js';\nimport { VaultClient } from './vault.js';\nimport { verifyWebhook, type VerifyWebhookOptions } from './webhook.js';\n\ntype JwksResolver = ReturnType<typeof createRemoteJWKSet>;\n\n/** Query parameters as they arrive on your callback route. */\nexport interface CallbackParams {\n code?: string | null;\n state?: string | null;\n error?: string | null;\n error_description?: string | null;\n}\n\n/** The values you persisted from {@link CboxIdClient.createAuthorizationRequest}. */\nexport interface StoredAuthState {\n state: string;\n codeVerifier: string;\n nonce: string;\n /** The `maxAge` this login demanded, if any. See {@link AuthorizationRequest.maxAge}. */\n maxAge?: number;\n}\n\n/**\n * Turnkey Cbox ID client for JavaScript/TypeScript. It speaks standard OpenID\n * Connect against a Cbox ID instance — so integrating is a redirect and a callback,\n * not a rewrite — and adds the conveniences a hosted-identity product needs: a\n * redirect to the instance's hosted profile page, and back-channel helpers (machine\n * tokens, userinfo, introspection, webhook verification).\n *\n * Login is hardened by default: PKCE (S256), a CSRF state check, a nonce, and full\n * id_token signature + issuer + audience verification against the instance's JWKS\n * (via `jose`).\n *\n * The class is framework-agnostic: {@link createAuthorizationRequest} hands you the\n * `state`, `codeVerifier` and `nonce` to persist however you like, and\n * {@link authenticate} takes them back. For Next.js, the `@cboxdk/id-js/nextjs`\n * entry wires this to cookies for you.\n */\nexport class CboxIdClient {\n private readonly discovery: Discovery;\n private readonly jwksByUri = new Map<string, JwksResolver>();\n\n constructor(private readonly config: CboxIdConfig) {\n if (!config.issuer) {\n throw new ConfigurationError('Cbox ID config `issuer` is required.');\n }\n if (!config.clientId) {\n throw new ConfigurationError('Cbox ID config `clientId` is required.');\n }\n if (!config.redirectUri) {\n throw new ConfigurationError('Cbox ID config `redirectUri` is required.');\n }\n this.discovery = new Discovery(\n config.issuer,\n config.timeoutMs ?? 10_000,\n config.cacheTtlMs ?? 3_600_000,\n );\n }\n\n /**\n * Begin login. Returns the authorize URL plus the `state`, `codeVerifier` and\n * `nonce` — persist those (signed, httpOnly cookies are ideal) and hand them back\n * to {@link authenticate} on the callback.\n */\n async createAuthorizationRequest(options: {\n scopes?: string[];\n redirectUri?: string;\n state?: string;\n prompt?: string;\n loginHint?: string;\n maxAge?: number;\n } = {}): Promise<AuthorizationRequest> {\n const codeVerifier = createVerifier();\n const state = options.state ?? randomToken(16);\n const nonce = randomToken(16);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: this.config.clientId,\n redirect_uri: options.redirectUri ?? this.config.redirectUri,\n scope: (options.scopes ?? this.scopes()).join(' '),\n state,\n nonce,\n code_challenge: await challenge(codeVerifier),\n code_challenge_method: 'S256',\n });\n if (options.prompt) {\n params.set('prompt', options.prompt);\n }\n if (options.loginHint) {\n params.set('login_hint', options.loginHint);\n }\n if (typeof options.maxAge === 'number') {\n params.set('max_age', String(options.maxAge));\n }\n\n const endpoint = await this.discovery.endpoint('authorization_endpoint');\n return {\n url: `${endpoint}?${params.toString()}`,\n state,\n codeVerifier,\n nonce,\n // Carried through so authenticate() can hold the instance to it. Only present\n // when requested (exactOptionalPropertyTypes).\n ...(typeof options.maxAge === 'number' ? { maxAge: options.maxAge } : {}),\n };\n }\n\n /**\n * Complete login on your callback route: verify state, exchange the code with the\n * PKCE verifier, verify the id_token, and return the authenticated user.\n *\n * @throws InvalidStateError when state does not match (forged/stale request)\n * @throws AuthenticationError on any other failure\n */\n async authenticate(input: {\n params: CallbackParams;\n stored: StoredAuthState;\n redirectUri?: string;\n }): Promise<CboxUser> {\n const { params, stored } = input;\n\n if (!params.state || !stored.state || !timingSafeEqualString(params.state, stored.state)) {\n throw new InvalidStateError('The login state did not match — the request may be forged or stale.');\n }\n\n if (params.error) {\n throw new AuthenticationError(\n `Cbox ID returned an error: ${params.error}${params.error_description ? ` (${params.error_description})` : ''}`,\n );\n }\n\n if (!params.code) {\n throw new AuthenticationError('The callback was missing an authorization code.');\n }\n\n const tokens = await this.exchange(params.code, stored.codeVerifier, input.redirectUri);\n\n if (!tokens.access_token) {\n throw new AuthenticationError('No access token was returned.');\n }\n\n let claims: Record<string, unknown> = {};\n if (tokens.id_token) {\n claims = await this.verifyIdToken(tokens.id_token, stored.nonce, stored.maxAge);\n } else if (typeof stored.maxAge === 'number') {\n // No id_token means no auth_time, and therefore no evidence the demanded\n // re-authentication happened. Accepting that silently is the whole defect.\n throw new AuthenticationError(\n 'A max_age was requested but no id_token was returned, so the authentication age could not be verified.',\n );\n }\n // Enrich with userinfo (email/name/org a minimal id_token may omit).\n claims = { ...claims, ...(await this.userinfo(tokens.access_token)) };\n\n const sub = claims['sub'];\n if (typeof sub !== 'string' || sub === '') {\n throw new AuthenticationError('The verified token carried no subject.');\n }\n\n const organizations = parseOrganizations(claims['organizations']);\n\n return {\n id: sub,\n email: typeof claims['email'] === 'string' ? claims['email'] : null,\n name: typeof claims['name'] === 'string' ? claims['name'] : null,\n organizationId: typeof claims['org'] === 'string' ? claims['org'] : null,\n // Only present when the instance emitted the claim (exactOptionalPropertyTypes).\n ...(organizations ? { organizations } : {}),\n claims,\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token ?? null,\n idToken: tokens.id_token ?? null,\n expiresIn: typeof tokens.expires_in === 'number' ? tokens.expires_in : 0,\n };\n }\n\n /**\n * Exchange a refresh token for a fresh access token (OAuth 2.0 `refresh_token`\n * grant). Cbox ID rotates refresh tokens and detects reuse, so ALWAYS persist the\n * returned `refreshToken` and discard the one you passed — presenting a rotated\n * token again revokes the entire token family.\n *\n * @throws AuthenticationError when the refresh token is invalid, expired, or already rotated.\n */\n async refresh(refreshToken: string): Promise<RefreshedTokens> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: this.config.clientId,\n refresh_token: refreshToken,\n });\n if (this.config.clientSecret) {\n body.set('client_secret', this.config.clientSecret);\n }\n\n const response = await this.post(await this.discovery.endpoint('token_endpoint'), body);\n if (!response.ok) {\n throw new AuthenticationError(`Token refresh failed: ${await response.text()}`);\n }\n\n const tokens = (await response.json()) as TokenResponse;\n if (!tokens.access_token) {\n throw new AuthenticationError('The refresh response carried no access token.');\n }\n\n return {\n accessToken: tokens.access_token,\n // Keep the presented token when the server does not rotate (OAuth 2.0 §6);\n // callers persist this value, so it must never come back null.\n refreshToken: tokens.refresh_token ?? refreshToken,\n idToken: tokens.id_token ?? null,\n expiresIn: typeof tokens.expires_in === 'number' ? tokens.expires_in : 0,\n scope: typeof tokens.scope === 'string' ? tokens.scope : null,\n };\n }\n\n /**\n * The URL of the instance's hosted account/profile page (self-service password,\n * MFA, passkeys, sessions). A signed-in user is authenticated there by their Cbox\n * ID session; `returnTo` is passed so the page can link back to your app.\n */\n profileUrl(returnTo?: string): string {\n const base = `${this.config.issuer.replace(/\\/$/, '')}${this.accountPath()}`;\n return returnTo ? `${base}?${new URLSearchParams({ return_to: returnTo }).toString()}` : base;\n }\n\n /**\n * The RP-initiated logout URL, or null when the instance advertises none.\n *\n * `client_id` is always sent, even without a `returnTo`: the OP validates\n * `post_logout_redirect_uri` against the registered allow-list of THAT client\n * (OIDC RP-Initiated Logout 1.0 §2). With no way to name the RP the OP cannot\n * check the list, so it silently drops the return URL and strands the user on a\n * bare \"you are signed out\" page. `idTokenHint` — the user's `id_token`, if you\n * still hold it — is the spec's other way to identify the RP, and additionally\n * tells the OP which subject is logging out.\n */\n async logoutUrl(returnTo?: string, idTokenHint?: string): Promise<string | null> {\n const endpoint = await this.discovery.optionalEndpoint('end_session_endpoint');\n if (!endpoint) {\n return null;\n }\n const params = new URLSearchParams({ client_id: this.config.clientId });\n if (returnTo) {\n params.set('post_logout_redirect_uri', returnTo);\n }\n if (idTokenHint) {\n params.set('id_token_hint', idTokenHint);\n }\n return `${endpoint}?${params.toString()}`;\n }\n\n /**\n * A machine (client-credentials) access token for calling Cbox ID APIs as your\n * app, not on a user's behalf. Requires a client secret.\n */\n async machineToken(options: { scopes?: string[]; resource?: string } = {}): Promise<string> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: this.config.clientId,\n client_secret: this.requireSecret(),\n });\n if (options.scopes && options.scopes.length > 0) {\n body.set('scope', options.scopes.join(' '));\n }\n if (options.resource) {\n body.set('resource', options.resource);\n }\n\n const response = await this.post(await this.discovery.endpoint('token_endpoint'), body);\n if (!response.ok) {\n throw new AuthenticationError(`Machine token request failed: ${await response.text()}`);\n }\n const json = (await response.json()) as { access_token?: unknown };\n if (typeof json.access_token !== 'string') {\n throw new AuthenticationError('The token response had no access_token.');\n }\n return json.access_token;\n }\n\n /** The OIDC userinfo claims for an access token. */\n async userinfo(accessToken: string): Promise<Record<string, unknown>> {\n const endpoint = await this.discovery.optionalEndpoint('userinfo_endpoint');\n if (!endpoint) {\n return {};\n }\n const response = await this.fetchWithTimeout(endpoint, {\n headers: { authorization: `Bearer ${accessToken}` },\n });\n if (!response.ok) {\n throw new AuthenticationError('Userinfo request failed.');\n }\n return (await response.json()) as Record<string, unknown>;\n }\n\n /**\n * RFC 7662 token introspection (confidential-client auth). Returns the raw\n * response; `active` tells you if the token is currently valid. Requires a secret.\n */\n async introspect(token: string): Promise<Record<string, unknown>> {\n const endpoint = await this.discovery.endpoint('introspection_endpoint');\n const basic = btoa(`${this.config.clientId}:${this.requireSecret()}`);\n const response = await this.post(\n endpoint,\n new URLSearchParams({ token }),\n { authorization: `Basic ${basic}` },\n );\n if (!response.ok) {\n throw new AuthenticationError('Introspection request failed.');\n }\n return (await response.json()) as Record<string, unknown>;\n }\n\n /**\n * RFC 7009 token revocation (confidential-client auth). Revokes an access or\n * refresh token; revoking a refresh token also drops the whole token family, so\n * this is what a real \"sign out everywhere\" does. Requires a secret.\n *\n * Per RFC 7009 the server answers 200 for an unknown or already-revoked token, so\n * a successful call means \"the token is not valid any more\", not \"it existed\".\n *\n * @param tokenTypeHint which store to search first — only a hint, never required.\n */\n async revoke(token: string, tokenTypeHint?: TokenTypeHint): Promise<void> {\n const endpoint = await this.discovery.endpoint('revocation_endpoint');\n const basic = btoa(`${this.config.clientId}:${this.requireSecret()}`);\n const body = new URLSearchParams({ token });\n if (tokenTypeHint) {\n body.set('token_type_hint', tokenTypeHint);\n }\n const response = await this.post(endpoint, body, { authorization: `Basic ${basic}` });\n if (!response.ok) {\n throw new AuthenticationError('Revocation request failed.');\n }\n }\n\n /** Verify a Cbox ID webhook / inline-action signature. See {@link verifyWebhook}. */\n verifyWebhook(options: VerifyWebhookOptions): Promise<boolean> {\n return verifyWebhook(options);\n }\n\n /**\n * A Token Vault client bound to an access token. Obtain the token with\n * {@link machineToken} (scope `vault.manage` to provision/grant, `vault.lease` to\n * redeem), then call `store` / `grant` / `lease` etc.\n */\n vault(accessToken: string): VaultClient {\n return new VaultClient(this.config.issuer, accessToken, this.config.timeoutMs ?? 10_000);\n }\n\n private async exchange(code: string, verifier: string, redirectUri?: string): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n code,\n redirect_uri: redirectUri ?? this.config.redirectUri,\n client_id: this.config.clientId,\n code_verifier: verifier,\n });\n if (this.config.clientSecret) {\n body.set('client_secret', this.config.clientSecret);\n }\n\n const response = await this.post(await this.discovery.endpoint('token_endpoint'), body);\n if (!response.ok) {\n throw new AuthenticationError(`Token exchange failed: ${await response.text()}`);\n }\n return (await response.json()) as TokenResponse;\n }\n\n private async verifyIdToken(\n idToken: string,\n nonce: string,\n maxAge?: number,\n ): Promise<Record<string, unknown>> {\n const jwksUri = await this.discovery.endpoint('jwks_uri');\n let resolver = this.jwksByUri.get(jwksUri);\n if (!resolver) {\n resolver = createRemoteJWKSet(new URL(jwksUri));\n this.jwksByUri.set(jwksUri, resolver);\n }\n\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(idToken, resolver, {\n issuer: this.config.issuer,\n audience: this.config.clientId,\n // Pin the accepted signature algorithms explicitly. `jose` already refuses\n // `alg: none` and key-type confusion, so this is belt-and-braces — but it\n // states the contract in code rather than relying on a library default.\n algorithms: ['RS256', 'ES256'],\n }));\n } catch (error) {\n throw new AuthenticationError(`The id_token could not be verified: ${String(error)}`);\n }\n\n if (nonce && payload['nonce'] !== nonce) {\n throw new AuthenticationError('The id_token nonce did not match — possible replay.');\n }\n\n // OIDC Core §3.1.3.7 step 12: when max_age was requested, `auth_time` is REQUIRED\n // and the relying party MUST check it. `max_age` is the control you reach for\n // before a payment or an admin grant, and the whole point is that the person\n // authenticated JUST NOW — so a login({maxAge}) whose result is never checked is a\n // step-up in name only: a day-old session comes back carrying its original\n // auth_time and nothing anywhere says so.\n if (typeof maxAge === 'number') {\n const authTime = payload['auth_time'];\n\n if (typeof authTime !== 'number') {\n throw new AuthenticationError(\n 'A max_age was requested but the id_token carried no auth_time, so the authentication age could not be verified.',\n );\n }\n\n const tolerance = this.config.authTimeToleranceSeconds ?? 60;\n const age = Math.floor(Date.now() / 1000) - authTime;\n\n if (age > maxAge + tolerance) {\n throw new AuthenticationError(\n `The authentication is ${age}s old but max_age required ${maxAge}s — the user did not re-authenticate.`,\n );\n }\n }\n\n return payload as Record<string, unknown>;\n }\n\n private scopes(): string[] {\n const scopes = this.config.scopes;\n return scopes && scopes.length > 0 ? scopes : ['openid', 'profile', 'email'];\n }\n\n private accountPath(): string {\n const path = this.config.accountPath;\n // `/account`, not `/settings`. The latter is the organization-admin page: it\n // redirects a non-admin to `/account` and drops `return_to` on the way, so a member\n // following this link arrives at the right screen having lost where they came from.\n return path && path !== '' ? `/${path.replace(/^\\//, '')}` : '/account';\n }\n\n private requireSecret(): string {\n if (!this.config.clientSecret) {\n throw new ConfigurationError('This call requires a `clientSecret`, but none is configured.');\n }\n return this.config.clientSecret;\n }\n\n private post(url: string, body: URLSearchParams, headers: Record<string, string> = {}): Promise<Response> {\n return this.fetchWithTimeout(url, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', ...headers },\n body,\n });\n }\n\n private async fetchWithTimeout(url: string, init: RequestInit): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.config.timeoutMs ?? 10_000);\n try {\n return await fetch(url, { ...init, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\n/** Constant-time string compare, so state validation doesn't leak via timing. */\nfunction timingSafeEqualString(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n let mismatch = 0;\n for (let i = 0; i < a.length; i++) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Parse an `organizations` claim into typed orgs, ignoring anything malformed. The\n * claim is optional and instance-specific; absent or non-array → undefined, so\n * callers can tell \"no claim\" from \"empty\".\n */\nfunction parseOrganizations(claim: unknown): CboxOrganization[] | undefined {\n if (!Array.isArray(claim)) {\n return undefined;\n }\n const orgs: CboxOrganization[] = [];\n for (const entry of claim) {\n if (typeof entry !== 'object' || entry === null) {\n continue;\n }\n const record = entry as Record<string, unknown>;\n const id = record['id'];\n const name = record['name'];\n if (typeof id === 'string' && id !== '' && typeof name === 'string' && name !== '') {\n orgs.push({ id, name, role: typeof record['role'] === 'string' ? record['role'] : null });\n }\n }\n return orgs;\n}\n"]}
|