@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.
- package/README.md +26 -1
- package/dist/authorization-code-pkce.d.ts +40 -0
- package/dist/authorization-code-pkce.d.ts.map +1 -0
- package/dist/authorization-code-pkce.js +272 -0
- package/dist/authorization-code-pkce.js.map +1 -0
- package/dist/client-credentials.d.ts +18 -0
- package/dist/client-credentials.d.ts.map +1 -0
- package/dist/client-credentials.js +79 -0
- package/dist/client-credentials.js.map +1 -0
- package/dist/client-store.d.ts +37 -0
- package/dist/client-store.d.ts.map +1 -0
- package/dist/client-store.js +138 -0
- package/dist/client-store.js.map +1 -0
- package/dist/client.d.ts +113 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +217 -0
- package/dist/client.js.map +1 -0
- package/dist/config-dir.d.ts +3 -0
- package/dist/config-dir.d.ts.map +1 -0
- package/dist/config-dir.js +11 -0
- package/dist/config-dir.js.map +1 -0
- package/dist/dynamic-registration.d.ts +28 -0
- package/dist/dynamic-registration.d.ts.map +1 -0
- package/dist/dynamic-registration.js +56 -0
- package/dist/dynamic-registration.js.map +1 -0
- package/dist/generated/client/client.gen.d.ts +3 -0
- package/dist/generated/client/client.gen.d.ts.map +1 -0
- package/dist/generated/client/client.gen.js +217 -0
- package/dist/generated/client/client.gen.js.map +1 -0
- package/dist/generated/client/index.d.ts +11 -0
- package/dist/generated/client/index.d.ts.map +1 -0
- package/dist/generated/client/index.js +7 -0
- package/dist/generated/client/index.js.map +1 -0
- package/dist/generated/client/types.gen.d.ts +121 -0
- package/dist/generated/client/types.gen.d.ts.map +1 -0
- package/dist/generated/client/types.gen.js +3 -0
- package/dist/generated/client/types.gen.js.map +1 -0
- package/dist/generated/client/utils.gen.d.ts +38 -0
- package/dist/generated/client/utils.gen.d.ts.map +1 -0
- package/dist/generated/client/utils.gen.js +229 -0
- package/dist/generated/client/utils.gen.js.map +1 -0
- package/dist/generated/client.gen.d.ts +13 -0
- package/dist/generated/client.gen.d.ts.map +1 -0
- package/dist/generated/client.gen.js +4 -0
- package/dist/generated/client.gen.js.map +1 -0
- package/dist/generated/core/auth.gen.d.ts +26 -0
- package/dist/generated/core/auth.gen.d.ts.map +1 -0
- package/dist/generated/core/auth.gen.js +15 -0
- package/dist/generated/core/auth.gen.js.map +1 -0
- package/dist/generated/core/bodySerializer.gen.d.ts +26 -0
- package/dist/generated/core/bodySerializer.gen.d.ts.map +1 -0
- package/dist/generated/core/bodySerializer.gen.js +58 -0
- package/dist/generated/core/bodySerializer.gen.js.map +1 -0
- package/dist/generated/core/params.gen.d.ts +44 -0
- package/dist/generated/core/params.gen.d.ts.map +1 -0
- package/dist/generated/core/params.gen.js +110 -0
- package/dist/generated/core/params.gen.js.map +1 -0
- package/dist/generated/core/pathSerializer.gen.d.ts +34 -0
- package/dist/generated/core/pathSerializer.gen.d.ts.map +1 -0
- package/dist/generated/core/pathSerializer.gen.js +107 -0
- package/dist/generated/core/pathSerializer.gen.js.map +1 -0
- package/dist/generated/core/queryKeySerializer.gen.d.ts +19 -0
- package/dist/generated/core/queryKeySerializer.gen.d.ts.map +1 -0
- package/dist/generated/core/queryKeySerializer.gen.js +93 -0
- package/dist/generated/core/queryKeySerializer.gen.js.map +1 -0
- package/dist/generated/core/serverSentEvents.gen.d.ts +72 -0
- package/dist/generated/core/serverSentEvents.gen.d.ts.map +1 -0
- package/dist/generated/core/serverSentEvents.gen.js +133 -0
- package/dist/generated/core/serverSentEvents.gen.js.map +1 -0
- package/dist/generated/core/types.gen.d.ts +84 -0
- package/dist/generated/core/types.gen.d.ts.map +1 -0
- package/dist/generated/core/types.gen.js +3 -0
- package/dist/generated/core/types.gen.js.map +1 -0
- package/dist/generated/core/utils.gen.d.ts +20 -0
- package/dist/generated/core/utils.gen.d.ts.map +1 -0
- package/dist/generated/core/utils.gen.js +88 -0
- package/dist/generated/core/utils.gen.js.map +1 -0
- package/dist/generated/enum-values.gen.d.ts +331 -0
- package/dist/generated/enum-values.gen.d.ts.map +1 -0
- package/dist/generated/enum-values.gen.js +332 -0
- package/dist/generated/enum-values.gen.js.map +1 -0
- package/dist/generated/file-schemas.gen.d.ts +14 -0
- package/dist/generated/file-schemas.gen.d.ts.map +1 -0
- package/dist/generated/file-schemas.gen.js +3786 -0
- package/dist/generated/file-schemas.gen.js.map +1 -0
- package/dist/generated/index.d.ts +3 -0
- package/dist/generated/index.d.ts.map +1 -0
- package/dist/generated/index.js +3 -0
- package/dist/generated/index.js.map +1 -0
- package/dist/generated/sdk.gen.d.ts +1713 -0
- package/dist/generated/sdk.gen.d.ts.map +1 -0
- package/dist/generated/sdk.gen.js +10574 -0
- package/dist/generated/sdk.gen.js.map +1 -0
- package/dist/generated/spec-source.gen.d.ts +8 -0
- package/dist/generated/spec-source.gen.d.ts.map +1 -0
- package/dist/generated/spec-source.gen.js +9 -0
- package/dist/generated/spec-source.gen.js.map +1 -0
- package/dist/generated/types.gen.d.ts +30382 -0
- package/dist/generated/types.gen.d.ts.map +1 -0
- package/dist/generated/types.gen.js +3 -0
- package/dist/generated/types.gen.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth-request-error.d.ts +26 -0
- package/dist/oauth-request-error.d.ts.map +1 -0
- package/dist/oauth-request-error.js +47 -0
- package/dist/oauth-request-error.js.map +1 -0
- package/dist/refresh-token.d.ts +50 -0
- package/dist/refresh-token.d.ts.map +1 -0
- package/dist/refresh-token.js +83 -0
- package/dist/refresh-token.js.map +1 -0
- package/dist/token-store.d.ts +38 -0
- package/dist/token-store.d.ts.map +1 -0
- package/dist/token-store.js +195 -0
- package/dist/token-store.js.map +1 -0
- package/openapi/openapi.json +128387 -0
- package/package.json +66 -4
- package/src/__tests__/authorization-code-pkce.test.ts +245 -0
- package/src/__tests__/client-credentials.test.ts +360 -0
- package/src/__tests__/client-store.test.ts +139 -0
- package/src/__tests__/client.test.ts +529 -0
- package/src/__tests__/config-dir.test.ts +22 -0
- package/src/__tests__/dynamic-registration.test.ts +181 -0
- package/src/__tests__/oauth-request-error.test.ts +148 -0
- package/src/__tests__/refresh-token.test.ts +206 -0
- package/src/__tests__/token-store.test.ts +449 -0
- package/src/authorization-code-pkce.ts +417 -0
- package/src/client-credentials.ts +127 -0
- package/src/client-store.ts +182 -0
- package/src/client.ts +261 -0
- package/src/config-dir.ts +12 -0
- package/src/dynamic-registration.ts +109 -0
- package/src/generated/client/client.gen.ts +277 -0
- package/src/generated/client/index.ts +27 -0
- package/src/generated/client/types.gen.ts +218 -0
- package/src/generated/client/utils.gen.ts +316 -0
- package/src/generated/client.gen.ts +16 -0
- package/src/generated/core/auth.gen.ts +48 -0
- package/src/generated/core/bodySerializer.gen.ts +82 -0
- package/src/generated/core/params.gen.ts +178 -0
- package/src/generated/core/pathSerializer.gen.ts +171 -0
- package/src/generated/core/queryKeySerializer.gen.ts +117 -0
- package/src/generated/core/serverSentEvents.gen.ts +242 -0
- package/src/generated/core/types.gen.ts +110 -0
- package/src/generated/core/utils.gen.ts +140 -0
- package/src/generated/enum-values.gen.ts +332 -0
- package/src/generated/file-schemas.gen.ts +3800 -0
- package/src/generated/index.ts +4 -0
- package/src/generated/sdk.gen.ts +10992 -0
- package/src/generated/spec-source.gen.ts +9 -0
- package/src/generated/types.gen.ts +32415 -0
- package/src/index.ts +55 -0
- package/src/oauth-request-error.ts +75 -0
- package/src/refresh-token.ts +142 -0
- package/src/token-store.ts +252 -0
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
1
|
# @perpetualsystems/typescript-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript SDK for the Perpetual Systems API, generated from its OpenAPI specification. It runs on Node 20.3 or later and on Bun.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @perpetualsystems/typescript-sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```typescript
|
|
10
|
+
import {
|
|
11
|
+
PerpetualClient,
|
|
12
|
+
usersGetCurrent,
|
|
13
|
+
} from "@perpetualsystems/typescript-sdk";
|
|
14
|
+
|
|
15
|
+
const perpetual = new PerpetualClient({
|
|
16
|
+
endpoint: "https://your-deployment.perpetualsystems.com",
|
|
17
|
+
});
|
|
18
|
+
await perpetual.login("your@email.com", "your-password");
|
|
19
|
+
|
|
20
|
+
const user = await usersGetCurrent({
|
|
21
|
+
client: perpetual.client,
|
|
22
|
+
headers: perpetual.getAuthHeaders(),
|
|
23
|
+
throwOnError: true,
|
|
24
|
+
});
|
|
25
|
+
console.log(`Logged in as ${user.data!.displayName}`);
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
OAuth client credentials, the authorization code flow and the full API reference are in the [repository README](https://github.com/perpetualsystems/typescript-sdk#readme). The `perpetual` CLI is published as [`@perpetualsystems/cli`](https://www.npmjs.com/package/@perpetualsystems/cli).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export interface AuthorizationCodePkceOptions {
|
|
2
|
+
endpoint: string;
|
|
3
|
+
/** OAuth client_id (typically obtained via dynamic registration). */
|
|
4
|
+
clientId: string;
|
|
5
|
+
/** Optional client_secret. PKCE alone is sufficient for public clients,
|
|
6
|
+
* but the Perpetual backend may issue a secret on registration; if so
|
|
7
|
+
* it must be sent on the token exchange. */
|
|
8
|
+
clientSecret?: string;
|
|
9
|
+
/** Loopback redirect URI registered with the authorization server.
|
|
10
|
+
* The CLI must listen on the host:port specified here. */
|
|
11
|
+
redirectUri: string;
|
|
12
|
+
/** Optional space-separated scopes. */
|
|
13
|
+
scope?: string;
|
|
14
|
+
/** Override fetch for testing */
|
|
15
|
+
_fetch?: typeof fetch;
|
|
16
|
+
/** Override browser open for testing */
|
|
17
|
+
_openUrl?: (url: string) => Promise<void>;
|
|
18
|
+
/** Where to write user-facing progress messages (defaults to stderr). */
|
|
19
|
+
log?: (message: string) => void;
|
|
20
|
+
/** Cap how long we wait for the user to complete the browser flow. */
|
|
21
|
+
timeoutMs?: number;
|
|
22
|
+
/** Limit for the token exchange request itself. */
|
|
23
|
+
requestTimeoutMs?: number;
|
|
24
|
+
}
|
|
25
|
+
export interface AuthorizationCodePkceResult {
|
|
26
|
+
token: string;
|
|
27
|
+
refreshToken?: string;
|
|
28
|
+
expiresIn?: number;
|
|
29
|
+
tokenType: string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Execute the OAuth 2.0 Authorization Code flow with PKCE (RFC 6749 §4.1
|
|
33
|
+
* + RFC 7636), opening the user's browser to authorize and catching the
|
|
34
|
+
* redirect on a localhost loopback per RFC 8252.
|
|
35
|
+
*
|
|
36
|
+
* Replaces the prior device-code flow which the Perpetual backend no
|
|
37
|
+
* longer supports.
|
|
38
|
+
*/
|
|
39
|
+
export declare function executeAuthorizationCodePkce(options: AuthorizationCodePkceOptions): Promise<AuthorizationCodePkceResult>;
|
|
40
|
+
//# sourceMappingURL=authorization-code-pkce.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authorization-code-pkce.d.ts","sourceRoot":"","sources":["../src/authorization-code-pkce.ts"],"names":[],"mappings":"AAWA,MAAM,WAAW,4BAA4B;IAC3C,QAAQ,EAAE,MAAM,CAAC;IACjB,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAC;IACjB;;iDAE6C;IAC7C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;+DAC2D;IAC3D,WAAW,EAAE,MAAM,CAAC;IACpB,uCAAuC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,iCAAiC;IACjC,MAAM,CAAC,EAAE,OAAO,KAAK,CAAC;IACtB,wCAAwC;IACxC,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1C,yEAAyE;IACzE,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IAChC,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,mDAAmD;IACnD,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,2BAA2B;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB;AA4ND;;;;;;;GAOG;AACH,wBAAsB,4BAA4B,CAChD,OAAO,EAAE,4BAA4B,GACpC,OAAO,CAAC,2BAA2B,CAAC,CAiJtC"}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { normalizeEndpoint } from "./token-store.js";
|
|
4
|
+
import { OAUTH_REQUEST_TIMEOUT_MS, oauthHttpError, oauthTransportError, readOAuthBody, } from "./oauth-request-error.js";
|
|
5
|
+
const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes — generous for SSO flows
|
|
6
|
+
function base64url(buf) {
|
|
7
|
+
return buf
|
|
8
|
+
.toString("base64")
|
|
9
|
+
.replace(/=/g, "")
|
|
10
|
+
.replace(/\+/g, "-")
|
|
11
|
+
.replace(/\//g, "_");
|
|
12
|
+
}
|
|
13
|
+
function generatePkcePair() {
|
|
14
|
+
// 32 random bytes → ~43 base64url chars (within RFC 7636 §4.1 length range)
|
|
15
|
+
const verifier = base64url(randomBytes(32));
|
|
16
|
+
const challenge = base64url(createHash("sha256").update(verifier).digest());
|
|
17
|
+
return { verifier, challenge };
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Start a one-shot localhost HTTP server that resolves with the OAuth
|
|
21
|
+
* callback's code+state. Guards against double-resolve from kept-alive
|
|
22
|
+
* connections delivering a second framed request after the first /callback
|
|
23
|
+
* hit, and against late server-error events firing after we've already
|
|
24
|
+
* settled. Closes the socket forcibly after responding so a misbehaving
|
|
25
|
+
* client cannot pipeline another request on the same connection.
|
|
26
|
+
*/
|
|
27
|
+
function awaitCallback(server, expectedState, timeoutMs) {
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
let settled = false;
|
|
30
|
+
const settle = (action) => {
|
|
31
|
+
if (settled)
|
|
32
|
+
return;
|
|
33
|
+
settled = true;
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
server.removeAllListeners("request");
|
|
36
|
+
server.removeAllListeners("error");
|
|
37
|
+
server.close();
|
|
38
|
+
action();
|
|
39
|
+
};
|
|
40
|
+
const timer = setTimeout(() => {
|
|
41
|
+
settle(() => reject(new Error(`Authorization timed out after ${Math.round(timeoutMs / 1000)}s. ` +
|
|
42
|
+
"Re-run the command and complete the browser flow.")));
|
|
43
|
+
}, timeoutMs);
|
|
44
|
+
server.on("request", (req, res) => {
|
|
45
|
+
// Surface socket errors instead of letting them become uncaught
|
|
46
|
+
// exceptions when the client disconnects mid-response.
|
|
47
|
+
req.on("error", () => { });
|
|
48
|
+
res.on("error", () => { });
|
|
49
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
50
|
+
// Only handle /callback; ignore favicon and other browser noise.
|
|
51
|
+
if (url.pathname !== "/callback") {
|
|
52
|
+
res.writeHead(404).end();
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
// Guard against late re-entry: if we've already settled, just close
|
|
56
|
+
// the connection cleanly.
|
|
57
|
+
if (settled) {
|
|
58
|
+
res.writeHead(410).end();
|
|
59
|
+
req.socket.destroy();
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const error = url.searchParams.get("error");
|
|
63
|
+
const errorDescription = url.searchParams.get("error_description");
|
|
64
|
+
const code = url.searchParams.get("code");
|
|
65
|
+
const state = url.searchParams.get("state");
|
|
66
|
+
const respond = (status, html) => {
|
|
67
|
+
res.writeHead(status, {
|
|
68
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
69
|
+
"Cache-Control": "no-store",
|
|
70
|
+
"X-Content-Type-Options": "nosniff",
|
|
71
|
+
});
|
|
72
|
+
res.end(html, () => {
|
|
73
|
+
// Forcibly close the socket so kept-alive can't pipeline another
|
|
74
|
+
// request that re-enters this handler post-settle.
|
|
75
|
+
req.socket.destroy();
|
|
76
|
+
});
|
|
77
|
+
};
|
|
78
|
+
if (error) {
|
|
79
|
+
respond(400, `<!doctype html><html><body style="font-family:sans-serif;padding:2em">` +
|
|
80
|
+
`<h1>Authorization failed</h1>` +
|
|
81
|
+
`<p>${escapeHtml(error)}: ${escapeHtml(errorDescription ?? "")}</p>` +
|
|
82
|
+
`<p>You may close this window and return to the terminal.</p>` +
|
|
83
|
+
`</body></html>`);
|
|
84
|
+
settle(() => reject(new Error(`Authorization server returned error: ${error}${errorDescription ? `: ${errorDescription}` : ""}`)));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (!code || !state) {
|
|
88
|
+
respond(400, `<!doctype html><html><body><h1>Invalid callback</h1></body></html>`);
|
|
89
|
+
settle(() => reject(new Error("Authorization callback missing required code or state")));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
if (state !== expectedState) {
|
|
93
|
+
// CSRF guard: state must match what we sent.
|
|
94
|
+
respond(400, `<!doctype html><html><body><h1>State mismatch</h1></body></html>`);
|
|
95
|
+
settle(() => reject(new Error("Authorization callback state does not match -- possible CSRF; aborting")));
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
respond(200, `<!doctype html><html><body style="font-family:sans-serif;padding:2em">` +
|
|
99
|
+
`<h1>Authorization complete</h1>` +
|
|
100
|
+
`<p>You may close this window and return to the terminal.</p>` +
|
|
101
|
+
`</body></html>`);
|
|
102
|
+
settle(() => resolve({ code, state }));
|
|
103
|
+
});
|
|
104
|
+
server.once("error", (e) => {
|
|
105
|
+
settle(() => reject(e));
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
function escapeHtml(s) {
|
|
110
|
+
return s
|
|
111
|
+
.replace(/&/g, "&")
|
|
112
|
+
.replace(/</g, "<")
|
|
113
|
+
.replace(/>/g, ">")
|
|
114
|
+
.replace(/"/g, """);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Listen on a loopback port matching `redirectUri`. If the URI has port 0,
|
|
118
|
+
* bind to a random free port and return a URI with the assigned port.
|
|
119
|
+
*
|
|
120
|
+
* Returns the server (already listening) plus the redirect URI to use,
|
|
121
|
+
* which may differ from the input when port 0 was requested.
|
|
122
|
+
*/
|
|
123
|
+
async function startLoopbackServer(redirectUri) {
|
|
124
|
+
const url = new URL(redirectUri);
|
|
125
|
+
if (url.hostname !== "127.0.0.1" && url.hostname !== "localhost") {
|
|
126
|
+
throw new Error(`redirectUri must use loopback host (127.0.0.1 or localhost); got "${url.hostname}"`);
|
|
127
|
+
}
|
|
128
|
+
// Reject non-http schemes: we serve plaintext HTTP locally. An https://
|
|
129
|
+
// URI would cause the browser to attempt TLS to our plaintext server
|
|
130
|
+
// and fail with a confusing protocol error mid-flow.
|
|
131
|
+
if (url.protocol !== "http:") {
|
|
132
|
+
throw new Error(`redirectUri must use http:// for loopback (we serve plaintext); got "${url.protocol}"`);
|
|
133
|
+
}
|
|
134
|
+
// Enforce the /callback path: the request handler only matches that
|
|
135
|
+
// path, so registering anything else with the AS produces a callback
|
|
136
|
+
// that we'd 404 and time out on.
|
|
137
|
+
if (url.pathname !== "/callback") {
|
|
138
|
+
throw new Error(`redirectUri path must be /callback (the SDK only handles that path); got "${url.pathname}"`);
|
|
139
|
+
}
|
|
140
|
+
const server = createServer();
|
|
141
|
+
const port = url.port === "" || url.port === "0" ? 0 : Number(url.port);
|
|
142
|
+
await new Promise((resolve, reject) => {
|
|
143
|
+
const onError = (e) => reject(e);
|
|
144
|
+
server.once("error", onError);
|
|
145
|
+
server.listen(port, url.hostname, () => {
|
|
146
|
+
server.removeListener("error", onError);
|
|
147
|
+
resolve();
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
const addr = server.address();
|
|
151
|
+
url.port = String(addr.port);
|
|
152
|
+
return { server, redirectUri: url.toString() };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Execute the OAuth 2.0 Authorization Code flow with PKCE (RFC 6749 §4.1
|
|
156
|
+
* + RFC 7636), opening the user's browser to authorize and catching the
|
|
157
|
+
* redirect on a localhost loopback per RFC 8252.
|
|
158
|
+
*
|
|
159
|
+
* Replaces the prior device-code flow which the Perpetual backend no
|
|
160
|
+
* longer supports.
|
|
161
|
+
*/
|
|
162
|
+
export async function executeAuthorizationCodePkce(options) {
|
|
163
|
+
const { endpoint, clientId, clientSecret, redirectUri, scope, _fetch: fetchFn = fetch, _openUrl, log = (msg) => process.stderr.write(msg), timeoutMs = DEFAULT_TIMEOUT_MS, requestTimeoutMs = OAUTH_REQUEST_TIMEOUT_MS, } = options;
|
|
164
|
+
const normalizedEndpoint = normalizeEndpoint(endpoint);
|
|
165
|
+
const { verifier, challenge } = generatePkcePair();
|
|
166
|
+
const state = base64url(randomBytes(16));
|
|
167
|
+
const { server, redirectUri: actualRedirectUri } = await startLoopbackServer(redirectUri);
|
|
168
|
+
try {
|
|
169
|
+
const authorizeUrl = new URL(`${normalizedEndpoint}/api/oauth/authorize`);
|
|
170
|
+
authorizeUrl.searchParams.set("response_type", "code");
|
|
171
|
+
authorizeUrl.searchParams.set("client_id", clientId);
|
|
172
|
+
authorizeUrl.searchParams.set("redirect_uri", actualRedirectUri);
|
|
173
|
+
authorizeUrl.searchParams.set("code_challenge", challenge);
|
|
174
|
+
authorizeUrl.searchParams.set("code_challenge_method", "S256");
|
|
175
|
+
authorizeUrl.searchParams.set("state", state);
|
|
176
|
+
if (scope)
|
|
177
|
+
authorizeUrl.searchParams.set("scope", scope);
|
|
178
|
+
const authorizeUrlStr = authorizeUrl.toString();
|
|
179
|
+
// Arm the callback listener BEFORE opening the browser. A fast SSO
|
|
180
|
+
// redirect (e.g. when the user is already signed in) can deliver the
|
|
181
|
+
// /callback hit microseconds after the browser launches; if the
|
|
182
|
+
// listener weren't yet attached, that request would 404 silently and
|
|
183
|
+
// we'd wait the full timeout.
|
|
184
|
+
const callbackPromise = awaitCallback(server, state, timeoutMs);
|
|
185
|
+
log("Opening browser for authorization...\n");
|
|
186
|
+
log(` ACTION REQUIRED if browser doesn't open -- visit this URL manually:\n ${authorizeUrlStr}\n\n`);
|
|
187
|
+
// Best-effort browser open; the URL is also printed above.
|
|
188
|
+
try {
|
|
189
|
+
if (_openUrl) {
|
|
190
|
+
await _openUrl(authorizeUrlStr);
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
const openModule = await import("open");
|
|
194
|
+
await openModule.default(authorizeUrlStr);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch (openError) {
|
|
198
|
+
const detail = openError instanceof Error ? openError.message : String(openError);
|
|
199
|
+
log(` (Could not open browser automatically: ${detail}. Please visit the URL above.)\n`);
|
|
200
|
+
}
|
|
201
|
+
log("Waiting for authorization...\n");
|
|
202
|
+
const callback = await callbackPromise;
|
|
203
|
+
// Exchange authorization code for token (RFC 6749 §4.1.3).
|
|
204
|
+
const tokenUrl = `${normalizedEndpoint}/api/oauth/token`;
|
|
205
|
+
const body = new URLSearchParams({
|
|
206
|
+
grant_type: "authorization_code",
|
|
207
|
+
code: callback.code,
|
|
208
|
+
redirect_uri: actualRedirectUri,
|
|
209
|
+
client_id: clientId,
|
|
210
|
+
code_verifier: verifier,
|
|
211
|
+
});
|
|
212
|
+
if (clientSecret)
|
|
213
|
+
body.set("client_secret", clientSecret);
|
|
214
|
+
let response;
|
|
215
|
+
try {
|
|
216
|
+
response = await fetchFn(tokenUrl, {
|
|
217
|
+
method: "POST",
|
|
218
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
219
|
+
body: body.toString(),
|
|
220
|
+
signal: AbortSignal.timeout(requestTimeoutMs),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
catch (networkError) {
|
|
224
|
+
throw oauthTransportError("Token exchange", tokenUrl, networkError);
|
|
225
|
+
}
|
|
226
|
+
const text = await readOAuthBody("Token exchange", tokenUrl, response);
|
|
227
|
+
if (!response.ok) {
|
|
228
|
+
throw oauthHttpError("Token exchange", response, text);
|
|
229
|
+
}
|
|
230
|
+
let data;
|
|
231
|
+
try {
|
|
232
|
+
data = JSON.parse(text);
|
|
233
|
+
}
|
|
234
|
+
catch (parseError) {
|
|
235
|
+
const detail = parseError instanceof Error ? parseError.message : String(parseError);
|
|
236
|
+
throw new Error(`Token response is not valid JSON (${response.status}): ${text.slice(0, 200) || response.statusText} (${detail})`);
|
|
237
|
+
}
|
|
238
|
+
if (typeof data.access_token !== "string" || !data.access_token) {
|
|
239
|
+
throw new Error("Token response missing access_token");
|
|
240
|
+
}
|
|
241
|
+
const tokenType = typeof data.token_type === "string" ? data.token_type : "Bearer";
|
|
242
|
+
if (tokenType.toLowerCase() !== "bearer") {
|
|
243
|
+
throw new Error(`Unsupported token type: "${tokenType}". Only Bearer tokens are supported.`);
|
|
244
|
+
}
|
|
245
|
+
let expiresIn;
|
|
246
|
+
if (data.expires_in !== undefined) {
|
|
247
|
+
if (typeof data.expires_in === "number" &&
|
|
248
|
+
Number.isFinite(data.expires_in) &&
|
|
249
|
+
data.expires_in > 0) {
|
|
250
|
+
expiresIn = data.expires_in;
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
log(`Warning: token response contained invalid expires_in: ${JSON.stringify(data.expires_in)}, ignoring\n`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
token: data.access_token,
|
|
258
|
+
refreshToken: typeof data.refresh_token === "string" ? data.refresh_token : undefined,
|
|
259
|
+
expiresIn,
|
|
260
|
+
tokenType,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
finally {
|
|
264
|
+
// Defensive: awaitCallback closes on every code path, but we want to
|
|
265
|
+
// be sure the listener is gone if startup succeeded but the URL open
|
|
266
|
+
// step threw before awaitCallback was reached.
|
|
267
|
+
if (server.listening) {
|
|
268
|
+
server.close();
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
//# sourceMappingURL=authorization-code-pkce.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authorization-code-pkce.js","sourceRoot":"","sources":["../src/authorization-code-pkce.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,YAAY,EAAe,MAAM,WAAW,CAAC;AAEtD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EACL,wBAAwB,EACxB,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAkClC,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,qCAAqC;AAE/E,SAAS,SAAS,CAAC,GAAW;IAC5B,OAAO,GAAG;SACP,QAAQ,CAAC,QAAQ,CAAC;SAClB,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;SACjB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AACzB,CAAC;AAED,SAAS,gBAAgB;IACvB,4EAA4E;IAC5E,MAAM,QAAQ,GAAG,SAAS,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC;IAC5C,MAAM,SAAS,GAAG,SAAS,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5E,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC;AACjC,CAAC;AAOD;;;;;;;GAOG;AACH,SAAS,aAAa,CACpB,MAAc,EACd,aAAqB,EACrB,SAAiB;IAEjB,OAAO,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CAAC,SAAS,EAAE,CAAC;YACrB,MAAM,CAAC,KAAK,EAAE,CAAC;QACjB,CAAC;IACH,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface ClientCredentialsOptions {
|
|
2
|
+
endpoint: string;
|
|
3
|
+
clientId: string;
|
|
4
|
+
clientSecret: string;
|
|
5
|
+
/** Override fetch for testing */
|
|
6
|
+
_fetch?: typeof fetch;
|
|
7
|
+
requestTimeoutMs?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface ClientCredentialsResponse {
|
|
10
|
+
access_token: string;
|
|
11
|
+
token_type: string;
|
|
12
|
+
expires_in?: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Exchange client credentials for an access token (OAuth 2.0 Client Credentials Grant, RFC 6749 §4.4).
|
|
16
|
+
*/
|
|
17
|
+
export declare function exchangeClientCredentials(options: ClientCredentialsOptions): Promise<ClientCredentialsResponse>;
|
|
18
|
+
//# sourceMappingURL=client-credentials.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-credentials.d.ts","sourceRoot":"","sources":["../src/client-credentials.ts"],"names":[],"mappings":"AAQA,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,iCAAiC;IACjC,MAAM,CAAC,EAAE,OAAO,KAAK,CAAC;IACtB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,yBAAyB;IACxC,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC,CAkGpC"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { normalizeEndpoint } from "./token-store.js";
|
|
2
|
+
import { OAUTH_REQUEST_TIMEOUT_MS, oauthHttpError, oauthTransportError, readOAuthBody, } from "./oauth-request-error.js";
|
|
3
|
+
/**
|
|
4
|
+
* Exchange client credentials for an access token (OAuth 2.0 Client Credentials Grant, RFC 6749 §4.4).
|
|
5
|
+
*/
|
|
6
|
+
export async function exchangeClientCredentials(options) {
|
|
7
|
+
const { endpoint, clientId, clientSecret, _fetch: fetchFn = fetch, requestTimeoutMs = OAUTH_REQUEST_TIMEOUT_MS, } = options;
|
|
8
|
+
const url = `${normalizeEndpoint(endpoint)}/api/oauth/token`;
|
|
9
|
+
let response;
|
|
10
|
+
try {
|
|
11
|
+
response = await fetchFn(url, {
|
|
12
|
+
method: "POST",
|
|
13
|
+
// RFC 6749 §4.4.2 + §3.2 specify form-encoded request body for the
|
|
14
|
+
// token endpoint. The Perpetual backend rejects JSON bodies with
|
|
15
|
+
// "unsupported_grant_type" (the parser can't read the field).
|
|
16
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
17
|
+
body: new URLSearchParams({
|
|
18
|
+
grant_type: "client_credentials",
|
|
19
|
+
client_id: clientId,
|
|
20
|
+
client_secret: clientSecret,
|
|
21
|
+
}).toString(),
|
|
22
|
+
signal: AbortSignal.timeout(requestTimeoutMs),
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
catch (networkError) {
|
|
26
|
+
throw oauthTransportError("Client credentials exchange", url, networkError);
|
|
27
|
+
}
|
|
28
|
+
const body = await readOAuthBody("Client credentials exchange", url, response);
|
|
29
|
+
if (!response.ok) {
|
|
30
|
+
throw oauthHttpError("Client credentials exchange", response, body);
|
|
31
|
+
}
|
|
32
|
+
let data;
|
|
33
|
+
try {
|
|
34
|
+
data = JSON.parse(body);
|
|
35
|
+
}
|
|
36
|
+
catch (parseError) {
|
|
37
|
+
const detail = parseError instanceof Error ? parseError.message : String(parseError);
|
|
38
|
+
throw new Error(`Client credentials response is not valid JSON (${response.status}): ${body.slice(0, 200) || response.statusText} (${detail})`);
|
|
39
|
+
}
|
|
40
|
+
if (!data.access_token || typeof data.access_token !== "string") {
|
|
41
|
+
throw new Error("Client credentials response missing access_token");
|
|
42
|
+
}
|
|
43
|
+
// Validate token_type: must be "Bearer" (case-insensitive) if present
|
|
44
|
+
if (data.token_type) {
|
|
45
|
+
if (typeof data.token_type !== "string" ||
|
|
46
|
+
data.token_type.toLowerCase() !== "bearer") {
|
|
47
|
+
throw new Error(`Unsupported token type: "${data.token_type}". Only Bearer tokens are supported.`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// Validate expires_in if present: must be a finite positive number.
|
|
51
|
+
// Unlike requestDeviceCode (which throws on invalid values because they
|
|
52
|
+
// poison the polling deadline), here we already have the token so we
|
|
53
|
+
// log a warning and omit the invalid value.
|
|
54
|
+
let expiresIn;
|
|
55
|
+
if (data.expires_in !== undefined) {
|
|
56
|
+
if (typeof data.expires_in !== "number" ||
|
|
57
|
+
!Number.isFinite(data.expires_in) ||
|
|
58
|
+
data.expires_in <= 0) {
|
|
59
|
+
try {
|
|
60
|
+
process.stderr.write(`Warning: client credentials response contained invalid expires_in: ${JSON.stringify(data.expires_in)}, ignoring\n`);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
// Best-effort warning — don't let a broken stderr discard a valid token
|
|
64
|
+
}
|
|
65
|
+
expiresIn = undefined;
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
expiresIn = data.expires_in;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Ensure token_type is set (RFC 6749 §5.1 requires it, default to Bearer)
|
|
72
|
+
const result = {
|
|
73
|
+
access_token: data.access_token,
|
|
74
|
+
token_type: typeof data.token_type === "string" ? data.token_type : "Bearer",
|
|
75
|
+
...(expiresIn !== undefined ? { expires_in: expiresIn } : {}),
|
|
76
|
+
};
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=client-credentials.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-credentials.js","sourceRoot":"","sources":["../src/client-credentials.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EACL,wBAAwB,EACxB,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,0BAA0B,CAAC;AAiBlC;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,OAAiC;IAEjC,MAAM,EACJ,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,MAAM,EAAE,OAAO,GAAG,KAAK,EACvB,gBAAgB,GAAG,wBAAwB,GAC5C,GAAG,OAAO,CAAC;IAEZ,MAAM,GAAG,GAAG,GAAG,iBAAiB,CAAC,QAAQ,CAAC,kBAAkB,CAAC;IAC7D,IAAI,QAAkB,CAAC;IACvB,IAAI,CAAC;QACH,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE;YAC5B,MAAM,EAAE,MAAM;YACd,mEAAmE;YACnE,iEAAiE;YACjE,8DAA8D;YAC9D,OAAO,EAAE,EAAE,cAAc,EAAE,mCAAmC,EAAE;YAChE,IAAI,EAAE,IAAI,eAAe,CAAC;gBACxB,UAAU,EAAE,oBAAoB;gBAChC,SAAS,EAAE,QAAQ;gBACnB,aAAa,EAAE,YAAY;aAC5B,CAAC,CAAC,QAAQ,EAAE;YACb,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,gBAAgB,CAAC;SAC9C,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,YAAY,EAAE,CAAC;QACtB,MAAM,mBAAmB,CAAC,6BAA6B,EAAE,GAAG,EAAE,YAAY,CAAC,CAAC;IAC9E,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,aAAa,CAC9B,6BAA6B,EAC7B,GAAG,EACH,QAAQ,CACT,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;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AC,EACpB,CAAC;YACD,IAAI,CAAC;gBACH,OAAO,CAAC,MAAM,CAAC,KAAK,CAClB,sEAAsE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,cAAc,CACpH,CAAC;YACJ,CAAC;YAAC,MAAM,CAAC;gBACP,wEAAwE;YAC1E,CAAC;YACD,SAAS,GAAG,SAAS,CAAC;QACxB,CAAC;aAAM,CAAC;YACN,SAAS,GAAG,IAAI,CAAC,UAAU,CAAC;QAC9B,CAAC;IACH,CAAC;IAED,0EAA0E;IAC1E,MAAM,MAAM,GAA8B;QACxC,YAAY,EAAE,IAAI,CAAC,YAAY;QAC/B,UAAU,EACR,OAAO,IAAI,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ;QAClE,GAAG,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC9D,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A dynamically registered OAuth client (RFC 7591) cached locally so the
|
|
3
|
+
* CLI doesn't need to register a fresh client_id on every invocation.
|
|
4
|
+
*
|
|
5
|
+
* The Perpetual backend issues a client_secret on registration even for
|
|
6
|
+
* PKCE-only public clients; we cache it here because it's required on
|
|
7
|
+
* the token exchange.
|
|
8
|
+
*
|
|
9
|
+
* `redirectUri` is recorded at registration time and reused on subsequent
|
|
10
|
+
* runs so the loopback server binds to the same port. If the port turns
|
|
11
|
+
* out to be in use, the caller should re-register with a new port.
|
|
12
|
+
*/
|
|
13
|
+
export interface RegisteredClientRecord {
|
|
14
|
+
clientId: string;
|
|
15
|
+
clientSecret?: string;
|
|
16
|
+
redirectUri: string;
|
|
17
|
+
registeredAt: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Look up a previously registered OAuth client for the given endpoint.
|
|
21
|
+
* Returns undefined if no registration exists locally.
|
|
22
|
+
*/
|
|
23
|
+
export declare function getRegisteredClient(endpoint: string): RegisteredClientRecord | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Persist a registered OAuth client for the given endpoint. Overwrites
|
|
26
|
+
* any prior registration for the same endpoint.
|
|
27
|
+
*/
|
|
28
|
+
export declare function saveRegisteredClient(endpoint: string, record: Omit<RegisteredClientRecord, "registeredAt"> & {
|
|
29
|
+
registeredAt?: string;
|
|
30
|
+
}): void;
|
|
31
|
+
/**
|
|
32
|
+
* Remove the cached registration for the given endpoint. Useful when the
|
|
33
|
+
* registered redirect_uri's port becomes unavailable and the caller wants
|
|
34
|
+
* to force a re-registration.
|
|
35
|
+
*/
|
|
36
|
+
export declare function clearRegisteredClient(endpoint: string): void;
|
|
37
|
+
//# sourceMappingURL=client-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-store.d.ts","sourceRoot":"","sources":["../src/client-store.ts"],"names":[],"mappings":"AAaA;;;;;;;;;;;GAWG;AACH,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;CACtB;AA0GD;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,MAAM,GACf,sBAAsB,GAAG,SAAS,CAIpC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,IAAI,CAAC,sBAAsB,EAAE,cAAc,CAAC,GAAG;IACrD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GACA,IAAI,CAUN;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAO5D"}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { getConfigDir } from "./config-dir.js";
|
|
4
|
+
import { normalizeEndpoint } from "./token-store.js";
|
|
5
|
+
function getClientFilePath() {
|
|
6
|
+
return join(getConfigDir(), "oauth-clients.json");
|
|
7
|
+
}
|
|
8
|
+
function readClientFile() {
|
|
9
|
+
const filePath = getClientFilePath();
|
|
10
|
+
if (!existsSync(filePath))
|
|
11
|
+
return {};
|
|
12
|
+
let text;
|
|
13
|
+
try {
|
|
14
|
+
text = readFileSync(filePath, "utf-8");
|
|
15
|
+
}
|
|
16
|
+
catch (e) {
|
|
17
|
+
// Read failure (permission, I/O error) is NOT the same as "no cache".
|
|
18
|
+
// Surface it so the user sees the real cause instead of silently
|
|
19
|
+
// re-registering on every run.
|
|
20
|
+
process.stderr.write(`Warning: could not read OAuth client cache at ${filePath}: ` +
|
|
21
|
+
`${e instanceof Error ? e.message : String(e)}\n`);
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
try {
|
|
25
|
+
const parsed = JSON.parse(text);
|
|
26
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
27
|
+
return {};
|
|
28
|
+
// Validate each entry's shape. A partial-write or hand-edit that
|
|
29
|
+
// produces a wrong-typed entry would otherwise crash deep inside the
|
|
30
|
+
// OAuth flow with a confusing TypeError.
|
|
31
|
+
const file = {};
|
|
32
|
+
for (const [k, v] of Object.entries(parsed)) {
|
|
33
|
+
if (v &&
|
|
34
|
+
typeof v === "object" &&
|
|
35
|
+
typeof v.clientId === "string" &&
|
|
36
|
+
typeof v.redirectUri === "string") {
|
|
37
|
+
file[k] = v;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return file;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Parse failure: file is corrupt (e.g. partial write from a crash).
|
|
44
|
+
// Treat as empty so we re-register cleanly.
|
|
45
|
+
process.stderr.write(`Warning: OAuth client cache at ${filePath} is corrupt; ignoring.\n`);
|
|
46
|
+
return {};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Atomically write the client cache. Writes to `<path>.tmp` first then
|
|
51
|
+
* renames into place; POSIX rename is atomic so a process kill mid-write
|
|
52
|
+
* cannot leave a half-written file that would silently lose every cached
|
|
53
|
+
* registration on next read.
|
|
54
|
+
*
|
|
55
|
+
* NOTE: There is no advisory lock around read-modify-write. Two concurrent
|
|
56
|
+
* CLI invocations both registering at the same time will both succeed at
|
|
57
|
+
* the AS but only one client_id ends up in the cache. The other becomes
|
|
58
|
+
* an orphan at the AS until manually cleaned. Acceptable for the CLI's
|
|
59
|
+
* usage pattern; revisit if SDK consumers run many parallel registrations.
|
|
60
|
+
*/
|
|
61
|
+
function writeClientFile(data) {
|
|
62
|
+
const dir = getConfigDir();
|
|
63
|
+
if (!existsSync(dir)) {
|
|
64
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
65
|
+
}
|
|
66
|
+
const filePath = getClientFilePath();
|
|
67
|
+
const tmpPath = `${filePath}.tmp`;
|
|
68
|
+
try {
|
|
69
|
+
writeFileSync(tmpPath, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
70
|
+
try {
|
|
71
|
+
chmodSync(tmpPath, 0o600);
|
|
72
|
+
}
|
|
73
|
+
catch (e) {
|
|
74
|
+
// Chmod failures matter on a credentials file: surface them so a
|
|
75
|
+
// mis-umask'd write doesn't leave the secret world-readable silently.
|
|
76
|
+
process.stderr.write(`Warning: could not chmod ${tmpPath} to 0600: ` +
|
|
77
|
+
`${e instanceof Error ? e.message : String(e)}\n`);
|
|
78
|
+
}
|
|
79
|
+
renameSync(tmpPath, filePath);
|
|
80
|
+
try {
|
|
81
|
+
chmodSync(dirname(filePath), 0o700);
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
process.stderr.write(`Warning: could not chmod ${dirname(filePath)} to 0700: ` +
|
|
85
|
+
`${e instanceof Error ? e.message : String(e)}\n`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch (writeError) {
|
|
89
|
+
// Clean up the staging file on failure so a transient I/O error
|
|
90
|
+
// doesn't leave a stray credentials .tmp around forever.
|
|
91
|
+
try {
|
|
92
|
+
if (existsSync(tmpPath))
|
|
93
|
+
unlinkSync(tmpPath);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
/* best effort */
|
|
97
|
+
}
|
|
98
|
+
throw writeError;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Look up a previously registered OAuth client for the given endpoint.
|
|
103
|
+
* Returns undefined if no registration exists locally.
|
|
104
|
+
*/
|
|
105
|
+
export function getRegisteredClient(endpoint) {
|
|
106
|
+
const key = normalizeEndpoint(endpoint);
|
|
107
|
+
const file = readClientFile();
|
|
108
|
+
return file[key];
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Persist a registered OAuth client for the given endpoint. Overwrites
|
|
112
|
+
* any prior registration for the same endpoint.
|
|
113
|
+
*/
|
|
114
|
+
export function saveRegisteredClient(endpoint, record) {
|
|
115
|
+
const key = normalizeEndpoint(endpoint);
|
|
116
|
+
const file = readClientFile();
|
|
117
|
+
file[key] = {
|
|
118
|
+
clientId: record.clientId,
|
|
119
|
+
clientSecret: record.clientSecret,
|
|
120
|
+
redirectUri: record.redirectUri,
|
|
121
|
+
registeredAt: record.registeredAt ?? new Date().toISOString(),
|
|
122
|
+
};
|
|
123
|
+
writeClientFile(file);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Remove the cached registration for the given endpoint. Useful when the
|
|
127
|
+
* registered redirect_uri's port becomes unavailable and the caller wants
|
|
128
|
+
* to force a re-registration.
|
|
129
|
+
*/
|
|
130
|
+
export function clearRegisteredClient(endpoint) {
|
|
131
|
+
const key = normalizeEndpoint(endpoint);
|
|
132
|
+
const file = readClientFile();
|
|
133
|
+
if (key in file) {
|
|
134
|
+
delete file[key];
|
|
135
|
+
writeClientFile(file);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
//# sourceMappingURL=client-store.js.map
|