@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
@@ -0,0 +1,182 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ renameSync,
7
+ unlinkSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { getConfigDir } from "./config-dir.js";
12
+ import { normalizeEndpoint } from "./token-store.js";
13
+
14
+ /**
15
+ * A dynamically registered OAuth client (RFC 7591) cached locally so the
16
+ * CLI doesn't need to register a fresh client_id on every invocation.
17
+ *
18
+ * The Perpetual backend issues a client_secret on registration even for
19
+ * PKCE-only public clients; we cache it here because it's required on
20
+ * the token exchange.
21
+ *
22
+ * `redirectUri` is recorded at registration time and reused on subsequent
23
+ * runs so the loopback server binds to the same port. If the port turns
24
+ * out to be in use, the caller should re-register with a new port.
25
+ */
26
+ export interface RegisteredClientRecord {
27
+ clientId: string;
28
+ clientSecret?: string;
29
+ redirectUri: string;
30
+ registeredAt: string;
31
+ }
32
+
33
+ interface ClientFile {
34
+ [endpoint: string]: RegisteredClientRecord;
35
+ }
36
+
37
+ function getClientFilePath(): string {
38
+ return join(getConfigDir(), "oauth-clients.json");
39
+ }
40
+
41
+ function readClientFile(): ClientFile {
42
+ const filePath = getClientFilePath();
43
+ if (!existsSync(filePath)) return {};
44
+ let text: string;
45
+ try {
46
+ text = readFileSync(filePath, "utf-8");
47
+ } catch (e) {
48
+ // Read failure (permission, I/O error) is NOT the same as "no cache".
49
+ // Surface it so the user sees the real cause instead of silently
50
+ // re-registering on every run.
51
+ process.stderr.write(
52
+ `Warning: could not read OAuth client cache at ${filePath}: ` +
53
+ `${e instanceof Error ? e.message : String(e)}\n`,
54
+ );
55
+ return {};
56
+ }
57
+ try {
58
+ const parsed = JSON.parse(text);
59
+ if (typeof parsed !== "object" || parsed === null) return {};
60
+ // Validate each entry's shape. A partial-write or hand-edit that
61
+ // produces a wrong-typed entry would otherwise crash deep inside the
62
+ // OAuth flow with a confusing TypeError.
63
+ const file: ClientFile = {};
64
+ for (const [k, v] of Object.entries(parsed)) {
65
+ if (
66
+ v &&
67
+ typeof v === "object" &&
68
+ typeof (v as Record<string, unknown>).clientId === "string" &&
69
+ typeof (v as Record<string, unknown>).redirectUri === "string"
70
+ ) {
71
+ file[k] = v as RegisteredClientRecord;
72
+ }
73
+ }
74
+ return file;
75
+ } catch {
76
+ // Parse failure: file is corrupt (e.g. partial write from a crash).
77
+ // Treat as empty so we re-register cleanly.
78
+ process.stderr.write(
79
+ `Warning: OAuth client cache at ${filePath} is corrupt; ignoring.\n`,
80
+ );
81
+ return {};
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Atomically write the client cache. Writes to `<path>.tmp` first then
87
+ * renames into place; POSIX rename is atomic so a process kill mid-write
88
+ * cannot leave a half-written file that would silently lose every cached
89
+ * registration on next read.
90
+ *
91
+ * NOTE: There is no advisory lock around read-modify-write. Two concurrent
92
+ * CLI invocations both registering at the same time will both succeed at
93
+ * the AS but only one client_id ends up in the cache. The other becomes
94
+ * an orphan at the AS until manually cleaned. Acceptable for the CLI's
95
+ * usage pattern; revisit if SDK consumers run many parallel registrations.
96
+ */
97
+ function writeClientFile(data: ClientFile): void {
98
+ const dir = getConfigDir();
99
+ if (!existsSync(dir)) {
100
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
101
+ }
102
+ const filePath = getClientFilePath();
103
+ const tmpPath = `${filePath}.tmp`;
104
+ try {
105
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), { mode: 0o600 });
106
+ try {
107
+ chmodSync(tmpPath, 0o600);
108
+ } catch (e) {
109
+ // Chmod failures matter on a credentials file: surface them so a
110
+ // mis-umask'd write doesn't leave the secret world-readable silently.
111
+ process.stderr.write(
112
+ `Warning: could not chmod ${tmpPath} to 0600: ` +
113
+ `${e instanceof Error ? e.message : String(e)}\n`,
114
+ );
115
+ }
116
+ renameSync(tmpPath, filePath);
117
+ try {
118
+ chmodSync(dirname(filePath), 0o700);
119
+ } catch (e) {
120
+ process.stderr.write(
121
+ `Warning: could not chmod ${dirname(filePath)} to 0700: ` +
122
+ `${e instanceof Error ? e.message : String(e)}\n`,
123
+ );
124
+ }
125
+ } catch (writeError) {
126
+ // Clean up the staging file on failure so a transient I/O error
127
+ // doesn't leave a stray credentials .tmp around forever.
128
+ try {
129
+ if (existsSync(tmpPath)) unlinkSync(tmpPath);
130
+ } catch {
131
+ /* best effort */
132
+ }
133
+ throw writeError;
134
+ }
135
+ }
136
+
137
+ /**
138
+ * Look up a previously registered OAuth client for the given endpoint.
139
+ * Returns undefined if no registration exists locally.
140
+ */
141
+ export function getRegisteredClient(
142
+ endpoint: string,
143
+ ): RegisteredClientRecord | undefined {
144
+ const key = normalizeEndpoint(endpoint);
145
+ const file = readClientFile();
146
+ return file[key];
147
+ }
148
+
149
+ /**
150
+ * Persist a registered OAuth client for the given endpoint. Overwrites
151
+ * any prior registration for the same endpoint.
152
+ */
153
+ export function saveRegisteredClient(
154
+ endpoint: string,
155
+ record: Omit<RegisteredClientRecord, "registeredAt"> & {
156
+ registeredAt?: string;
157
+ },
158
+ ): void {
159
+ const key = normalizeEndpoint(endpoint);
160
+ const file = readClientFile();
161
+ file[key] = {
162
+ clientId: record.clientId,
163
+ clientSecret: record.clientSecret,
164
+ redirectUri: record.redirectUri,
165
+ registeredAt: record.registeredAt ?? new Date().toISOString(),
166
+ };
167
+ writeClientFile(file);
168
+ }
169
+
170
+ /**
171
+ * Remove the cached registration for the given endpoint. Useful when the
172
+ * registered redirect_uri's port becomes unavailable and the caller wants
173
+ * to force a re-registration.
174
+ */
175
+ export function clearRegisteredClient(endpoint: string): void {
176
+ const key = normalizeEndpoint(endpoint);
177
+ const file = readClientFile();
178
+ if (key in file) {
179
+ delete file[key];
180
+ writeClientFile(file);
181
+ }
182
+ }
package/src/client.ts ADDED
@@ -0,0 +1,261 @@
1
+ import type { AuthorizationCodePkceOptions } from "./authorization-code-pkce.js";
2
+ import { executeAuthorizationCodePkce } from "./authorization-code-pkce.js";
3
+ import type { ClientCredentialsOptions } from "./client-credentials.js";
4
+ import { exchangeClientCredentials } from "./client-credentials.js";
5
+ import type { Client } from "./generated/client/index.js";
6
+ import { createClient, createConfig } from "./generated/client/index.js";
7
+ import { sessionCreate, sessionDelete } from "./generated/sdk.gen.js";
8
+ import { normalizeEndpoint } from "./token-store.js";
9
+
10
+ export interface PerpetualClientOptions {
11
+ endpoint: string;
12
+ /** Request timeout in milliseconds. When set, each fetch request will be aborted if it exceeds this duration. */
13
+ timeout?: number;
14
+ }
15
+
16
+ export class PerpetualClient {
17
+ private _client: Client;
18
+ private endpoint: string;
19
+ private _token: string | null = null;
20
+
21
+ constructor(options: PerpetualClientOptions) {
22
+ this.endpoint = normalizeEndpoint(options.endpoint);
23
+ const config: Parameters<typeof createConfig>[0] = {
24
+ baseUrl: `${this.endpoint}/api/v0`,
25
+ };
26
+ if (options.timeout != null && options.timeout > 0) {
27
+ const ms = options.timeout;
28
+ config.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
29
+ const timeoutSignal = AbortSignal.timeout(ms);
30
+ const signal = init?.signal
31
+ ? AbortSignal.any([init.signal, timeoutSignal])
32
+ : timeoutSignal;
33
+ return fetch(input, { ...init, signal });
34
+ };
35
+ }
36
+ this._client = createClient(createConfig(config));
37
+ }
38
+
39
+ /**
40
+ * Get the underlying SDK client for direct API calls.
41
+ * Use with generated SDK functions like dashboardsList, dashboardsCreate, etc.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import { dashboardsList } from "./generated/sdk.gen.js";
46
+ *
47
+ * const response = await dashboardsList({
48
+ * client: perpetual.client,
49
+ * path: { orgId },
50
+ * headers: perpetual.getAuthHeaders(),
51
+ * });
52
+ * ```
53
+ */
54
+ get client(): Client {
55
+ return this._client;
56
+ }
57
+
58
+ /**
59
+ * Get the normalized endpoint URL (lowercase host, no trailing slash).
60
+ * Use as a key for the token store.
61
+ */
62
+ get endpointUrl(): string {
63
+ return this.endpoint;
64
+ }
65
+
66
+ /**
67
+ * Get the current authentication token, or null if not authenticated.
68
+ */
69
+ get token(): string | null {
70
+ return this._token;
71
+ }
72
+
73
+ /**
74
+ * Get headers with Bearer token if available.
75
+ * Sends both cookie variants to support local (http) and production (https) environments.
76
+ *
77
+ * Use this with SDK calls that require authentication:
78
+ * ```ts
79
+ * const response = await dashboardsList({
80
+ * client: perpetual.client,
81
+ * path: { orgId },
82
+ * headers: perpetual.getAuthHeaders(),
83
+ * });
84
+ * ```
85
+ */
86
+ getAuthHeaders(): Record<string, string> {
87
+ if (this._token) {
88
+ return {
89
+ Authorization: `Bearer ${this._token}`,
90
+ Cookie: `better-auth.session_token=${this._token}; __Secure-better-auth.session_token=${this._token}`,
91
+ };
92
+ }
93
+ return {};
94
+ }
95
+
96
+ /**
97
+ * Check if the client has an active authentication token.
98
+ */
99
+ get isAuthenticated(): boolean {
100
+ return this._token !== null;
101
+ }
102
+
103
+ /**
104
+ * Set the authentication token directly, e.g. when restoring from a stored profile.
105
+ * @param token - A previously obtained session token
106
+ */
107
+ setToken(token: string): void {
108
+ if (!token) {
109
+ throw new Error("Cannot set empty token");
110
+ }
111
+ this._token = token;
112
+ }
113
+
114
+ /**
115
+ * Login via the OAuth 2.0 Authorization Code flow with PKCE
116
+ * (RFC 6749 §4.1 + RFC 7636). Opens a browser for the user to authorize,
117
+ * catches the redirect on a localhost loopback, and exchanges the code
118
+ * for a token. Replaces the prior device-code flow which the Perpetual
119
+ * backend no longer supports.
120
+ *
121
+ * @param clientId - OAuth client ID registered with the server (typically
122
+ * obtained via Dynamic Client Registration; see `registerClient`)
123
+ * @param redirectUri - Loopback redirect URI registered with the AS;
124
+ * the SDK will start an HTTP server bound to its host:port to catch
125
+ * the callback. Use `http://127.0.0.1:PORT/callback`.
126
+ * @param options - Optional client_secret, log/open overrides for testing,
127
+ * and timeout. The Perpetual backend issues a secret on registration
128
+ * even for PKCE-only clients; pass it here when present.
129
+ * @returns Object containing the access token and optional refresh token
130
+ * + expiration in seconds.
131
+ */
132
+ async loginInteractive(
133
+ clientId: string,
134
+ redirectUri: string,
135
+ options?: Pick<
136
+ AuthorizationCodePkceOptions,
137
+ "clientSecret" | "scope" | "log" | "_openUrl" | "_fetch" | "timeoutMs"
138
+ >,
139
+ ): Promise<{ token: string; refreshToken?: string; expiresIn?: number }> {
140
+ const result = await executeAuthorizationCodePkce({
141
+ endpoint: this.endpoint,
142
+ clientId,
143
+ redirectUri,
144
+ ...options,
145
+ });
146
+ this._token = result.token;
147
+ return {
148
+ token: result.token,
149
+ refreshToken: result.refreshToken,
150
+ expiresIn: result.expiresIn,
151
+ };
152
+ }
153
+
154
+ /**
155
+ * Login via OAuth Client Credentials Grant (RFC 6749 §4.4).
156
+ * Exchanges client_id + client_secret for an access token.
157
+ *
158
+ * @param clientId - OAuth client ID
159
+ * @param clientSecret - OAuth client secret
160
+ * @param options - Optional fetch override for testing
161
+ * @returns Object containing the access token and optional expiration in seconds
162
+ */
163
+ async loginClientCredentials(
164
+ clientId: string,
165
+ clientSecret: string,
166
+ options?: Pick<ClientCredentialsOptions, "_fetch">,
167
+ ): Promise<{ token: string; expiresIn?: number }> {
168
+ const result = await exchangeClientCredentials({
169
+ endpoint: this.endpoint,
170
+ clientId,
171
+ clientSecret,
172
+ ...options,
173
+ });
174
+ this._token = result.access_token;
175
+ return { token: result.access_token, expiresIn: result.expires_in };
176
+ }
177
+
178
+ /**
179
+ * Login with username and password.
180
+ * @param username - User's email address
181
+ * @param password - User's password
182
+ * @returns The userId from the session
183
+ * @throws Error if authentication fails or token cannot be extracted
184
+ */
185
+ async login(username: string, password: string): Promise<string> {
186
+ const response = await sessionCreate({
187
+ client: this._client,
188
+ body: { username, password },
189
+ throwOnError: true,
190
+ });
191
+
192
+ if (!response.data) {
193
+ throw new Error("Login failed: no data returned from server");
194
+ }
195
+
196
+ if (!response.data.userId || typeof response.data.userId !== "string") {
197
+ throw new Error("Login failed: userId missing from response");
198
+ }
199
+
200
+ // Extract token from set-cookie header
201
+ const setCookie = response.response.headers.get("set-cookie");
202
+ if (!setCookie) {
203
+ throw new Error(
204
+ "Login failed: no set-cookie header in response. Server may not be returning session token.",
205
+ );
206
+ }
207
+
208
+ const tokenMatch = setCookie.match(
209
+ /(?:^|;\s*)(?:__Secure-)?better-auth\.session_token=([^;]+)/,
210
+ );
211
+ if (!tokenMatch?.[1] || tokenMatch[1].trim() === "") {
212
+ throw new Error(
213
+ "Login failed: token value in set-cookie header is empty or invalid",
214
+ );
215
+ }
216
+
217
+ // Decode URL-encoded token values (cookies may be percent-encoded)
218
+ try {
219
+ this._token = decodeURIComponent(tokenMatch[1]);
220
+ } catch (decodeError) {
221
+ throw new Error(
222
+ `Login failed: unable to decode session token from cookie (${decodeError instanceof Error ? decodeError.message : String(decodeError)})`,
223
+ );
224
+ }
225
+ return response.data.userId;
226
+ }
227
+
228
+ /**
229
+ * Logout and destroy the current session.
230
+ * Idempotent - safe to call even if not logged in or if server call fails.
231
+ * Always clears local token regardless of server response.
232
+ */
233
+ async logout(): Promise<void> {
234
+ if (!this._token) {
235
+ return; // Already logged out
236
+ }
237
+
238
+ try {
239
+ await sessionDelete({
240
+ client: this._client,
241
+ headers: this.getAuthHeaders(),
242
+ throwOnError: true,
243
+ });
244
+ } catch (error) {
245
+ // Log but don't throw - logout should succeed locally even if server call fails
246
+ // Server session may already be expired or invalidated
247
+ try {
248
+ const errorType =
249
+ error instanceof Error ? error.constructor.name : "Unknown";
250
+ const errorMsg = error instanceof Error ? error.message : String(error);
251
+ process.stderr.write(
252
+ `Warning: Server logout failed (local token cleared) [${errorType}]: ${errorMsg}\n`,
253
+ );
254
+ } catch {
255
+ // Best-effort warning — don't let a broken stderr violate logout's no-throw contract
256
+ }
257
+ } finally {
258
+ this._token = null;
259
+ }
260
+ }
261
+ }
@@ -0,0 +1,12 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, join } from "node:path";
3
+
4
+ /** The XDG spec says to ignore a relative XDG_CONFIG_HOME, which would put secrets under the working directory. */
5
+ export function getConfigDir(): string {
6
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME;
7
+ const base =
8
+ xdgConfigHome && isAbsolute(xdgConfigHome)
9
+ ? xdgConfigHome
10
+ : join(homedir(), ".config");
11
+ return join(base, "perpetual");
12
+ }
@@ -0,0 +1,109 @@
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 RegisterClientOptions {
10
+ endpoint: string;
11
+ clientName: string;
12
+ redirectUris: string[];
13
+ /** Defaults to ["authorization_code", "refresh_token"] for interactive CLI clients. */
14
+ grantTypes?: string[];
15
+ /** Defaults to ["code"]. */
16
+ responseTypes?: string[];
17
+ /** Override fetch for testing */
18
+ _fetch?: typeof fetch;
19
+ requestTimeoutMs?: number;
20
+ }
21
+
22
+ export interface RegisteredClient {
23
+ clientId: string;
24
+ /** Confidential clients receive a secret; public PKCE-only clients may not. */
25
+ clientSecret?: string;
26
+ redirectUris: string[];
27
+ }
28
+
29
+ /**
30
+ * Register a new OAuth 2.0 client with the authorization server (RFC 7591
31
+ * Dynamic Client Registration). Returns a client_id (and secret if the
32
+ * server issues one) that can be used in subsequent authorization flows.
33
+ *
34
+ * The Perpetual backend issues a client_secret even for public PKCE clients;
35
+ * callers using the authorization-code-pkce flow may ignore the secret.
36
+ */
37
+ export async function registerClient(
38
+ options: RegisterClientOptions,
39
+ ): Promise<RegisteredClient> {
40
+ const {
41
+ endpoint,
42
+ clientName,
43
+ redirectUris,
44
+ grantTypes = ["authorization_code", "refresh_token"],
45
+ responseTypes = ["code"],
46
+ _fetch: fetchFn = fetch,
47
+ requestTimeoutMs = OAUTH_REQUEST_TIMEOUT_MS,
48
+ } = options;
49
+
50
+ const url = `${normalizeEndpoint(endpoint)}/api/oauth/register`;
51
+ let response: Response;
52
+ try {
53
+ response = await fetchFn(url, {
54
+ method: "POST",
55
+ headers: { "Content-Type": "application/json" },
56
+ body: JSON.stringify({
57
+ client_name: clientName,
58
+ redirect_uris: redirectUris,
59
+ grant_types: grantTypes,
60
+ response_types: responseTypes,
61
+ }),
62
+ signal: AbortSignal.timeout(requestTimeoutMs),
63
+ });
64
+ } catch (networkError) {
65
+ throw oauthTransportError("Dynamic client registration", url, networkError);
66
+ }
67
+
68
+ const text = await readOAuthBody(
69
+ "Dynamic client registration",
70
+ url,
71
+ response,
72
+ );
73
+
74
+ if (!response.ok) {
75
+ throw oauthHttpError("Dynamic client registration", response, text);
76
+ }
77
+
78
+ let data: Record<string, unknown>;
79
+ try {
80
+ data = JSON.parse(text);
81
+ } catch (parseError) {
82
+ const detail =
83
+ parseError instanceof Error ? parseError.message : String(parseError);
84
+ throw new Error(
85
+ `Dynamic client registration response is not valid JSON (${response.status}): ${text.slice(0, 200) || response.statusText} (${detail})`,
86
+ );
87
+ }
88
+
89
+ if (typeof data.client_id !== "string" || !data.client_id) {
90
+ throw new Error(
91
+ "Dynamic client registration response missing required client_id",
92
+ );
93
+ }
94
+ if (
95
+ !Array.isArray(data.redirect_uris) ||
96
+ data.redirect_uris.some((u) => typeof u !== "string")
97
+ ) {
98
+ throw new Error(
99
+ "Dynamic client registration response missing valid redirect_uris array",
100
+ );
101
+ }
102
+
103
+ return {
104
+ clientId: data.client_id,
105
+ clientSecret:
106
+ typeof data.client_secret === "string" ? data.client_secret : undefined,
107
+ redirectUris: data.redirect_uris as string[],
108
+ };
109
+ }