@zuiio/oidc 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,110 @@
1
- # Temporary Holding Version
1
+ # @zuiio/oidc
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OIDC client library for integrating non-Supabase applications with Zuiio ID.
4
+
5
+ ## When to use this
6
+
7
+ Use this package when your application **does not** use Supabase Auth and you
8
+ want to authenticate users through Zuiio ID (the Zuiio ecosystem's central
9
+ identity provider).
10
+
11
+ If your app **does** use Supabase Auth, use `@zuiio/auth` instead — it
12
+ integrates via the `custom:zuiio` OIDC provider with a simpler API.
13
+
14
+ ## Quickstart
15
+
16
+ ```bash
17
+ pnpm add @zuiio/oidc openid-client
18
+ ```
19
+
20
+ ### 1. Register your application
21
+
22
+ Contact the Zuiio team to register an OAuth client for your application.
23
+ You'll receive a `client_id` and `client_secret`.
24
+
25
+ ### 2. Create the client
26
+
27
+ ```ts
28
+ import { createZuiioOidcClient } from "@zuiio/oidc";
29
+
30
+ const zuiioId = await createZuiioOidcClient({
31
+ issuer: "https://id.zuiiotech.com",
32
+ clientId: process.env.ZUIIO_OIDC_CLIENT_ID!,
33
+ clientSecret: process.env.ZUIIO_OIDC_CLIENT_SECRET!,
34
+ redirectUri: "https://yourapp.com/auth/callback",
35
+ });
36
+ ```
37
+
38
+ ### 3. Start login (server-side route)
39
+
40
+ ```ts
41
+ const auth = await zuiioId.beginAuthorization();
42
+ // Store auth.state, auth.nonce, auth.codeVerifier in an encrypted session
43
+ // (never in localStorage or URL params)
44
+ session.set("oidc_transaction", auth);
45
+ redirect(auth.url);
46
+ ```
47
+
48
+ ### 4. Handle callback
49
+
50
+ ```ts
51
+ const transaction = session.get("oidc_transaction");
52
+ const tokens = await zuiioId.handleCallback(request.url, transaction);
53
+ session.destroy("oidc_transaction");
54
+ session.set("tokens", tokens);
55
+ ```
56
+
57
+ ### 5. Fetch user info
58
+
59
+ ```ts
60
+ const user = await zuiioId.userinfo(tokens.accessToken);
61
+ // user.sub, user.email, user.name, user.username, ...
62
+ ```
63
+
64
+ ### 6. Refresh tokens
65
+
66
+ ```ts
67
+ const newTokens = await zuiioId.refresh(tokens.refreshToken);
68
+ ```
69
+
70
+ ### 7. Logout
71
+
72
+ ```ts
73
+ const logoutUrl = zuiioId.endSessionUrl(tokens.idToken, "https://yourapp.com");
74
+ // Redirect the user to this URL
75
+ redirect(logoutUrl);
76
+ ```
77
+
78
+ ## API
79
+
80
+ ### `createZuiioOidcClient(config)`
81
+
82
+ Creates an OIDC client by discovering the issuer's OpenID Provider metadata.
83
+
84
+ **Config:**
85
+
86
+ | Field | Type | Required | Description |
87
+ |-------|------|----------|-------------|
88
+ | `issuer` | `string` | Yes | Issuer URL (e.g. `https://id.zuiiotech.com`) |
89
+ | `clientId` | `string` | Yes | OAuth client ID |
90
+ | `clientSecret` | `string` | No | Client secret (omit for public clients) |
91
+ | `redirectUri` | `string` | Yes | Registered redirect URI |
92
+ | `scopes` | `string[]` | No | Default: `["openid", "profile", "email", "offline_access"]` |
93
+
94
+ ### Client methods
95
+
96
+ | Method | Returns | Description |
97
+ |--------|---------|-------------|
98
+ | `beginAuthorization()` | `AuthorizationTransaction` | Generate PKCE + state + nonce, return authorize URL |
99
+ | `handleCallback(url, tx)` | `ZuiioTokenSet` | Exchange code for tokens |
100
+ | `refresh(refreshToken)` | `ZuiioTokenSet` | Refresh an expired access token |
101
+ | `userinfo(accessToken)` | `ZuiioUserinfo` | Fetch userinfo from the userinfo endpoint |
102
+ | `endSessionUrl(idTokenHint, postLogoutRedirectUri)` | `string \| undefined` | Build RP-initiated logout URL |
103
+
104
+ ## Security
105
+
106
+ - **Server-side only.** Never expose `client_secret`, `codeVerifier`, or tokens
107
+ to the browser.
108
+ - Store `AuthorizationTransaction` in encrypted server sessions (not `localStorage`).
109
+ - The `openid-client` library validates ID token signatures, issuer, audience,
110
+ and nonce automatically.
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Zuiio OIDC client.
3
+ *
4
+ * A server-side OIDC client for integrating non-Supabase applications
5
+ * with Zuiio ID. Handles discovery, PKCE authorization, token exchange,
6
+ * refresh, and logout.
7
+ *
8
+ * Uses `openid-client` under the hood — the de facto standard Node.js
9
+ * OIDC library by Filip Skokan (panva).
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { createZuiioOidcClient } from "@zuiio/oidc";
14
+ *
15
+ * const client = await createZuiioOidcClient({
16
+ * issuer: "https://id.zuiiotech.com",
17
+ * clientId: "your-client-id",
18
+ * clientSecret: "your-client-secret",
19
+ * redirectUri: "https://yourapp.com/auth/callback",
20
+ * });
21
+ *
22
+ * // Start login
23
+ * const auth = await client.beginAuthorization();
24
+ * // Store auth.state, auth.nonce, auth.codeVerifier in session
25
+ * redirect(auth.url);
26
+ *
27
+ * // Handle callback
28
+ * const tokens = await client.handleCallback(request.url, auth);
29
+ * // tokens.accessToken, tokens.idToken, tokens.refreshToken
30
+ * ```
31
+ *
32
+ * @module
33
+ */
34
+ import { type Configuration, type TokenEndpointResponse } from "openid-client";
35
+ export interface ZuiioOidcConfig {
36
+ /** OIDC issuer URL (e.g. "https://id.zuiiotech.com") */
37
+ issuer: string;
38
+ /** OAuth client ID registered with Zuiio ID */
39
+ clientId: string;
40
+ /** OAuth client secret (for confidential clients) */
41
+ clientSecret?: string;
42
+ /** Redirect URI registered for this application */
43
+ redirectUri: string;
44
+ /** Requested scopes (default: "openid profile email offline_access") */
45
+ scopes?: string[];
46
+ }
47
+ /**
48
+ * An in-progress authorization transaction.
49
+ * Store these values server-side (encrypted session, not localStorage).
50
+ */
51
+ export interface AuthorizationTransaction {
52
+ /** Full authorize URL to redirect the user to */
53
+ url: string;
54
+ /** CSRF state parameter — verify on callback */
55
+ state: string;
56
+ /** Nonce for ID token validation */
57
+ nonce: string;
58
+ /** PKCE code verifier — must be stored for the callback exchange */
59
+ codeVerifier: string;
60
+ }
61
+ /** Token set returned after successful authentication. */
62
+ export interface ZuiioTokenSet {
63
+ /** Access token (JWT) */
64
+ accessToken: string;
65
+ /** ID token (JWT with user claims) */
66
+ idToken: string;
67
+ /** Refresh token (for obtaining new access tokens) */
68
+ refreshToken?: string;
69
+ /** Access token expiry as Unix timestamp (seconds) */
70
+ expiresAt?: number;
71
+ /** Raw openid-client token response (for advanced usage) */
72
+ raw: TokenEndpointResponse;
73
+ }
74
+ /** Userinfo claims returned from the userinfo endpoint. */
75
+ export interface ZuiioUserinfo {
76
+ sub: string;
77
+ email?: string;
78
+ emailVerified?: boolean;
79
+ name?: string;
80
+ fullName?: string;
81
+ username?: string;
82
+ picture?: string;
83
+ updatedAt?: number;
84
+ [key: string]: unknown;
85
+ }
86
+ /**
87
+ * Zuiio ID OIDC client interface.
88
+ *
89
+ * All methods are server-side only. Never expose tokens or
90
+ * code verifiers to the browser.
91
+ */
92
+ export interface ZuiioOidcClient {
93
+ /**
94
+ * Begin an authorization flow.
95
+ * Generates PKCE code challenge, state, and nonce.
96
+ * Returns the authorization URL and transaction state
97
+ * that must be stored server-side.
98
+ */
99
+ beginAuthorization(): Promise<AuthorizationTransaction>;
100
+ /**
101
+ * Handle the callback from Zuiio ID after the user authorizes.
102
+ * Exchanges the authorization code for tokens.
103
+ *
104
+ * @param callbackUrl - The full callback URL (with code + state params)
105
+ * @param transaction - The transaction from beginAuthorization()
106
+ * @returns Token set with access, ID, and optional refresh tokens
107
+ */
108
+ handleCallback(callbackUrl: string | URL, transaction: AuthorizationTransaction): Promise<ZuiioTokenSet>;
109
+ /**
110
+ * Refresh an expired access token.
111
+ *
112
+ * @param refreshToken - The refresh token from a previous token set
113
+ * @returns New token set
114
+ */
115
+ refresh(refreshToken: string): Promise<ZuiioTokenSet>;
116
+ /**
117
+ * Fetch userinfo from the userinfo endpoint.
118
+ *
119
+ * @param accessToken - A valid access token
120
+ * @returns Userinfo claims
121
+ */
122
+ userinfo(accessToken: string): Promise<ZuiioUserinfo>;
123
+ /**
124
+ * Build a logout URL that ends the session at Zuiio ID.
125
+ * Redirect the user to this URL to log them out of the identity provider.
126
+ *
127
+ * @param idTokenHint - The ID token (required by OIDC RP-Initiated Logout)
128
+ * @param postLogoutRedirectUri - Where to redirect after logout
129
+ * @returns Full logout URL
130
+ */
131
+ endSessionUrl(idTokenHint?: string, postLogoutRedirectUri?: string): string | undefined;
132
+ /** The underlying openid-client Configuration (for advanced use). */
133
+ raw: Configuration;
134
+ }
135
+ /**
136
+ * Create a Zuiio OIDC client by discovering the issuer's metadata.
137
+ *
138
+ * Fetches `/.well-known/openid-configuration` from the issuer to
139
+ * auto-configure endpoints, JWKS, and supported features.
140
+ *
141
+ * @param config - OIDC configuration
142
+ * @returns A configured OIDC client
143
+ *
144
+ * @throws If the issuer is unreachable or the client registration
145
+ * doesn't match the issuer's requirements.
146
+ */
147
+ export declare function createZuiioOidcClient(config: ZuiioOidcConfig): Promise<ZuiioOidcClient>;
148
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAcL,KAAK,aAAa,EAClB,KAAK,qBAAqB,EAE3B,MAAM,eAAe,CAAC;AAIvB,MAAM,WAAW,eAAe;IAC9B,wDAAwD;IACxD,MAAM,EAAE,MAAM,CAAC;IACf,+CAA+C;IAC/C,QAAQ,EAAE,MAAM,CAAC;IACjB,qDAAqD;IACrD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,mDAAmD;IACnD,WAAW,EAAE,MAAM,CAAC;IACpB,wEAAwE;IACxE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;CACnB;AAED;;;GAGG;AACH,MAAM,WAAW,wBAAwB;IACvC,iDAAiD;IACjD,GAAG,EAAE,MAAM,CAAC;IACZ,gDAAgD;IAChD,KAAK,EAA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,EAAE,MAAM,EACpB,qBAAqB,CAAC,EAAE,MAAM,GAC7B,MAAM,GAAG,SAAS,CAAC;IAEtB,qEAAqE;IACrE,GAAG,EAAE,aAAa,CAAC;CACpB;AAID;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,eAAe,GACtB,OAAO,CAAC,eAAe,CAAC,CA4H1B"}
package/dist/client.js ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Zuiio OIDC client.
3
+ *
4
+ * A server-side OIDC client for integrating non-Supabase applications
5
+ * with Zuiio ID. Handles discovery, PKCE authorization, token exchange,
6
+ * refresh, and logout.
7
+ *
8
+ * Uses `openid-client` under the hood — the de facto standard Node.js
9
+ * OIDC library by Filip Skokan (panva).
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { createZuiioOidcClient } from "@zuiio/oidc";
14
+ *
15
+ * const client = await createZuiioOidcClient({
16
+ * issuer: "https://id.zuiiotech.com",
17
+ * clientId: "your-client-id",
18
+ * clientSecret: "your-client-secret",
19
+ * redirectUri: "https://yourapp.com/auth/callback",
20
+ * });
21
+ *
22
+ * // Start login
23
+ * const auth = await client.beginAuthorization();
24
+ * // Store auth.state, auth.nonce, auth.codeVerifier in session
25
+ * redirect(auth.url);
26
+ *
27
+ * // Handle callback
28
+ * const tokens = await client.handleCallback(request.url, auth);
29
+ * // tokens.accessToken, tokens.idToken, tokens.refreshToken
30
+ * ```
31
+ *
32
+ * @module
33
+ */
34
+ import { ClientSecretBasic, None, authorizationCodeGrant, buildAuthorizationUrl, buildEndSessionUrl, calculatePKCECodeChallenge, discovery, fetchUserInfo, randomNonce, randomPKCECodeVerifier, randomState, refreshTokenGrant, skipSubjectCheck, } from "openid-client";
35
+ // ─── Factory ────────────────────────────────────────────────────────
36
+ /**
37
+ * Create a Zuiio OIDC client by discovering the issuer's metadata.
38
+ *
39
+ * Fetches `/.well-known/openid-configuration` from the issuer to
40
+ * auto-configure endpoints, JWKS, and supported features.
41
+ *
42
+ * @param config - OIDC configuration
43
+ * @returns A configured OIDC client
44
+ *
45
+ * @throws If the issuer is unreachable or the client registration
46
+ * doesn't match the issuer's requirements.
47
+ */
48
+ export async function createZuiioOidcClient(config) {
49
+ const oidc = await discovery(new URL(config.issuer), config.clientId, {
50
+ redirect_uris: [config.redirectUri],
51
+ response_types: ["code"],
52
+ token_endpoint_auth_method: config.clientSecret
53
+ ? "client_secret_basic"
54
+ : "none",
55
+ }, config.clientSecret ? ClientSecretBasic(config.clientSecret) : None());
56
+ const scopes = config.scopes ?? [
57
+ "openid",
58
+ "profile",
59
+ "email",
60
+ "offline_access",
61
+ ];
62
+ function toTokenSet(response) {
63
+ return {
64
+ accessToken: response.access_token,
65
+ idToken: response.id_token ?? "",
66
+ refreshToken: response.refresh_token,
67
+ expiresAt: typeof response.expires_in === "number"
68
+ ? Math.floor(Date.now() / 1000) + response.expires_in
69
+ : undefined,
70
+ raw: response,
71
+ };
72
+ }
73
+ // ── beginAuthorization ──
74
+ async function beginAuthorization() {
75
+ const codeVerifier = randomPKCECodeVerifier();
76
+ const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);
77
+ const state = randomState();
78
+ const nonce = randomNonce();
79
+ const url = buildAuthorizationUrl(oidc, {
80
+ redirect_uri: config.redirectUri,
81
+ scope: scopes.join(" "),
82
+ code_challenge: codeChallenge,
83
+ code_challenge_method: "S256",
84
+ state,
85
+ nonce,
86
+ });
87
+ return { url: url.href, state, nonce, codeVerifier };
88
+ }
89
+ // ── handleCallback ──
90
+ async function handleCallback(callbackUrl, transaction) {
91
+ const url = typeof callbackUrl === "string" ? new URL(callbackUrl) : callbackUrl;
92
+ const response = await authorizationCodeGrant(oidc, url, {
93
+ expectedState: transaction.state,
94
+ expectedNonce: transaction.nonce,
95
+ pkceCodeVerifier: transaction.codeVerifier,
96
+ });
97
+ return toTokenSet(response);
98
+ }
99
+ // ── refresh ──
100
+ async function refresh(refreshToken) {
101
+ return toTokenSet(await refreshTokenGrant(oidc, refreshToken));
102
+ }
103
+ // ── userinfo ──
104
+ async function userinfo(accessToken) {
105
+ const response = await fetchUserInfo(oidc, accessToken, skipSubjectCheck);
106
+ return {
107
+ ...response,
108
+ sub: response.sub,
109
+ email: response.email,
110
+ emailVerified: response.email_verified,
111
+ name: response.name,
112
+ fullName: typeof response.full_name === "string" ? response.full_name : undefined,
113
+ username: typeof response.username === "string"
114
+ ? response.username
115
+ : response.preferred_username,
116
+ picture: response.picture,
117
+ updatedAt: response.updated_at,
118
+ };
119
+ }
120
+ // ── endSessionUrl ──
121
+ function endSessionUrl(idTokenHint, postLogoutRedirectUri) {
122
+ if (!oidc.serverMetadata().end_session_endpoint)
123
+ return undefined;
124
+ const parameters = {};
125
+ if (idTokenHint)
126
+ parameters.id_token_hint = idTokenHint;
127
+ if (postLogoutRedirectUri) {
128
+ parameters.post_logout_redirect_uri = postLogoutRedirectUri;
129
+ }
130
+ return buildEndSessionUrl(oidc, parameters).href;
131
+ }
132
+ return {
133
+ beginAuthorization,
134
+ handleCallback,
135
+ refresh,
136
+ userinfo,
137
+ endSessionUrl,
138
+ raw: oidc,
139
+ };
140
+ }
141
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EACL,iBAAiB,EACjB,IAAI,EACJ,sBAAsB,EACtB,qBAAqB,EACrB,kBAAkB,EAClB,0BAA0B,EAC1B,SAAS,EACT,aAAa,EACb,WAAW,EACX,sBAAsB,EACtB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,GAIjB,MAAM,eAAe,CAAC;AAwHvB,uEAAuE;AAEvE;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,MAAuB;IAEvB,MAAM,IAAI,GAAG,MAAM,SAAS,CAC1B,IAAI,GAAG,CAAC,MAAM,CAAC,M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zE,QAAQ,EACN,OAAO,QAAQ,CAAC,QAAQ,KAAK,QAAQ;gBACnC,CAAC,CAAC,QAAQ,CAAC,QAAQ;gBACnB,CAAC,CAAC,QAAQ,CAAC,kBAAkB;YACjC,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,SAAS,EAAE,QAAQ,CAAC,UAAU;SAC/B,CAAC;IACJ,CAAC;IAED,sBAAsB;IACtB,SAAS,aAAa,CACpB,WAAoB,EACpB,qBAA8B;QAE9B,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC,oBAAoB;YAAE,OAAO,SAAS,CAAC;QAElE,MAAM,UAAU,GAA2B,EAAE,CAAC;QAC9C,IAAI,WAAW;YAAE,UAAU,CAAC,aAAa,GAAG,WAAW,CAAC;QACxD,IAAI,qBAAqB,EAAE,CAAC;YAC1B,UAAU,CAAC,wBAAwB,GAAG,qBAAqB,CAAC;QAC9D,CAAC;QAED,OAAO,kBAAkB,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC,IAAI,CAAC;IACnD,CAAC;IAED,OAAO;QACL,kBAAkB;QAClB,cAAc;QACd,OAAO;QACP,QAAQ;QACR,aAAa;QACb,GAAG,EAAE,IAAI;KACV,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Zuiio OIDC client.\n *\n * A server-side OIDC client for integrating non-Supabase applications\n * with Zuiio ID. Handles discovery, PKCE authorization, token exchange,\n * refresh, and logout.\n *\n * Uses `openid-client` under the hood — the de facto standard Node.js\n * OIDC library by Filip Skokan (panva).\n *\n * @example\n * ```ts\n * import { createZuiioOidcClient } from \"@zuiio/oidc\";\n *\n * const client = await createZuiioOidcClient({\n * issuer: \"https://id.zuiiotech.com\",\n * clientId: \"your-client-id\",\n * clientSecret: \"your-client-secret\",\n * redirectUri: \"https://yourapp.com/auth/callback\",\n * });\n *\n * // Start login\n * const auth = await client.beginAuthorization();\n * // Store auth.state, auth.nonce, auth.codeVerifier in session\n * redirect(auth.url);\n *\n * // Handle callback\n * const tokens = await client.handleCallback(request.url, auth);\n * // tokens.accessToken, tokens.idToken, tokens.refreshToken\n * ```\n *\n * @module\n */\n\nimport {\n ClientSecretBasic,\n None,\n authorizationCodeGrant,\n buildAuthorizationUrl,\n buildEndSessionUrl,\n calculatePKCECodeChallenge,\n discovery,\n fetchUserInfo,\n randomNonce,\n randomPKCECodeVerifier,\n randomState,\n refreshTokenGrant,\n skipSubjectCheck,\n type Configuration,\n type TokenEndpointResponse,\n type UserInfoResponse,\n} from \"openid-client\";\n\n// ─── Types ──────────────────────────────────────────────────────────\n\nexport interface ZuiioOidcConfig {\n /** OIDC issuer URL (e.g. \"https://id.zuiiotech.com\") */\n issuer: string;\n /** OAuth client ID registered with Zuiio ID */\n clientId: string;\n /** OAuth client secret (for confidential clients) */\n clientSecret?: string;\n /** Redirect URI registered for this application */\n redirectUri: string;\n /** Requested scopes (default: \"openid profile email offline_access\") */\n scopes?: string[];\n}\n\n/**\n * An in-progress authorization transaction.\n * Store these values server-side (encrypted session, not localStorage).\n */\nexport interface AuthorizationTransaction {\n /** Full authorize URL to redirect the user to */\n url: string;\n /** CSRF state parameter — verify on callback */\n state: string;\n /** Nonce for ID token validation */\n nonce: string;\n /** PKCE code verifier — must be stored for the callback exchange */\n codeVerifier: string;\n}\n\n/** Token set returned after successful authentication. */\nexport interface ZuiioTokenSet {\n /** Access token (JWT) */\n accessToken: string;\n /** ID token (JWT with user claims) */\n idToken: string;\n /** Refresh token (for obtaining new access tokens) */\n refreshToken?: string;\n /** Access token expiry as Unix timestamp (seconds) */\n expiresAt?: number;\n /** Raw openid-client token response (for advanced usage) */\n raw: TokenEndpointResponse;\n}\n\n/** Userinfo claims returned from the userinfo endpoint. */\nexport interface ZuiioUserinfo {\n sub: string;\n email?: string;\n emailVerified?: boolean;\n name?: string;\n fullName?: string;\n username?: string;\n picture?: string;\n updatedAt?: number;\n [key: string]: unknown;\n}\n\n/**\n * Zuiio ID OIDC client interface.\n *\n * All methods are server-side only. Never expose tokens or\n * code verifiers to the browser.\n */\nexport interface ZuiioOidcClient {\n /**\n * Begin an authorization flow.\n * Generates PKCE code challenge, state, and nonce.\n * Returns the authorization URL and transaction state\n * that must be stored server-side.\n */\n beginAuthorization(): Promise<AuthorizationTransaction>;\n\n /**\n * Handle the callback from Zuiio ID after the user authorizes.\n * Exchanges the authorization code for tokens.\n *\n * @param callbackUrl - The full callback URL (with code + state params)\n * @param transaction - The transaction from beginAuthorization()\n * @returns Token set with access, ID, and optional refresh tokens\n */\n handleCallback(\n callbackUrl: string | URL,\n transaction: AuthorizationTransaction,\n ): Promise<ZuiioTokenSet>;\n\n /**\n * Refresh an expired access token.\n *\n * @param refreshToken - The refresh token from a previous token set\n * @returns New token set\n */\n refresh(refreshToken: string): Promise<ZuiioTokenSet>;\n\n /**\n * Fetch userinfo from the userinfo endpoint.\n *\n * @param accessToken - A valid access token\n * @returns Userinfo claims\n */\n userinfo(accessToken: string): Promise<ZuiioUserinfo>;\n\n /**\n * Build a logout URL that ends the session at Zuiio ID.\n * Redirect the user to this URL to log them out of the identity provider.\n *\n * @param idTokenHint - The ID token (required by OIDC RP-Initiated Logout)\n * @param postLogoutRedirectUri - Where to redirect after logout\n * @returns Full logout URL\n */\n endSessionUrl(\n idTokenHint?: string,\n postLogoutRedirectUri?: string,\n ): string | undefined;\n\n /** The underlying openid-client Configuration (for advanced use). */\n raw: Configuration;\n}\n\n// ─── Factory ────────────────────────────────────────────────────────\n\n/**\n * Create a Zuiio OIDC client by discovering the issuer's metadata.\n *\n * Fetches `/.well-known/openid-configuration` from the issuer to\n * auto-configure endpoints, JWKS, and supported features.\n *\n * @param config - OIDC configuration\n * @returns A configured OIDC client\n *\n * @throws If the issuer is unreachable or the client registration\n * doesn't match the issuer's requirements.\n */\nexport async function createZuiioOidcClient(\n config: ZuiioOidcConfig,\n): Promise<ZuiioOidcClient> {\n const oidc = await discovery(\n new URL(config.issuer),\n config.clientId,\n {\n redirect_uris: [config.redirectUri],\n response_types: [\"code\"],\n token_endpoint_auth_method: config.clientSecret\n ? \"client_secret_basic\"\n : \"none\",\n },\n config.clientSecret ? ClientSecretBasic(config.clientSecret) : None(),\n );\n\n const scopes = config.scopes ?? [\n \"openid\",\n \"profile\",\n \"email\",\n \"offline_access\",\n ];\n\n function toTokenSet(response: TokenEndpointResponse): ZuiioTokenSet {\n return {\n accessToken: response.access_token,\n idToken: response.id_token ?? \"\",\n refreshToken: response.refresh_token,\n expiresAt:\n typeof response.expires_in === \"number\"\n ? Math.floor(Date.now() / 1000) + response.expires_in\n : undefined,\n raw: response,\n };\n }\n\n // ── beginAuthorization ──\n async function beginAuthorization(): Promise<AuthorizationTransaction> {\n const codeVerifier = randomPKCECodeVerifier();\n const codeChallenge = await calculatePKCECodeChallenge(codeVerifier);\n const state = randomState();\n const nonce = randomNonce();\n\n const url = buildAuthorizationUrl(oidc, {\n redirect_uri: config.redirectUri,\n scope: scopes.join(\" \"),\n code_challenge: codeChallenge,\n code_challenge_method: \"S256\",\n state,\n nonce,\n });\n\n return { url: url.href, state, nonce, codeVerifier };\n }\n\n // ── handleCallback ──\n async function handleCallback(\n callbackUrl: string | URL,\n transaction: AuthorizationTransaction,\n ): Promise<ZuiioTokenSet> {\n const url =\n typeof callbackUrl === \"string\" ? new URL(callbackUrl) : callbackUrl;\n\n const response = await authorizationCodeGrant(oidc, url, {\n expectedState: transaction.state,\n expectedNonce: transaction.nonce,\n pkceCodeVerifier: transaction.codeVerifier,\n });\n\n return toTokenSet(response);\n }\n\n // ── refresh ──\n async function refresh(refreshToken: string): Promise<ZuiioTokenSet> {\n return toTokenSet(await refreshTokenGrant(oidc, refreshToken));\n }\n\n // ── userinfo ──\n async function userinfo(accessToken: string): Promise<ZuiioUserinfo> {\n const response: UserInfoResponse = await fetchUserInfo(\n oidc,\n accessToken,\n skipSubjectCheck,\n );\n\n return {\n ...response,\n sub: response.sub,\n email: response.email,\n emailVerified: response.email_verified,\n name: response.name,\n fullName:\n typeof response.full_name === \"string\" ? response.full_name : undefined,\n username:\n typeof response.username === \"string\"\n ? response.username\n : response.preferred_username,\n picture: response.picture,\n updatedAt: response.updated_at,\n };\n }\n\n // ── endSessionUrl ──\n function endSessionUrl(\n idTokenHint?: string,\n postLogoutRedirectUri?: string,\n ): string | undefined {\n if (!oidc.serverMetadata().end_session_endpoint) return undefined;\n\n const parameters: Record<string, string> = {};\n if (idTokenHint) parameters.id_token_hint = idTokenHint;\n if (postLogoutRedirectUri) {\n parameters.post_logout_redirect_uri = postLogoutRedirectUri;\n }\n\n return buildEndSessionUrl(oidc, parameters).href;\n }\n\n return {\n beginAuthorization,\n handleCallback,\n refresh,\n userinfo,\n endSessionUrl,\n raw: oidc,\n };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export { createZuiioOidcClient, type ZuiioOidcConfig, type ZuiioOidcClient, type AuthorizationTransaction, type ZuiioTokenSet, type ZuiioUserinfo, } from "./client.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,wBAAwB,EAC7B,KAAK,aAAa,EAClB,KAAK,aAAa,GACnB,MAAM,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createZuiioOidcClient, } from "./client.js";
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,GAMtB,MAAM,UAAU,CAAC","sourcesContent":["export {\n createZuiioOidcClient,\n type ZuiioOidcConfig,\n type ZuiioOidcClient,\n type AuthorizationTransaction,\n type ZuiioTokenSet,\n type ZuiioUserinfo,\n} from \"./client\";\n"]}
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@zuiio/oidc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "OIDC client for Zuiio ID — discovery, PKCE authorization, token refresh, logout",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "peerDependencies": {
8
+ "openid-client": "^6"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/themuuln/zuiio.git",
13
+ "directory": "packages/oidc"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
22
+ }
23
+ },
24
+ "types": "./dist/index.d.ts",
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "publishConfig": {
28
+ "registry": "https://registry.npmjs.org",
29
+ "access": "public"
30
+ }
31
+ }