@manta-eu/auth 0.1.8 → 0.1.10

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.
Files changed (58) hide show
  1. package/README.md +67 -4
  2. package/dist/auth-commands.js +1 -0
  3. package/dist/auth-commands.js.map +1 -0
  4. package/dist/browser-login.js +1 -0
  5. package/dist/browser-login.js.map +1 -0
  6. package/dist/browser.js +1 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/credential-store.js +1 -0
  9. package/dist/credential-store.js.map +1 -0
  10. package/dist/default-deployment.d.ts +8 -0
  11. package/dist/default-deployment.d.ts.map +1 -1
  12. package/dist/default-deployment.js +7 -0
  13. package/dist/default-deployment.js.map +1 -0
  14. package/dist/device-login.js +1 -0
  15. package/dist/device-login.js.map +1 -0
  16. package/dist/http.js +1 -0
  17. package/dist/http.js.map +1 -0
  18. package/dist/index.d.ts +3 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/oidc.d.ts +15 -0
  23. package/dist/oidc.d.ts.map +1 -0
  24. package/dist/oidc.js +27 -0
  25. package/dist/oidc.js.map +1 -0
  26. package/dist/stored-login.js +1 -0
  27. package/dist/stored-login.js.map +1 -0
  28. package/dist/token.d.ts +3 -4
  29. package/dist/token.d.ts.map +1 -1
  30. package/dist/token.js +32 -10
  31. package/dist/token.js.map +1 -0
  32. package/dist/web-login.d.ts +40 -0
  33. package/dist/web-login.d.ts.map +1 -0
  34. package/dist/web-login.js +82 -0
  35. package/dist/web-login.js.map +1 -0
  36. package/dist/web-routes.d.ts +42 -0
  37. package/dist/web-routes.d.ts.map +1 -0
  38. package/dist/web-routes.js +248 -0
  39. package/dist/web-routes.js.map +1 -0
  40. package/dist/web.d.ts +8 -0
  41. package/dist/web.d.ts.map +1 -0
  42. package/dist/web.js +7 -0
  43. package/dist/web.js.map +1 -0
  44. package/package.json +14 -3
  45. package/src/auth-commands.ts +239 -0
  46. package/src/browser-login.ts +203 -0
  47. package/src/browser.ts +32 -0
  48. package/src/credential-store.ts +225 -0
  49. package/src/default-deployment.ts +15 -0
  50. package/src/device-login.ts +181 -0
  51. package/src/http.ts +47 -0
  52. package/src/index.ts +60 -0
  53. package/src/oidc.ts +40 -0
  54. package/src/stored-login.ts +63 -0
  55. package/src/token.ts +151 -0
  56. package/src/web-login.ts +106 -0
  57. package/src/web-routes.ts +321 -0
  58. package/src/web.ts +25 -0
