@perpetualsystems/typescript-sdk 0.0.0-bootstrap.0 → 0.4.0-next-20261110214241

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 (157) hide show
  1. package/README.md +26 -1
  2. package/dist/authorization-code-pkce.d.ts +40 -0
  3. package/dist/authorization-code-pkce.d.ts.map +1 -0
  4. package/dist/authorization-code-pkce.js +272 -0
  5. package/dist/authorization-code-pkce.js.map +1 -0
  6. package/dist/client-credentials.d.ts +18 -0
  7. package/dist/client-credentials.d.ts.map +1 -0
  8. package/dist/client-credentials.js +79 -0
  9. package/dist/client-credentials.js.map +1 -0
  10. package/dist/client-store.d.ts +37 -0
  11. package/dist/client-store.d.ts.map +1 -0
  12. package/dist/client-store.js +138 -0
  13. package/dist/client-store.js.map +1 -0
  14. package/dist/client.d.ts +113 -0
  15. package/dist/client.d.ts.map +1 -0
  16. package/dist/client.js +217 -0
  17. package/dist/client.js.map +1 -0
  18. package/dist/config-dir.d.ts +3 -0
  19. package/dist/config-dir.d.ts.map +1 -0
  20. package/dist/config-dir.js +11 -0
  21. package/dist/config-dir.js.map +1 -0
  22. package/dist/dynamic-registration.d.ts +28 -0
  23. package/dist/dynamic-registration.d.ts.map +1 -0
  24. package/dist/dynamic-registration.js +56 -0
  25. package/dist/dynamic-registration.js.map +1 -0
  26. package/dist/generated/client/client.gen.d.ts +3 -0
  27. package/dist/generated/client/client.gen.d.ts.map +1 -0
  28. package/dist/generated/client/client.gen.js +217 -0
  29. package/dist/generated/client/client.gen.js.map +1 -0
  30. package/dist/generated/client/index.d.ts +11 -0
  31. package/dist/generated/client/index.d.ts.map +1 -0
  32. package/dist/generated/client/index.js +7 -0
  33. package/dist/generated/client/index.js.map +1 -0
  34. package/dist/generated/client/types.gen.d.ts +121 -0
  35. package/dist/generated/client/types.gen.d.ts.map +1 -0
  36. package/dist/generated/client/types.gen.js +3 -0
  37. package/dist/generated/client/types.gen.js.map +1 -0
  38. package/dist/generated/client/utils.gen.d.ts +38 -0
  39. package/dist/generated/client/utils.gen.d.ts.map +1 -0
  40. package/dist/generated/client/utils.gen.js +229 -0
  41. package/dist/generated/client/utils.gen.js.map +1 -0
  42. package/dist/generated/client.gen.d.ts +13 -0
  43. package/dist/generated/client.gen.d.ts.map +1 -0
  44. package/dist/generated/client.gen.js +4 -0
  45. package/dist/generated/client.gen.js.map +1 -0
  46. package/dist/generated/core/auth.gen.d.ts +26 -0
  47. package/dist/generated/core/auth.gen.d.ts.map +1 -0
  48. package/dist/generated/core/auth.gen.js +15 -0
  49. package/dist/generated/core/auth.gen.js.map +1 -0
  50. package/dist/generated/core/bodySerializer.gen.d.ts +26 -0
  51. package/dist/generated/core/bodySerializer.gen.d.ts.map +1 -0
  52. package/dist/generated/core/bodySerializer.gen.js +58 -0
  53. package/dist/generated/core/bodySerializer.gen.js.map +1 -0
  54. package/dist/generated/core/params.gen.d.ts +44 -0
  55. package/dist/generated/core/params.gen.d.ts.map +1 -0
  56. package/dist/generated/core/params.gen.js +110 -0
  57. package/dist/generated/core/params.gen.js.map +1 -0
  58. package/dist/generated/core/pathSerializer.gen.d.ts +34 -0
  59. package/dist/generated/core/pathSerializer.gen.d.ts.map +1 -0
  60. package/dist/generated/core/pathSerializer.gen.js +107 -0
  61. package/dist/generated/core/pathSerializer.gen.js.map +1 -0
  62. package/dist/generated/core/queryKeySerializer.gen.d.ts +19 -0
  63. package/dist/generated/core/queryKeySerializer.gen.d.ts.map +1 -0
  64. package/dist/generated/core/queryKeySerializer.gen.js +93 -0
  65. package/dist/generated/core/queryKeySerializer.gen.js.map +1 -0
  66. package/dist/generated/core/serverSentEvents.gen.d.ts +72 -0
  67. package/dist/generated/core/serverSentEvents.gen.d.ts.map +1 -0
  68. package/dist/generated/core/serverSentEvents.gen.js +133 -0
  69. package/dist/generated/core/serverSentEvents.gen.js.map +1 -0
  70. package/dist/generated/core/types.gen.d.ts +84 -0
  71. package/dist/generated/core/types.gen.d.ts.map +1 -0
  72. package/dist/generated/core/types.gen.js +3 -0
  73. package/dist/generated/core/types.gen.js.map +1 -0
  74. package/dist/generated/core/utils.gen.d.ts +20 -0
  75. package/dist/generated/core/utils.gen.d.ts.map +1 -0
  76. package/dist/generated/core/utils.gen.js +88 -0
  77. package/dist/generated/core/utils.gen.js.map +1 -0
  78. package/dist/generated/enum-values.gen.d.ts +331 -0
  79. package/dist/generated/enum-values.gen.d.ts.map +1 -0
  80. package/dist/generated/enum-values.gen.js +332 -0
  81. package/dist/generated/enum-values.gen.js.map +1 -0
  82. package/dist/generated/file-schemas.gen.d.ts +14 -0
  83. package/dist/generated/file-schemas.gen.d.ts.map +1 -0
  84. package/dist/generated/file-schemas.gen.js +3786 -0
  85. package/dist/generated/file-schemas.gen.js.map +1 -0
  86. package/dist/generated/index.d.ts +3 -0
  87. package/dist/generated/index.d.ts.map +1 -0
  88. package/dist/generated/index.js +3 -0
  89. package/dist/generated/index.js.map +1 -0
  90. package/dist/generated/sdk.gen.d.ts +1713 -0
  91. package/dist/generated/sdk.gen.d.ts.map +1 -0
  92. package/dist/generated/sdk.gen.js +10574 -0
  93. package/dist/generated/sdk.gen.js.map +1 -0
  94. package/dist/generated/spec-source.gen.d.ts +8 -0
  95. package/dist/generated/spec-source.gen.d.ts.map +1 -0
  96. package/dist/generated/spec-source.gen.js +9 -0
  97. package/dist/generated/spec-source.gen.js.map +1 -0
  98. package/dist/generated/types.gen.d.ts +30382 -0
  99. package/dist/generated/types.gen.d.ts.map +1 -0
  100. package/dist/generated/types.gen.js +3 -0
  101. package/dist/generated/types.gen.js.map +1 -0
  102. package/dist/index.d.ts +21 -0
  103. package/dist/index.d.ts.map +1 -0
  104. package/dist/index.js +16 -0
  105. package/dist/index.js.map +1 -0
  106. package/dist/oauth-request-error.d.ts +26 -0
  107. package/dist/oauth-request-error.d.ts.map +1 -0
  108. package/dist/oauth-request-error.js +47 -0
  109. package/dist/oauth-request-error.js.map +1 -0
  110. package/dist/refresh-token.d.ts +50 -0
  111. package/dist/refresh-token.d.ts.map +1 -0
  112. package/dist/refresh-token.js +83 -0
  113. package/dist/refresh-token.js.map +1 -0
  114. package/dist/token-store.d.ts +38 -0
  115. package/dist/token-store.d.ts.map +1 -0
  116. package/dist/token-store.js +195 -0
  117. package/dist/token-store.js.map +1 -0
  118. package/openapi/openapi.json +128387 -0
  119. package/package.json +66 -4
  120. package/src/__tests__/authorization-code-pkce.test.ts +245 -0
  121. package/src/__tests__/client-credentials.test.ts +360 -0
  122. package/src/__tests__/client-store.test.ts +139 -0
  123. package/src/__tests__/client.test.ts +529 -0
  124. package/src/__tests__/config-dir.test.ts +22 -0
  125. package/src/__tests__/dynamic-registration.test.ts +181 -0
  126. package/src/__tests__/oauth-request-error.test.ts +148 -0
  127. package/src/__tests__/refresh-token.test.ts +206 -0
  128. package/src/__tests__/token-store.test.ts +449 -0
  129. package/src/authorization-code-pkce.ts +417 -0
  130. package/src/client-credentials.ts +127 -0
  131. package/src/client-store.ts +182 -0
  132. package/src/client.ts +261 -0
  133. package/src/config-dir.ts +12 -0
  134. package/src/dynamic-registration.ts +109 -0
  135. package/src/generated/client/client.gen.ts +277 -0
  136. package/src/generated/client/index.ts +27 -0
  137. package/src/generated/client/types.gen.ts +218 -0
  138. package/src/generated/client/utils.gen.ts +316 -0
  139. package/src/generated/client.gen.ts +16 -0
  140. package/src/generated/core/auth.gen.ts +48 -0
  141. package/src/generated/core/bodySerializer.gen.ts +82 -0
  142. package/src/generated/core/params.gen.ts +178 -0
  143. package/src/generated/core/pathSerializer.gen.ts +171 -0
  144. package/src/generated/core/queryKeySerializer.gen.ts +117 -0
  145. package/src/generated/core/serverSentEvents.gen.ts +242 -0
  146. package/src/generated/core/types.gen.ts +110 -0
  147. package/src/generated/core/utils.gen.ts +140 -0
  148. package/src/generated/enum-values.gen.ts +332 -0
  149. package/src/generated/file-schemas.gen.ts +3800 -0
  150. package/src/generated/index.ts +4 -0
  151. package/src/generated/sdk.gen.ts +10992 -0
  152. package/src/generated/spec-source.gen.ts +9 -0
  153. package/src/generated/types.gen.ts +32415 -0
  154. package/src/index.ts +55 -0
  155. package/src/oauth-request-error.ts +75 -0
  156. package/src/refresh-token.ts +142 -0
  157. package/src/token-store.ts +252 -0
