@plasgos/oidc-client 0.0.0-stage → 0.1.0-next.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.
@@ -0,0 +1,375 @@
1
+ import { Environment, OidcErrorReason, TokenSet, IdTokenClaims, UserScope, ClientProfile } from '@plasgos/auth-shared';
2
+
3
+ /**
4
+ * The step of the SDK that failed.
5
+ *
6
+ * @example
7
+ * if (event.operation === "refresh" && event.reason === "config_invalid") alertOps(event);
8
+ */
9
+ type OidcOperation = "callback" | "token" | "refresh" | "revocation" | "logout_ticket" | "service_token" | "service_request";
10
+ /**
11
+ * One failure, as the `onFailure` hook receives it. It never holds a token, code, secret, body or
12
+ * query string.
13
+ *
14
+ * @example
15
+ * const onFailure = (event: OidcFailureEvent) => {
16
+ * logger.error(`login failed: ${event.operation} ${event.reason} request_id=${event.requestId ?? "-"}`);
17
+ * };
18
+ */
19
+ interface OidcFailureEvent {
20
+ /** The `environment` of the client that failed. */
21
+ environment: Environment;
22
+ /** The step that failed. */
23
+ operation: OidcOperation;
24
+ /** The same reason an `OidcError` of this failure carries. */
25
+ reason: OidcErrorReason;
26
+ /** HTTP method of the call that failed, or null. */
27
+ method: string | null;
28
+ /** Path of the call that failed, without query string or fragment, or null. */
29
+ path: string | null;
30
+ /** HTTP status of the provider's answer; null when there was none. */
31
+ status: number | null;
32
+ /** `x-request-id` of the provider's answer, or null. */
33
+ requestId: string | null;
34
+ /** The `error` code the provider answered with, or null. */
35
+ providerError: string | null;
36
+ }
37
+
38
+ /**
39
+ * Where the client keeps refreshes in flight. The key is the SHA-256 of the refresh token, never
40
+ * the token itself. Implement it over a shared store to hold the lock across several instances.
41
+ *
42
+ * @example
43
+ * const redisLock: RefreshLockStore = {
44
+ * run: (key, refresh, reuseMs) => runOnceAcrossInstances(redis, key, refresh, reuseMs),
45
+ * };
46
+ * const client = createOidcClient({ ...options, refreshLock: redisLock });
47
+ */
48
+ interface RefreshLockStore {
49
+ /**
50
+ * Runs `refresh` at most once per key among callers sharing this store and gives every caller the same result.
51
+ * A fulfilled result is reused for `reuseMs`; a rejection is not cached.
52
+ */
53
+ run(key: string, refresh: () => Promise<TokenSet>, reuseMs: number): Promise<TokenSet>;
54
+ }
55
+ /**
56
+ * The default lock store: a map in this process, so it only holds within one instance.
57
+ *
58
+ * @example
59
+ * const client = createOidcClient({ ...options, refreshLock: memoryLockStore() });
60
+ */
61
+ declare function memoryLockStore(options?: {
62
+ now?: (() => number) | undefined;
63
+ }): RefreshLockStore;
64
+
65
+ /**
66
+ * One login in progress: what `startLogin` creates, the transaction cookie carries, and
67
+ * `handleCallback` checks the provider's answer against.
68
+ *
69
+ * @example
70
+ * const tx: OidcTransaction = {
71
+ * state, nonce, code_verifier,
72
+ * return_to: "/packages",
73
+ * created_at: Date.now(),
74
+ * };
75
+ */
76
+ interface OidcTransaction {
77
+ /** Random value the callback must return unchanged. */
78
+ state: string;
79
+ /** Random value the ID token must carry. */
80
+ nonce: string;
81
+ /** PKCE verifier, sent with the code exchange. */
82
+ code_verifier: string;
83
+ /** Where the app sends the user after the callback; the app validates it. */
84
+ return_to: string;
85
+ /** Epoch milliseconds. */
86
+ created_at: number;
87
+ /** The login re-authenticates a signed-in user (`prompt=login`). */
88
+ reauth?: boolean | undefined;
89
+ /** The `max_age` sent to the provider, in seconds. */
90
+ max_age?: number | undefined;
91
+ }
92
+ /**
93
+ * The `fetch` the SDK calls: always with a string URL and a `RequestInit`.
94
+ *
95
+ * @example
96
+ * const tracedFetch: OidcFetch = (input, init) => fetch(input, { ...init, headers: withTraceId(init.headers) });
97
+ * const client = createOidcClient({ ...options, fetch: tracedFetch });
98
+ */
99
+ type OidcFetch = (input: string, init: RequestInit) => Promise<Response>;
100
+ /**
101
+ * Options of `createOidcClient`. Values usually come from `process.env`; every problem is reported
102
+ * at once in one `ConfigError`, by field name and never by value.
103
+ *
104
+ * @example
105
+ * const options: OidcClientOptions = {
106
+ * environment: "production",
107
+ * issuer: "https://accounts.plasgos.co.id",
108
+ * backchannelUrl: process.env.PLASGOS_BACKCHANNEL_URL,
109
+ * clientId: process.env.PLASGOS_LOGIN_CLIENT_ID ?? "",
110
+ * clientSecret: process.env.PLASGOS_LOGIN_CLIENT_SECRET ?? "",
111
+ * redirectUri: "https://kirim.plasgos.co.id/auth/callback",
112
+ * scopes: ["openid", "profile", "email", "packages:read", "packages:write"],
113
+ * profile: "first-party",
114
+ * resource: "https://api.plasgos.co.id/packages",
115
+ * };
116
+ */
117
+ interface OidcClientOptions {
118
+ /** `"sandbox"` or `"production"`; checked against `issuer`, `resource` and `backchannelUrl`. */
119
+ environment: Environment;
120
+ /** Bare origin of the provider: browser URLs and the exact `iss` value. */
121
+ issuer: string;
122
+ /** Internal api-main origin for the token, revocation and logout-ticket calls; `http:` allowed. Default: `issuer`. */
123
+ backchannelUrl?: string | undefined;
124
+ /** Client id of the interactive (login) client. */
125
+ clientId: string;
126
+ /** Sent only as `client_secret_basic`. */
127
+ clientSecret: string;
128
+ /** Registered callback URL, exact. `https:` unless `allowInsecureHttp`. */
129
+ redirectUri: string;
130
+ /** Registered post-logout URL, same scheme rule. */
131
+ postLogoutRedirectUri?: string | undefined;
132
+ /** Must include `"openid"`. */
133
+ scopes: readonly UserScope[];
134
+ /** `"first-party"`: an app of Plasgos itself. `"third-party"`: any other app. */
135
+ profile: ClientProfile;
136
+ /** Resource indicator (audience); required by `account:*` / `packages:*`, refused for `"third-party"`. */
137
+ resource?: string | undefined;
138
+ /**
139
+ * Mint a logout ticket at logout. Default: `true` for first-party with `endSession: "redirect"`
140
+ * and a `backchannelUrl`, otherwise `false`. An explicit `true` requires `backchannelUrl`.
141
+ */
142
+ logoutTicket?: boolean | undefined;
143
+ /** `"redirect"` (default, a GET URL) or `"form-post"` (only for an app on the issuer's own origin). */
144
+ endSession?: "redirect" | "form-post" | undefined;
145
+ /** ID token claims returned in `claims.extra`, for example `["plasgos_public_id"]`. */
146
+ extraClaims?: readonly string[] | undefined;
147
+ /** Sandbox only: `http:` for the issuer, redirect and post-logout URLs. */
148
+ allowInsecureHttp?: boolean | undefined;
149
+ /** Per call, body read included: integers from 1 to 60000. Defaults 10000 and 3000. */
150
+ timeouts?: {
151
+ tokenMs?: number | undefined;
152
+ logoutMs?: number | undefined;
153
+ } | undefined;
154
+ /** Default: the global `fetch`. */
155
+ fetch?: OidcFetch | undefined;
156
+ /** Single-flight store for refresh. Default: one `memoryLockStore()` per client. */
157
+ refreshLock?: RefreshLockStore | undefined;
158
+ /** Called once per failure, thrown or swallowed. Exceptions it throws are swallowed. */
159
+ onFailure?: ((event: OidcFailureEvent) => void) | undefined;
160
+ }
161
+ /**
162
+ * Input of `client.startLogin`.
163
+ *
164
+ * @example
165
+ * client.startLogin({ returnTo: "/orders", prompt: "login", maxAge: 0, reauth: true });
166
+ */
167
+ interface StartLoginInput {
168
+ /** Already sanitised by the app: starts with one "/", at most 512 chars. */
169
+ returnTo: string;
170
+ /** OIDC `prompt`: `"login"` forces a new login. */
171
+ prompt?: "login" | "consent" | "none" | undefined;
172
+ /** Seconds; OIDC max_age. */
173
+ maxAge?: number | undefined;
174
+ /** OIDC `login_hint`, at most 512 characters. */
175
+ loginHint?: string | undefined;
176
+ /** Marks a step-up login; returned by handleCallback for the app's subject check. */
177
+ reauth?: boolean | undefined;
178
+ /** Epoch ms, for tests. */
179
+ now?: number | undefined;
180
+ }
181
+ /**
182
+ * Where to send the browser, and the transaction to seal into the transaction cookie.
183
+ *
184
+ * @example
185
+ * const { location, transaction } = client.startLogin({ returnTo: "/" });
186
+ * headers.append("Set-Cookie", store.commitTransaction(transaction));
187
+ * headers.set("Location", location);
188
+ * return new Response(null, { status: 302, headers });
189
+ */
190
+ interface StartLoginResult {
191
+ /** The authorization URL on the issuer to redirect the browser to. */
192
+ location: string;
193
+ /** To be sealed with `store.commitTransaction` and read back at the callback. */
194
+ transaction: OidcTransaction;
195
+ }
196
+ /**
197
+ * The checked ID token claims, plus the claims named in `extraClaims` (prototype-free, frozen).
198
+ *
199
+ * @example
200
+ * // createOidcClient({ ...options, extraClaims: ["plasgos_public_id"] })
201
+ * const { claims } = await client.handleCallback(request.url, transaction);
202
+ * const publicId = claims.extra["plasgos_public_id"];
203
+ */
204
+ type VerifiedIdTokenClaims = IdTokenClaims & {
205
+ extra: Readonly<Record<string, string | number | boolean>>;
206
+ };
207
+ /**
208
+ * Options of `client.handleCallback`.
209
+ *
210
+ * @example
211
+ * await client.handleCallback(callbackUrl, transaction, { now: Date.UTC(2026, 0, 1) });
212
+ */
213
+ interface HandleCallbackOptions {
214
+ /** Epoch ms, for tests. */
215
+ now?: number | undefined;
216
+ }
217
+ /**
218
+ * What `client.handleCallback` returns: the token set, the checked ID token claims, and the
219
+ * transaction the login started with (`return_to`, `reauth`).
220
+ *
221
+ * @example
222
+ * const { tokens, claims, transaction } = await client.handleCallback(request.url, store.readTransaction(request));
223
+ * const expiresAt = accessTokenExpiry(tokens, Date.now());
224
+ * return redirect(transaction.return_to);
225
+ */
226
+ interface CallbackResult {
227
+ /** The token set of the code exchange. */
228
+ tokens: TokenSet;
229
+ /** The checked ID token claims. */
230
+ claims: VerifiedIdTokenClaims;
231
+ /** The transaction the login started with. */
232
+ transaction: OidcTransaction;
233
+ }
234
+ /**
235
+ * The part of a stored session `client.ensureFresh` reads and renews. Any object with these fields
236
+ * fits, for example the `AuthState` of `@plasgos/oidc-client/session`.
237
+ *
238
+ * @example
239
+ * const auth: RefreshableAuth = { access_token, refresh_token, expires_at: accessTokenExpiry(tokens, Date.now()) };
240
+ * const fresh = await client.ensureFresh(auth);
241
+ */
242
+ interface RefreshableAuth {
243
+ /** The current access token. */
244
+ access_token: string;
245
+ /** Absent for a client without refresh tokens; then nothing can be renewed. */
246
+ refresh_token?: string | undefined;
247
+ /** Epoch seconds at which the access token expires. */
248
+ expires_at: number;
249
+ }
250
+ /**
251
+ * Options of `client.ensureFresh`.
252
+ *
253
+ * @example
254
+ * // The API answered 401 invalid_token: refresh once, whatever the expiry says.
255
+ * const { auth } = await client.ensureFresh(session.data.auth, { force: true });
256
+ */
257
+ interface EnsureFreshOptions {
258
+ /** Refresh when the access token expires within this many seconds. Default 60. */
259
+ skewSeconds?: number | undefined;
260
+ /** Refresh even if the token looks valid (the API answered 401 invalid_token). Default false. */
261
+ force?: boolean | undefined;
262
+ /** Epoch ms, for tests. */
263
+ now?: number | undefined;
264
+ }
265
+ /**
266
+ * What `client.ensureFresh` returns: the auth to use, and whether it has to be stored again.
267
+ *
268
+ * @example
269
+ * const { auth, changed } = await client.ensureFresh(current);
270
+ * if (changed) session.update({ auth });
271
+ */
272
+ interface EnsureFreshResult<A> {
273
+ /** The input object itself when `changed` is false, a renewed copy otherwise. */
274
+ auth: A;
275
+ /** True when `auth` was renewed and must be stored again. */
276
+ changed: boolean;
277
+ }
278
+ /**
279
+ * Input of `client.logout`: what the session being ended still holds.
280
+ *
281
+ * @example
282
+ * await client.logout({
283
+ * refreshToken: auth?.refresh_token,
284
+ * idToken: auth?.id_token,
285
+ * browser: { clientIp: null, userAgent: request.headers.get("User-Agent") },
286
+ * });
287
+ */
288
+ interface LogoutInput {
289
+ /** Revoked at the provider when given. */
290
+ refreshToken?: string | undefined;
291
+ /** Swapped for a one-time logout ticket, or sent as `id_token_hint` in `"form-post"` mode. */
292
+ idToken?: string | undefined;
293
+ /** The browser's address and agent, forwarded as X-Client-Ip / X-Client-User-Agent when not null. */
294
+ browser?: {
295
+ clientIp: string | null;
296
+ userAgent: string | null;
297
+ } | undefined;
298
+ }
299
+ /**
300
+ * Where `client.logout` sends the browser. `redirect`: a GET URL without any token; `ticket` tells
301
+ * whether the provider will end its session without asking. `form`: the fields of a POST form to
302
+ * `action`, for an app on the issuer's own origin (`endSession: "form-post"`).
303
+ *
304
+ * @example
305
+ * const result = await client.logout({ refreshToken, idToken });
306
+ * if (result.kind === "redirect") return new Response(null, { status: 303, headers: { Location: result.location } });
307
+ * return renderAutoSubmitForm(result.action, result.fields);
308
+ */
309
+ type LogoutResult = {
310
+ kind: "redirect";
311
+ location: string;
312
+ ticket: boolean;
313
+ } | {
314
+ kind: "form";
315
+ action: string;
316
+ fields: Readonly<Record<string, string>>;
317
+ };
318
+ /**
319
+ * What `createOidcClient` returns.
320
+ *
321
+ * @example
322
+ * const { location, transaction } = client.startLogin({ returnTo: "/packages" });
323
+ * headers.append("Set-Cookie", store.commitTransaction(transaction));
324
+ * headers.set("Location", location);
325
+ * return new Response(null, { status: 302, headers });
326
+ */
327
+ interface OidcClient {
328
+ /** The `environment` the client was created with. */
329
+ readonly environment: Environment;
330
+ /** The validated issuer (canonical origin). */
331
+ readonly issuer: string;
332
+ /** The client id the client was created with. */
333
+ readonly clientId: string;
334
+ /** Builds the authorization URL (code + PKCE S256) and its transaction. Throws `TypeError` on a bad input. */
335
+ startLogin(input: StartLoginInput): StartLoginResult;
336
+ /**
337
+ * Checks the callback URL against the transaction, exchanges the code and checks the ID token.
338
+ * Rejects with an `OidcError`; the app clears the transaction cookie on every path.
339
+ *
340
+ * @example
341
+ * const { tokens, claims, transaction } = await client.handleCallback(request.url, store.readTransaction(request));
342
+ */
343
+ handleCallback(url: URL | string, transaction: OidcTransaction | null, options?: HandleCallbackOptions): Promise<CallbackResult>;
344
+ /**
345
+ * One rotated refresh. Calls with the same refresh token share one request (and its result for
346
+ * 30 s) through the client's `refreshLock`. Rejects with an `OidcError`: `invalid_grant` and
347
+ * `invalid_target` mean the session is over.
348
+ *
349
+ * @example
350
+ * const tokens = await client.refresh(auth.refresh_token);
351
+ */
352
+ refresh(refreshToken: string): Promise<TokenSet>;
353
+ /**
354
+ * Renews `auth` when its access token is about to expire. Never changes `auth` itself. A refresh
355
+ * that fails while the access token still works keeps the current auth (`changed: false`), except
356
+ * for `invalid_grant` and `invalid_target`, which always reject: the app then clears the session.
357
+ *
358
+ * @example
359
+ * const { auth, changed } = await client.ensureFresh(session.data.auth);
360
+ * if (changed) session.update({ auth });
361
+ */
362
+ ensureFresh<A extends RefreshableAuth>(auth: A, options?: EnsureFreshOptions): Promise<EnsureFreshResult<A>>;
363
+ /**
364
+ * Revokes the refresh token and builds the provider's end-session step. Never rejects: a failed
365
+ * back-channel call is one `onFailure` event. The app clears its session cookies itself.
366
+ *
367
+ * @example
368
+ * const result = await client.logout({ refreshToken: auth?.refresh_token, idToken: auth?.id_token });
369
+ * if (result.kind === "redirect") return redirect(result.location, { status: 303, headers });
370
+ */
371
+ logout(input: LogoutInput): Promise<LogoutResult>;
372
+ }
373
+
374
+ export { memoryLockStore as m };
375
+ export type { CallbackResult as C, EnsureFreshOptions as E, HandleCallbackOptions as H, LogoutInput as L, OidcClientOptions as O, RefreshLockStore as R, StartLoginInput as S, VerifiedIdTokenClaims as V, OidcClient as a, EnsureFreshResult as b, LogoutResult as c, OidcFailureEvent as d, OidcFetch as e, OidcOperation as f, OidcTransaction as g, RefreshableAuth as h, StartLoginResult as i };
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@plasgos/oidc-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-next.1",
4
+ "description": "Plasgos OIDC client for Node servers: user login (code + PKCE), sealed session cookies and client_credentials.",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=22.22"
8
+ },
9
+ "sideEffects": false,
10
+ "license": "SEE LICENSE IN LICENSE",
11
+ "author": "Plasgos",
12
+ "homepage": "https://github.com/plasgos/plasgos-auth-sdk/tree/main/packages/oidc-client#readme",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/plasgos/plasgos-auth-sdk.git",
16
+ "directory": "packages/oidc-client"
17
+ },
18
+ "publishConfig": {
19
+ "access": "public",
20
+ "registry": "https://registry.npmjs.org"
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "CHANGELOG.md",
26
+ "LICENSE"
27
+ ],
28
+ "exports": {
29
+ ".": {
30
+ "import": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "require": {
35
+ "types": "./dist/index.d.cts",
36
+ "default": "./dist/index.cjs"
37
+ }
38
+ },
39
+ "./session": {
40
+ "import": {
41
+ "types": "./dist/session.d.ts",
42
+ "default": "./dist/session.js"
43
+ },
44
+ "require": {
45
+ "types": "./dist/session.d.cts",
46
+ "default": "./dist/session.cjs"
47
+ }
48
+ },
49
+ "./service": {
50
+ "import": {
51
+ "types": "./dist/service.d.ts",
52
+ "default": "./dist/service.js"
53
+ },
54
+ "require": {
55
+ "types": "./dist/service.d.cts",
56
+ "default": "./dist/service.cjs"
57
+ }
58
+ },
59
+ "./package.json": "./package.json"
60
+ },
61
+ "main": "./dist/index.cjs",
62
+ "types": "./dist/index.d.cts",
63
+ "dependencies": {
64
+ "@plasgos/auth-shared": "0.1.0-next.1"
65
+ },
66
+ "scripts": {
67
+ "build": "tsup"
68
+ }
6
69
  }