package/src/http.ts ADDED
@@ -0,0 +1,47 @@
1
+ export type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
2
+
3
+ export function formRequest(fields: Record<string, string>): RequestInit {
4
+ return {
5
+ method: "POST",
6
+ headers: { "content-type": "application/x-www-form-urlencoded" },
7
+ body: new URLSearchParams(fields).toString(),
8
+ };
9
+ }
10
+
11
+ export class RefusedRequestError extends Error {
12
+ constructor(
13
+ message: string,
14
+ readonly status: number,
15
+ ) {
16
+ super(message);
17
+ }
18
+ }
19
+
20
+ // Overload and timeout, which are worth repeating; every other refusal is the server's final word.
21
+ export function isTransientStatus(status: number): boolean {
22
+ return status >= 500 || status === 429 || status === 408;
23
+ }
24
+
25
+ export async function readJson<T>(response: Response, endpoint: string): Promise<T> {
26
+ const body = await response.text();
27
+
28
+ try {
29
+ return JSON.parse(body) as T;
30
+ } catch {
31
+ throw new Error(`${endpoint} answered status ${response.status} with text, not JSON: ${body}`);
32
+ }
33
+ }
34
+
35
+ export async function postTo(endpoint: string, init: RequestInit, fetchImpl: FetchLike = fetch): Promise<Response> {
36
+ try {
37
+ return await fetchImpl(endpoint, init);
38
+ } catch (cause) {
39
+ throw new Error(`cannot reach ${endpoint}.`, { cause });
40
+ }
41
+ }
42
+
43
+ export function describeError(error: unknown): string {
44
+ if (!(error instanceof Error)) return String(error);
45
+
46
+ return error.cause instanceof Error ? `${error.message}\n caused by: ${error.cause.message}` : error.message;
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,60 @@
1
+ export {
2
+ ciClientId,
3
+ cliClientId,
4
+ clientIdHelp,
5
+ interactiveLogin,
6
+ logIn,
7
+ loginStatus,
8
+ logOut,
9
+ publicClientFrom,
10
+ registerAuthCommands,
11
+ revokeRefreshToken,
12
+ userTokenSource,
13
+ type ClientOptions,
14
+ type LoginOptions,
15
+ } from "./auth-commands.js";
16
+ export { browserLogin, loginScope } from "./browser-login.js";
17
+ export {
18
+ defaultCredentialStore,
19
+ fileCredentialStore,
20
+ keychainCredentialStore,
21
+ keychainWithFileFallback,
22
+ type CredentialStore,
23
+ type RunSecurity,
24
+ type SecurityResult,
25
+ type StoredLogin,
26
+ } from "./credential-store.js";
27
+ export { defaultDeployment } from "./default-deployment.js";
28
+ export {
29
+ pollForDeviceTokens,
30
+ refreshAccessToken,
31
+ startDeviceLogin,
32
+ type DeviceLogin,
33
+ type DeviceTokens,
34
+ type PkcePair,
35
+ type PublicClient,
36
+ type Sleep,
37
+ } from "./device-login.js";
38
+ export { describeError, isTransientStatus, postTo, readJson, RefusedRequestError, type FetchLike } from "./http.js";
39
+ export { saveLogin, storedLoginTokenSource } from "./stored-login.js";
40
+ export {
41
+ cachedToken,
42
+ mintWithClientCredentials,
43
+ withRenewal,
44
+ type ClientCredentials,
45
+ type RenewableTokenSource,
46
+ type TokenSource,
47
+ } from "./token.js";
48
+ export { discoveryUrl, issuerUrl, type OidcClient, type Realm } from "./oidc.js";
49
+ export {
50
+ endWebLogin,
51
+ finishWebLogin,
52
+ refreshWebLogin,
53
+ startWebLogin,
54
+ webLogoutUrl,
55
+ type StartWebLoginOptions,
56
+ type WebLoginStart,
57
+ type WebLogoutOptions,
58
+ type WebTokens,
59
+ } from "./web-login.js";
60
+ export { webLoginRoutes, type WebLoginRoutes, type WebLoginRoutesOptions, type WebSession } from "./web-routes.js";
package/src/oidc.ts ADDED
@@ -0,0 +1,40 @@
1
+ import * as oidc from "openid-client";
2
+ import { type Realm, realmOrDefault } from "./default-deployment.js";
3
+ import type { PublicClient } from "./device-login.js";
4
+ import type { FetchLike } from "./http.js";
5
+
6
+ export type { Realm };
7
+
8
+ /** A client with a secret is an app's own server; without one it is a public client, like the CLIs. */
9
+ export type OidcClient = Omit<PublicClient, "baseUrl" | "realm"> & Realm & { clientSecret?: string };
10
+
11
+ /** The realm's issuer, the `iss` of every token it signs. */
12
+ export function issuerUrl(target?: Realm): string {
13
+ const { baseUrl, realm } = realmOrDefault(target);
14
+ return `${baseUrl}/realms/${realm}`;
15
+ }
16
+
17
+ /** The OpenID Connect discovery document most libraries configure themselves from. */
18
+ export function discoveryUrl(target?: Realm): string {
19
+ return `${issuerUrl(target)}/.well-known/openid-configuration`;
20
+ }
21
+
22
+ // Keycloak's endpoints are fixed under the issuer, so no discovery request precedes each call.
23
+ export function oidcConfiguration(client: OidcClient, fetchImpl?: FetchLike): oidc.Configuration {
24
+ const issuer = issuerUrl(client);
25
+ const endpoint = (name: string) => `${issuer}/protocol/openid-connect/${name}`;
26
+ const config = new oidc.Configuration(
27
+ {
28
+ issuer,
29
+ authorization_endpoint: endpoint("auth"),
30
+ token_endpoint: endpoint("token"),
31
+ end_session_endpoint: endpoint("logout"),
32
+ revocation_endpoint: endpoint("revoke"),
33
+ },
34
+ client.clientId,
35
+ undefined,
36
+ client.clientSecret ? oidc.ClientSecretPost(client.clientSecret) : oidc.None(),
37
+ );
38
+ if (fetchImpl) config[oidc.customFetch] = (url, options) => fetchImpl(url, options as RequestInit);
39
+ return config;
40
+ }
@@ -0,0 +1,63 @@
1
+ import type { CredentialStore } from "./credential-store.js";
2
+ import { type DeviceTokens, type PublicClient, refreshAccessToken } from "./device-login.js";
3
+ import { describeError, type FetchLike } from "./http.js";
4
+ import { accessTokenUsername, cachedToken, type RenewableTokenSource } from "./token.js";
5
+
6
+ // Keycloak may rotate the refresh token on every renewal, so each new one replaces the stored one.
7
+ export async function saveLogin(store: CredentialStore, client: PublicClient, tokens: DeviceTokens): Promise<boolean> {
8
+ if (!tokens.refreshToken) return false;
9
+
10
+ const username = accessTokenUsername(tokens.accessToken);
11
+
12
+ await store.write(client, { refreshToken: tokens.refreshToken, ...(username ? { username } : {}) });
13
+
14
+ return true;
15
+ }
16
+
17
+ // Renews from the stored login, and only asks for a new one when Keycloak refuses it; a network error keeps it.
18
+ export function storedLoginTokenSource({
19
+ client,
20
+ store,
21
+ login,
22
+ warn = console.error,
23
+ fetchImpl = fetch,
24
+ clock = Date.now,
25
+ }: {
26
+ client: PublicClient;
27
+ store: CredentialStore;
28
+ login: () => Promise<DeviceTokens>;
29
+ warn?: (message: string) => void;
30
+ fetchImpl?: FetchLike;
31
+ clock?: () => number;
32
+ }): RenewableTokenSource {
33
+ // A store it cannot write, e.g. a read-only $HOME, costs the next run a login instead of failing this one.
34
+ async function keep(tokens: DeviceTokens): Promise<void> {
35
+ await saveLogin(store, client, tokens).catch((error: unknown) =>
36
+ warn(`could not store the login, so the next run may ask for another: ${describeError(error)}`),
37
+ );
38
+ }
39
+
40
+ async function renewOrLogIn(): Promise<string> {
41
+ const stored = await store.read(client);
42
+
43
+ if (stored) {
44
+ const renewed = await refreshAccessToken(client, stored.refreshToken, fetchImpl);
45
+
46
+ if (renewed) {
47
+ await keep(renewed);
48
+ return renewed.accessToken;
49
+ }
50
+
51
+ await store
52
+ .remove(client)
53
+ .catch((error: unknown) => warn(`could not delete the refused login: ${describeError(error)}`));
54
+ }
55
+
56
+ const tokens = await login();
57
+ await keep(tokens);
58
+
59
+ return tokens.accessToken;
60
+ }
61
+
62
+ return cachedToken(renewOrLogIn, clock);
63
+ }
package/src/token.ts ADDED
@@ -0,0 +1,151 @@
1
+ import { type Realm, realmOrDefault } from "./default-deployment.js";
2
+ import { type FetchLike, formRequest, postTo, RefusedRequestError } from "./http.js";
3
+
4
+ export type ClientCredentials = Realm & {
5
+ clientId: string;
6
+ clientSecret: string;
7
+ scope?: string;
8
+ };
9
+
10
+ export type TokenSource = () => Promise<string>;
11
+
12
+ // A source that can drop its cached token, so a request the API rejected is retried with a fresh one.
13
+ export type RenewableTokenSource = TokenSource & { renew: (rejected?: string) => void };
14
+
15
+ function isRenewable(token: TokenSource): token is RenewableTokenSource {
16
+ return typeof (token as Partial<RenewableTokenSource>).renew === "function";
17
+ }
18
+
19
+ // A token revoked or expired early answers 401 once; renewing and retrying once is what Claude Code does for MCP.
20
+ export async function withRenewal<T>(token: TokenSource, call: (accessToken: string) => Promise<T>): Promise<T> {
21
+ let accessToken: string | undefined;
22
+ try {
23
+ accessToken = await token();
24
+ return await call(accessToken);
25
+ } catch (error) {
26
+ if (!(error instanceof RefusedRequestError && error.status === 401) || !isRenewable(token)) throw error;
27
+
28
+ token.renew(accessToken);
29
+
30
+ return call(await token());
31
+ }
32
+ }
33
+
34
+ // Re-mint before Keycloak's own exp, so an in-flight request never races an expired token.
35
+ export const tokenExpiryBufferMs = 60_000;
36
+
37
+ // The exp claim did not parse, so the token gets a short life rather than none.
38
+ export const unparsableTokenTtlMs = 30_000;
39
+
40
+ export function tokenEndpoint(baseUrl: string, realm: string): string {
41
+ return `${baseUrl}/realms/${realm}/protocol/openid-connect/token`;
42
+ }
43
+
44
+ // atob and TextDecoder, not Buffer, so the token helpers also run in a browser.
45
+ function decodeBase64Url(value: string): string {
46
+ const base64 = value
47
+ .replace(/-/g, "+")
48
+ .replace(/_/g, "/")
49
+ .padEnd(Math.ceil(value.length / 4) * 4, "=");
50
+ return new TextDecoder().decode(Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)));
51
+ }
52
+
53
+ // Reads the claims without checking the signature: callers only use them to schedule and to label.
54
+ function unverifiedClaims(accessToken: string): Record<string, unknown> {
55
+ const payload = accessToken.split(".")[1];
56
+
57
+ if (!payload) return {};
58
+
59
+ try {
60
+ const claims: unknown = JSON.parse(decodeBase64Url(payload));
61
+
62
+ return typeof claims === "object" && claims !== null ? (claims as Record<string, unknown>) : {};
63
+ } catch {
64
+ return {};
65
+ }
66
+ }
67
+
68
+ export function accessTokenExpiresAt(accessToken: string, now: number): number {
69
+ const exp = unverifiedClaims(accessToken).exp;
70
+
71
+ return typeof exp === "number" ? exp * 1000 - tokenExpiryBufferMs : now + unparsableTokenTtlMs;
72
+ }
73
+
74
+ export function accessTokenUsername(accessToken: string): string | undefined {
75
+ const claims = unverifiedClaims(accessToken);
76
+ const name = claims.preferred_username ?? claims.email;
77
+
78
+ return typeof name === "string" ? name : undefined;
79
+ }
80
+
81
+ export function isFresh(expiresAt: number, now: number): boolean {
82
+ return expiresAt > now;
83
+ }
84
+
85
+ function clientCredentialsRequest({ clientId, clientSecret, scope }: ClientCredentials): RequestInit {
86
+ return formRequest({
87
+ grant_type: "client_credentials",
88
+ client_id: clientId,
89
+ client_secret: clientSecret,
90
+ ...(scope ? { scope } : {}),
91
+ });
92
+ }
93
+
94
+ function readAccessToken(body: unknown, realm: string): string {
95
+ const accessToken = (body as { access_token?: unknown }).access_token;
96
+
97
+ if (typeof accessToken !== "string") {
98
+ throw new Error(`the Keycloak response for realm ${realm} carries no access_token.`);
99
+ }
100
+
101
+ return accessToken;
102
+ }
103
+
104
+ export async function mintWithClientCredentials(
105
+ credentials: ClientCredentials,
106
+ fetchImpl: FetchLike = fetch,
107
+ ): Promise<string> {
108
+ const { baseUrl, realm } = realmOrDefault(credentials);
109
+ const endpoint = tokenEndpoint(baseUrl, realm);
110
+ const response = await postTo(endpoint, clientCredentialsRequest(credentials), fetchImpl);
111
+
112
+ if (!response.ok) {
113
+ throw new Error(
114
+ `Keycloak refused the client credentials for realm ${realm} with status ${response.status}. ` +
115
+ `Check the client id and the secret against ${endpoint}.`,
116
+ );
117
+ }
118
+
119
+ return readAccessToken(await response.json(), realm);
120
+ }
121
+
122
+ export function cachedToken(mint: TokenSource, clock: () => number = Date.now): RenewableTokenSource {
123
+ let held: { token: string; expiresAt: number } | undefined;
124
+ // Shared, so callers racing an expired token start one mint: parallel refreshes would spend one refresh token.
125
+ let minting: Promise<string> | undefined;
126
+
127
+ const mintOnce = async () => {
128
+ const token = await mint();
129
+ // A device login blocks until the browser answers, so `now` is already stale here.
130
+ held = { token, expiresAt: accessTokenExpiresAt(token, clock()) };
131
+
132
+ return token;
133
+ };
134
+
135
+ const source = async () => {
136
+ if (held && isFresh(held.expiresAt, clock())) return held.token;
137
+
138
+ const current = (minting ??= mintOnce().finally(() => {
139
+ if (minting === current) minting = undefined;
140
+ }));
141
+
142
+ return current;
143
+ };
144
+
145
+ return Object.assign(source, {
146
+ // Keeps an in-flight mint, so racing 401s join it, and a newer token than the one refused.
147
+ renew: (rejected?: string) => {
148
+ if (rejected === undefined || held?.token === rejected) held = undefined;
149
+ },
150
+ });
151
+ }
@@ -0,0 +1,106 @@
1
+ import * as oidc from "openid-client";
2
+ import { isTransientStatus, type FetchLike } from "./http.js";
3
+ import { type OidcClient, oidcConfiguration } from "./oidc.js";
4
+
5
+ export type WebLoginStart = { url: string; state: string; verifier: string };
6
+
7
+ export type WebTokens = { accessToken: string; refreshToken?: string; idToken?: string };
8
+
9
+ export type StartWebLoginOptions = {
10
+ redirectUri: string;
11
+ offlineAccess?: boolean;
12
+ scope?: string;
13
+ idpHint?: string;
14
+ };
15
+
16
+ export type WebLogoutOptions = { idToken?: string; postLogoutRedirectUri?: string; state?: string };
17
+
18
+ function tokensOf(response: oidc.TokenEndpointResponse): WebTokens {
19
+ return {
20
+ accessToken: response.access_token,
21
+ ...(response.refresh_token ? { refreshToken: response.refresh_token } : {}),
22
+ ...(response.id_token ? { idToken: response.id_token } : {}),
23
+ };
24
+ }
25
+
26
+ function statusOf(error: unknown): number | undefined {
27
+ if (error instanceof oidc.ResponseBodyError) return error.status;
28
+ const cause = error instanceof Error ? error.cause : undefined;
29
+ return cause instanceof Response ? cause.status : undefined;
30
+ }
31
+
32
+ /** Starts a sign-in; keep `state` and `verifier` in the person's session for the callback. */
33
+ export async function startWebLogin(client: OidcClient, options: StartWebLoginOptions): Promise<WebLoginStart> {
34
+ const { redirectUri, offlineAccess = false, idpHint } = options;
35
+ const verifier = oidc.randomPKCECodeVerifier();
36
+ const state = oidc.randomState();
37
+ const url = oidc.buildAuthorizationUrl(oidcConfiguration(client), {
38
+ redirect_uri: redirectUri,
39
+ scope: options.scope ?? (offlineAccess ? "openid offline_access" : "openid"),
40
+ state,
41
+ code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
42
+ code_challenge_method: "S256",
43
+ ...(idpHint ? { kc_idp_hint: idpHint } : {}),
44
+ });
45
+
46
+ return { url: url.toString(), state, verifier };
47
+ }
48
+
49
+ /** Trades the callback for tokens; pass `callbackUrl` and `state` to have them checked too. */
50
+ export async function finishWebLogin(
51
+ client: OidcClient,
52
+ login: { code: string; redirectUri: string; verifier: string; callbackUrl?: string; state?: string },
53
+ fetchImpl?: FetchLike,
54
+ ): Promise<WebTokens> {
55
+ const { code, redirectUri, verifier, callbackUrl, state } = login;
56
+ // The library sends the callback URL without its query as redirect_uri, so the registered one carries the answer.
57
+ const currentUrl = new URL(redirectUri);
58
+ currentUrl.search =
59
+ callbackUrl === undefined ? new URLSearchParams({ code }).toString() : new URL(callbackUrl).search;
60
+ const response = await oidc.authorizationCodeGrant(oidcConfiguration(client, fetchImpl), currentUrl, {
61
+ pkceCodeVerifier: verifier,
62
+ expectedState: state ?? oidc.skipStateCheck,
63
+ });
64
+ return tokensOf(response);
65
+ }
66
+
67
+ /** Renews the access token; store the rotated refresh token it returns. `undefined` means sign in again. */
68
+ export async function refreshWebLogin(
69
+ client: OidcClient,
70
+ refreshToken: string,
71
+ fetchImpl?: FetchLike,
72
+ ): Promise<WebTokens | undefined> {
73
+ try {
74
+ const renewed = tokensOf(await oidc.refreshTokenGrant(oidcConfiguration(client, fetchImpl), refreshToken));
75
+ return { ...renewed, refreshToken: renewed.refreshToken ?? refreshToken };
76
+ } catch (error) {
77
+ const status = statusOf(error);
78
+ // A refused refresh token is terminal and earns a new login; an overloaded Keycloak must not cost one.
79
+ if (status === undefined || isTransientStatus(status)) throw error;
80
+ return undefined;
81
+ }
82
+ }
83
+
84
+ /** Where to send the browser to sign out of Manta too; pass the latest `idToken` to skip Keycloak's prompt. */
85
+ export function webLogoutUrl(client: OidcClient, options: WebLogoutOptions = {}): string {
86
+ const { idToken, postLogoutRedirectUri, state } = options;
87
+ return oidc
88
+ .buildEndSessionUrl(oidcConfiguration(client), {
89
+ ...(idToken ? { id_token_hint: idToken } : {}),
90
+ ...(postLogoutRedirectUri ? { post_logout_redirect_uri: postLogoutRedirectUri } : {}),
91
+ ...(state ? { state } : {}),
92
+ })
93
+ .toString();
94
+ }
95
+
96
+ /** Revokes the refresh token, ending this app's session only; `false` when Keycloak did not confirm. */
97
+ export async function endWebLogin(client: OidcClient, refreshToken: string, fetchImpl?: FetchLike): Promise<boolean> {
98
+ try {
99
+ await oidc.tokenRevocation(oidcConfiguration(client, fetchImpl), refreshToken, {
100
+ token_type_hint: "refresh_token",
101
+ });
102
+ return true;
103
+ } catch {
104
+ return false;
105
+ }
106
+ }