package/src/index.ts ADDED
@@ -0,0 +1,55 @@
1
+ // Main exports
2
+
3
+ // Authorization Code with PKCE flow (RFC 6749 §4.1 + RFC 7636 + RFC 8252)
4
+ export type {
5
+ AuthorizationCodePkceOptions,
6
+ AuthorizationCodePkceResult,
7
+ } from "./authorization-code-pkce.js";
8
+ export { executeAuthorizationCodePkce } from "./authorization-code-pkce.js";
9
+ export type { PerpetualClientOptions } from "./client.js";
10
+ export { PerpetualClient } from "./client.js";
11
+ // Client credentials flow (RFC 6749 §4.4)
12
+ export type {
13
+ ClientCredentialsOptions,
14
+ ClientCredentialsResponse,
15
+ } from "./client-credentials.js";
16
+ export { exchangeClientCredentials } from "./client-credentials.js";
17
+ // Locally cached OAuth client registrations (DCR results)
18
+ export type { RegisteredClientRecord } from "./client-store.js";
19
+ export {
20
+ clearRegisteredClient,
21
+ getRegisteredClient,
22
+ saveRegisteredClient,
23
+ } from "./client-store.js";
24
+ // Dynamic Client Registration (RFC 7591)
25
+ export type {
26
+ RegisterClientOptions,
27
+ RegisteredClient,
28
+ } from "./dynamic-registration.js";
29
+ export { registerClient } from "./dynamic-registration.js";
30
+ // Re-export the Client type so consumers don't need deep imports
31
+ export type { Client } from "./generated/client/index.js";
32
+ // Re-export generated types and SDK for direct usage
33
+ // Users can import types like DashboardsListResponses, DashboardsCreateData, etc.
34
+ // and SDK functions like dashboardsList, dashboardsCreate, usersGetCurrent, etc.
35
+ export * from "./generated/index.js";
36
+ export { specSource } from "./generated/spec-source.gen.js";
37
+ // Refresh token grant (RFC 6749 §6) — exchange a refresh token for a fresh
38
+ // access token without re-prompting the user for browser auth.
39
+ export type {
40
+ RefreshTokenGrantOptions,
41
+ RefreshTokenGrantResult,
42
+ } from "./refresh-token.js";
43
+ export { executeRefreshTokenGrant } from "./refresh-token.js";
44
+ export type { OAuthRequestFailure } from "./oauth-request-error.js";
45
+ export { OAuthRequestError } from "./oauth-request-error.js";
46
+ export { getConfigDir } from "./config-dir.js";
47
+ // Token store for persisting OAuth tokens to disk
48
+ export type { StoredToken } from "./token-store.js";
49
+ export {
50
+ clearAllTokens,
51
+ clearToken,
52
+ getStoredToken,
53
+ normalizeEndpoint,
54
+ saveToken,
55
+ } from "./token-store.js";
@@ -0,0 +1,75 @@
1
+ export type OAuthRequestFailure = "network" | "timeout" | "http";
2
+
3
+ /** Matches PerpetualClient's default, so a hung authorization server cannot stall a login forever. */
4
+ export const OAUTH_REQUEST_TIMEOUT_MS = 30_000;
5
+
6
+ /**
7
+ * A request to an OAuth endpoint (token, refresh, registration) that got no
8
+ * usable response. `failure` tells an outage (`network`, `timeout`) apart from
9
+ * an endpoint that answered with an error status (`http`, with `status`).
10
+ */
11
+ export class OAuthRequestError extends Error {
12
+ readonly failure: OAuthRequestFailure;
13
+ readonly status?: number;
14
+
15
+ constructor(
16
+ message: string,
17
+ options: { failure: OAuthRequestFailure; status?: number; cause?: unknown },
18
+ ) {
19
+ super(message, { cause: options.cause });
20
+ this.name = "OAuthRequestError";
21
+ this.failure = options.failure;
22
+ this.status = options.status;
23
+ }
24
+ }
25
+
26
+ function isTimeout(error: unknown): boolean {
27
+ return (
28
+ error instanceof Error &&
29
+ (error.name === "TimeoutError" || error.name === "AbortError")
30
+ );
31
+ }
32
+
33
+ export function oauthTransportError(
34
+ action: string,
35
+ url: string,
36
+ cause: unknown,
37
+ ): OAuthRequestError {
38
+ const detail = cause instanceof Error ? cause.message : String(cause);
39
+ const timedOut = isTimeout(cause);
40
+ return new OAuthRequestError(
41
+ timedOut
42
+ ? `${action} failed: timed out waiting for ${url}`
43
+ : `${action} failed: network error at ${url}: ${detail}`,
44
+ { failure: timedOut ? "timeout" : "network", cause },
45
+ );
46
+ }
47
+
48
+ export function oauthHttpError(
49
+ action: string,
50
+ response: Response,
51
+ body: string,
52
+ ): OAuthRequestError {
53
+ return new OAuthRequestError(
54
+ `${action} failed (${response.status}): ${body || response.statusText}`,
55
+ { failure: "http", status: response.status },
56
+ );
57
+ }
58
+
59
+ /**
60
+ * A success whose body stops arriving is an outage like any other, so it is a
61
+ * transport failure; an error status keeps a placeholder so its status still
62
+ * reaches the caller.
63
+ */
64
+ export async function readOAuthBody(
65
+ action: string,
66
+ url: string,
67
+ response: Response,
68
+ ): Promise<string> {
69
+ try {
70
+ return await response.text();
71
+ } catch (e) {
72
+ if (response.ok) throw oauthTransportError(action, url, e);
73
+ return `(error body unreadable: ${e instanceof Error ? e.message : String(e)})`;
74
+ }
75
+ }
@@ -0,0 +1,142 @@
1
+ import { normalizeEndpoint } from "./token-store.js";
2
+ import {
3
+ OAUTH_REQUEST_TIMEOUT_MS,
4
+ oauthHttpError,
5
+ oauthTransportError,
6
+ readOAuthBody,
7
+ } from "./oauth-request-error.js";
8
+
9
+ export interface RefreshTokenGrantOptions {
10
+ endpoint: string;
11
+ /** OAuth client_id from dynamic registration. Public clients still send
12
+ * client_id on refresh; confidential clients also send client_secret. */
13
+ clientId: string;
14
+ /** Optional client_secret. Mirrors authorization-code-pkce.ts: PKCE-only
15
+ * flows can omit it, but the Perpetual backend may issue a secret on
16
+ * registration which must be included here. */
17
+ clientSecret?: string;
18
+ /** The refresh token to exchange. Per OAuth 2.1 §6, the AS may rotate
19
+ * this on every use — the response's refresh_token field MUST be saved
20
+ * back if present. */
21
+ refreshToken: string;
22
+ /** Override fetch for testing. */
23
+ _fetch?: typeof fetch;
24
+ /** Where to write user-facing progress messages (defaults to no-op,
25
+ * since refresh is silent). */
26
+ log?: (message: string) => void;
27
+ requestTimeoutMs?: number;
28
+ }
29
+
30
+ export interface RefreshTokenGrantResult {
31
+ token: string;
32
+ /** New refresh token if the AS rotated it. Per OAuth 2.1 §6.1 rotation
33
+ * is recommended for public clients; if the response omits it, the
34
+ * caller should keep using the previous refresh token (older AS
35
+ * implementations don't rotate). */
36
+ refreshToken?: string;
37
+ expiresIn?: number;
38
+ tokenType: string;
39
+ }
40
+
41
+ /**
42
+ * Exchange a refresh token for a fresh access token.
43
+ *
44
+ * Implements RFC 6749 §6 (Refreshing an Access Token) against the
45
+ * Perpetual `/api/oauth/token` endpoint. Mirrors the response-parsing
46
+ * shape of `executeAuthorizationCodePkce` so callers can handle both
47
+ * grant types uniformly.
48
+ *
49
+ * Throws on:
50
+ * - Network errors (transport-level failures hitting the token endpoint)
51
+ * - Non-2xx responses (refresh token expired/invalid/revoked)
52
+ * - Malformed response (missing access_token, non-Bearer token_type)
53
+ *
54
+ * The CLI's refreshStoredLogin catches these and surfaces a
55
+ * "Run perpetual login to re-authenticate" message — most failures here
56
+ * mean the refresh token is no longer valid and the user must re-auth
57
+ * via the browser flow.
58
+ */
59
+ export async function executeRefreshTokenGrant(
60
+ options: RefreshTokenGrantOptions,
61
+ ): Promise<RefreshTokenGrantResult> {
62
+ const fetchFn = options._fetch ?? fetch;
63
+ const requestTimeoutMs = options.requestTimeoutMs ?? OAUTH_REQUEST_TIMEOUT_MS;
64
+ const log = options.log ?? (() => {});
65
+
66
+ const tokenUrl = `${normalizeEndpoint(options.endpoint)}/api/oauth/token`;
67
+ const body = new URLSearchParams({
68
+ grant_type: "refresh_token",
69
+ refresh_token: options.refreshToken,
70
+ client_id: options.clientId,
71
+ });
72
+ if (options.clientSecret) {
73
+ body.set("client_secret", options.clientSecret);
74
+ }
75
+
76
+ let response: Response;
77
+ try {
78
+ response = await fetchFn(tokenUrl, {
79
+ method: "POST",
80
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
81
+ body: body.toString(),
82
+ signal: AbortSignal.timeout(requestTimeoutMs),
83
+ });
84
+ } catch (networkError) {
85
+ throw oauthTransportError("Refresh token exchange", tokenUrl, networkError);
86
+ }
87
+
88
+ const text = await readOAuthBody(
89
+ "Refresh token exchange",
90
+ tokenUrl,
91
+ response,
92
+ );
93
+
94
+ if (!response.ok) {
95
+ throw oauthHttpError("Refresh token exchange", response, text);
96
+ }
97
+
98
+ let data: Record<string, unknown>;
99
+ try {
100
+ data = JSON.parse(text);
101
+ } catch (parseError) {
102
+ const detail =
103
+ parseError instanceof Error ? parseError.message : String(parseError);
104
+ throw new Error(
105
+ `Refresh token response is not valid JSON (${response.status}): ${text.slice(0, 200) || response.statusText} (${detail})`,
106
+ );
107
+ }
108
+
109
+ if (typeof data.access_token !== "string" || !data.access_token) {
110
+ throw new Error("Refresh token response missing access_token");
111
+ }
112
+ const tokenType =
113
+ typeof data.token_type === "string" ? data.token_type : "Bearer";
114
+ if (tokenType.toLowerCase() !== "bearer") {
115
+ throw new Error(
116
+ `Unsupported token type: "${tokenType}". Only Bearer tokens are supported.`,
117
+ );
118
+ }
119
+
120
+ let expiresIn: number | undefined;
121
+ if (data.expires_in !== undefined) {
122
+ if (
123
+ typeof data.expires_in === "number" &&
124
+ Number.isFinite(data.expires_in) &&
125
+ data.expires_in > 0
126
+ ) {
127
+ expiresIn = data.expires_in;
128
+ } else {
129
+ log(
130
+ `Warning: refresh response contained invalid expires_in: ${JSON.stringify(data.expires_in)}, ignoring\n`,
131
+ );
132
+ }
133
+ }
134
+
135
+ return {
136
+ token: data.access_token,
137
+ refreshToken:
138
+ typeof data.refresh_token === "string" ? data.refresh_token : undefined,
139
+ expiresIn,
140
+ tokenType,
141
+ };
142
+ }
@@ -0,0 +1,252 @@
1
+ import {
2
+ chmodSync,
3
+ copyFileSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ renameSync,
8
+ unlinkSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { getConfigDir } from "./config-dir.js";
13
+
14
+ export interface StoredToken {
15
+ token: string;
16
+ expiresAt?: string;
17
+ userId?: string;
18
+ orgId?: string;
19
+ }
20
+
21
+ interface TokenFile {
22
+ [key: string]: StoredToken;
23
+ }
24
+
25
+ /**
26
+ * Normalize an endpoint URL for use as a token store key.
27
+ * Strips trailing slashes and lowercases the host portion.
28
+ */
29
+ export function normalizeEndpoint(endpoint: string): string {
30
+ try {
31
+ const url = new URL(endpoint);
32
+ url.hostname = url.hostname.toLowerCase();
33
+ // Remove trailing slash from pathname
34
+ if (url.pathname.endsWith("/")) {
35
+ url.pathname = url.pathname.replace(/\/+$/, "") || "/";
36
+ }
37
+ // Return origin + pathname (without trailing slash), dropping default port
38
+ let result = url.origin;
39
+ if (url.pathname !== "/") {
40
+ result += url.pathname;
41
+ }
42
+ return result;
43
+ } catch (parseError) {
44
+ throw new Error(
45
+ `Invalid endpoint URL: "${endpoint}". Must include protocol (e.g., https://example.com). ` +
46
+ `Parse error: ${parseError instanceof Error ? parseError.message : String(parseError)}`,
47
+ );
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Build a composite key for the token store.
53
+ * When clientId is provided, the key is `endpoint::clientId` to support
54
+ * multiple OAuth clients on the same endpoint.
55
+ */
56
+ function tokenKey(endpoint: string, clientId?: string): string {
57
+ const normalized = normalizeEndpoint(endpoint);
58
+ return clientId ? `${normalized}::${clientId}` : normalized;
59
+ }
60
+
61
+ function getTokenFilePath(): string {
62
+ return join(getConfigDir(), "tokens.json");
63
+ }
64
+
65
+ /**
66
+ * Back up a corrupted token file so data is not permanently lost.
67
+ * Best-effort: logs a warning if the backup itself fails.
68
+ */
69
+ function backupCorruptedFile(filePath: string): void {
70
+ const backupPath = `${filePath}.bak`;
71
+ try {
72
+ copyFileSync(filePath, backupPath);
73
+ process.stderr.write(` Corrupted file backed up to ${backupPath}\n`);
74
+ } catch (backupError) {
75
+ process.stderr.write(
76
+ ` Warning: Could not back up corrupted file: ${backupError instanceof Error ? backupError.message : String(backupError)}\n`,
77
+ );
78
+ }
79
+ }
80
+
81
+ function readTokenFile(): TokenFile {
82
+ const filePath = getTokenFilePath();
83
+ if (!existsSync(filePath)) {
84
+ return {};
85
+ }
86
+
87
+ let content: string;
88
+ try {
89
+ content = readFileSync(filePath, "utf-8");
90
+ } catch (fsError) {
91
+ // Filesystem errors (permissions, I/O) — propagate so callers know
92
+ throw new Error(
93
+ `Cannot read tokens.json: ${fsError instanceof Error ? fsError.message : String(fsError)}`,
94
+ );
95
+ }
96
+
97
+ let parsed: unknown;
98
+ try {
99
+ parsed = JSON.parse(content);
100
+ } catch (parseError) {
101
+ const detail =
102
+ parseError instanceof Error ? parseError.message : String(parseError);
103
+ backupCorruptedFile(filePath);
104
+ process.stderr.write(
105
+ `Warning: tokens.json contains invalid JSON (${detail}), starting fresh\n`,
106
+ );
107
+ return {};
108
+ }
109
+
110
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
111
+ backupCorruptedFile(filePath);
112
+ process.stderr.write(
113
+ "Warning: tokens.json has unexpected format, ignoring\n",
114
+ );
115
+ return {};
116
+ }
117
+ return parsed as TokenFile;
118
+ }
119
+
120
+ function writeTokenFile(data: TokenFile): void {
121
+ const filePath = getTokenFilePath();
122
+ const dir = dirname(filePath);
123
+ const tmpPath = `${filePath}.tmp`;
124
+
125
+ // Atomic write: stage to <path>.tmp, chmod, then rename into place.
126
+ // POSIX rename is atomic, so a process kill mid-write cannot leave a
127
+ // half-written file that would silently lose every stored token on next
128
+ // read. Mirrors the pattern used in client-store.ts.
129
+ try {
130
+ if (!existsSync(dir)) {
131
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
132
+ }
133
+
134
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), { mode: 0o600 });
135
+ try {
136
+ // writeFileSync's `mode` is only honored when CREATING the file, so
137
+ // chmod after-the-fact when the staging path already existed.
138
+ // Chmod failures matter on a credentials file: surface them so a
139
+ // mis-umask'd write doesn't leave the secret world-readable silently.
140
+ chmodSync(tmpPath, 0o600);
141
+ } catch (e) {
142
+ process.stderr.write(
143
+ `Warning: could not chmod ${tmpPath} to 0600: ` +
144
+ `${e instanceof Error ? e.message : String(e)}\n`,
145
+ );
146
+ }
147
+ renameSync(tmpPath, filePath);
148
+ try {
149
+ chmodSync(dir, 0o700);
150
+ } catch (e) {
151
+ process.stderr.write(
152
+ `Warning: could not chmod ${dir} to 0700: ` +
153
+ `${e instanceof Error ? e.message : String(e)}\n`,
154
+ );
155
+ }
156
+ } catch (fsError) {
157
+ // Clean up the staging file on failure so a transient I/O error
158
+ // doesn't leave a stray credentials .tmp around forever.
159
+ try {
160
+ if (existsSync(tmpPath)) unlinkSync(tmpPath);
161
+ } catch {
162
+ /* best effort */
163
+ }
164
+ throw new Error(
165
+ `Failed to write token file at ${filePath}: ${fsError instanceof Error ? fsError.message : String(fsError)}`,
166
+ );
167
+ }
168
+ }
169
+
170
+ /** Buffer before token expiry to avoid using almost-expired tokens (60 seconds). */
171
+ const EXPIRY_BUFFER_MS = 60 * 1000;
172
+
173
+ /**
174
+ * Retrieve a stored token for the given endpoint (and optional clientId).
175
+ * Returns null if no token is found, the token is expired (or within 60s of expiry),
176
+ * or the file has invalid JSON.
177
+ * Throws if the file cannot be read due to filesystem errors (permissions, I/O).
178
+ */
179
+ export function getStoredToken(
180
+ endpoint: string,
181
+ clientId?: string,
182
+ ): StoredToken | null {
183
+ const key = tokenKey(endpoint, clientId);
184
+ const tokens = readTokenFile();
185
+ const stored = tokens[key];
186
+ if (!stored?.token) {
187
+ return null;
188
+ }
189
+ // Check expiry if present (with buffer to avoid using almost-expired tokens)
190
+ if (stored.expiresAt) {
191
+ const expiry = new Date(stored.expiresAt);
192
+ if (
193
+ Number.isNaN(expiry.getTime()) ||
194
+ expiry.getTime() <= Date.now() + EXPIRY_BUFFER_MS
195
+ ) {
196
+ return null;
197
+ }
198
+ }
199
+ return stored;
200
+ }
201
+
202
+ /**
203
+ * Save a token for the given endpoint (and optional clientId).
204
+ */
205
+ export function saveToken(
206
+ endpoint: string,
207
+ token: string,
208
+ options?: {
209
+ clientId?: string;
210
+ userId?: string;
211
+ orgId?: string;
212
+ expiresAt?: string;
213
+ },
214
+ ): void {
215
+ if (!token) {
216
+ throw new Error("Cannot save empty token");
217
+ }
218
+ if (options?.expiresAt) {
219
+ const expiry = new Date(options.expiresAt);
220
+ if (Number.isNaN(expiry.getTime())) {
221
+ throw new Error(`Invalid expiresAt date: ${options.expiresAt}`);
222
+ }
223
+ }
224
+ const key = tokenKey(endpoint, options?.clientId);
225
+ const tokens = readTokenFile();
226
+ tokens[key] = {
227
+ token,
228
+ ...(options?.expiresAt ? { expiresAt: options.expiresAt } : {}),
229
+ ...(options?.userId ? { userId: options.userId } : {}),
230
+ ...(options?.orgId ? { orgId: options.orgId } : {}),
231
+ };
232
+ writeTokenFile(tokens);
233
+ }
234
+
235
+ /**
236
+ * Clear the stored token for a specific endpoint (and optional clientId).
237
+ * May throw if the token file cannot be read or written (filesystem errors).
238
+ */
239
+ export function clearToken(endpoint: string, clientId?: string): void {
240
+ const key = tokenKey(endpoint, clientId);
241
+ const tokens = readTokenFile();
242
+ delete tokens[key];
243
+ writeTokenFile(tokens);
244
+ }
245
+
246
+ /**
247
+ * Clear all stored tokens.
248
+ * May throw if the token file cannot be written (filesystem errors).
249
+ */
250
+ export function clearAllTokens(): void {
251
+ writeTokenFile({});
252
+ }