@tracken/cli 0.0.0-stage → 0.2.0
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/CHANGELOG.md +376 -0
- package/LICENSE +21 -0
- package/README.md +307 -2
- package/dist/bin/tracken.d.ts +2 -0
- package/dist/bin/tracken.js +5 -0
- package/dist/cli/args.d.ts +17 -0
- package/dist/cli/args.js +114 -0
- package/dist/cli/commands/api.d.ts +2 -0
- package/dist/cli/commands/api.js +73 -0
- package/dist/cli/commands/auth.d.ts +8 -0
- package/dist/cli/commands/auth.js +141 -0
- package/dist/cli/commands/mcp.d.ts +19 -0
- package/dist/cli/commands/mcp.js +89 -0
- package/dist/cli/commands/org.d.ts +24 -0
- package/dist/cli/commands/org.js +123 -0
- package/dist/cli/context.d.ts +54 -0
- package/dist/cli/context.js +135 -0
- package/dist/cli/execute.d.ts +16 -0
- package/dist/cli/execute.js +112 -0
- package/dist/cli/help.d.ts +8 -0
- package/dist/cli/help.js +153 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +114 -0
- package/dist/cli/operation-args.d.ts +25 -0
- package/dist/cli/operation-args.js +245 -0
- package/dist/core/auth/oauth.d.ts +39 -0
- package/dist/core/auth/oauth.js +102 -0
- package/dist/core/auth/scopes.d.ts +19 -0
- package/dist/core/auth/scopes.js +49 -0
- package/dist/core/auth/secret-store.d.ts +60 -0
- package/dist/core/auth/secret-store.js +141 -0
- package/dist/core/auth/session.d.ts +75 -0
- package/dist/core/auth/session.js +200 -0
- package/dist/core/catalog.d.ts +12 -0
- package/dist/core/catalog.js +33 -0
- package/dist/core/client.d.ts +22 -0
- package/dist/core/client.js +45 -0
- package/dist/core/config.d.ts +27 -0
- package/dist/core/config.js +109 -0
- package/dist/core/environments.d.ts +21 -0
- package/dist/core/environments.js +53 -0
- package/dist/core/errors.d.ts +87 -0
- package/dist/core/errors.js +226 -0
- package/dist/core/index.d.ts +21 -0
- package/dist/core/index.js +22 -0
- package/dist/core/jobs.d.ts +15 -0
- package/dist/core/jobs.js +19 -0
- package/dist/core/operations.d.ts +108 -0
- package/dist/core/operations.js +7 -0
- package/dist/core/output/format.d.ts +19 -0
- package/dist/core/output/format.js +62 -0
- package/dist/core/output/render.d.ts +53 -0
- package/dist/core/output/render.js +229 -0
- package/dist/core/pagination.d.ts +2 -0
- package/dist/core/pagination.js +3 -0
- package/dist/core/request.d.ts +29 -0
- package/dist/core/request.js +109 -0
- package/dist/core/version.d.ts +10 -0
- package/dist/core/version.js +13 -0
- package/dist/generated/mcp-tools.d.ts +2 -0
- package/dist/generated/mcp-tools.js +5937 -0
- package/dist/generated/operations.d.ts +4 -0
- package/dist/generated/operations.js +17701 -0
- package/dist/mcp/errors.d.ts +34 -0
- package/dist/mcp/errors.js +91 -0
- package/dist/mcp/live.d.ts +3 -0
- package/dist/mcp/live.js +5 -0
- package/dist/mcp/prompts.d.ts +23 -0
- package/dist/mcp/prompts.js +101 -0
- package/dist/mcp/resources.d.ts +25 -0
- package/dist/mcp/resources.js +125 -0
- package/dist/mcp/server.d.ts +20 -0
- package/dist/mcp/server.js +59 -0
- package/dist/mcp/session.d.ts +60 -0
- package/dist/mcp/session.js +105 -0
- package/dist/mcp/tools.d.ts +17 -0
- package/dist/mcp/tools.js +181 -0
- package/dist/mcp/types.d.ts +25 -0
- package/dist/mcp/types.js +2 -0
- package/node_modules/@tracken/sdk/LICENSE +21 -0
- package/node_modules/@tracken/sdk/README.md +72 -0
- package/node_modules/@tracken/sdk/SOURCE.json +10 -0
- package/node_modules/@tracken/sdk/dist/client.d.ts +94 -0
- package/node_modules/@tracken/sdk/dist/client.js +258 -0
- package/node_modules/@tracken/sdk/dist/credentials.d.ts +60 -0
- package/node_modules/@tracken/sdk/dist/credentials.js +122 -0
- package/node_modules/@tracken/sdk/dist/decimal.d.ts +20 -0
- package/node_modules/@tracken/sdk/dist/decimal.js +67 -0
- package/node_modules/@tracken/sdk/dist/environments.d.ts +14 -0
- package/node_modules/@tracken/sdk/dist/environments.js +16 -0
- package/node_modules/@tracken/sdk/dist/errors.d.ts +126 -0
- package/node_modules/@tracken/sdk/dist/errors.js +165 -0
- package/node_modules/@tracken/sdk/dist/generated/operations.d.ts +1955 -0
- package/node_modules/@tracken/sdk/dist/generated/operations.js +2745 -0
- package/node_modules/@tracken/sdk/dist/generated/schema.d.ts +17988 -0
- package/node_modules/@tracken/sdk/dist/generated/schema.js +5 -0
- package/node_modules/@tracken/sdk/dist/index.d.ts +27 -0
- package/node_modules/@tracken/sdk/dist/index.js +24 -0
- package/node_modules/@tracken/sdk/dist/jobs.d.ts +23 -0
- package/node_modules/@tracken/sdk/dist/jobs.js +80 -0
- package/node_modules/@tracken/sdk/dist/operations.d.ts +23 -0
- package/node_modules/@tracken/sdk/dist/operations.js +2 -0
- package/node_modules/@tracken/sdk/dist/pagination.d.ts +19 -0
- package/node_modules/@tracken/sdk/dist/pagination.js +49 -0
- package/node_modules/@tracken/sdk/dist/request.d.ts +27 -0
- package/node_modules/@tracken/sdk/dist/request.js +10 -0
- package/node_modules/@tracken/sdk/dist/runtime.d.ts +22 -0
- package/node_modules/@tracken/sdk/dist/runtime.js +33 -0
- package/node_modules/@tracken/sdk/dist/tracken.d.ts +74 -0
- package/node_modules/@tracken/sdk/dist/tracken.js +203 -0
- package/node_modules/@tracken/sdk/dist/types.d.ts +130 -0
- package/node_modules/@tracken/sdk/dist/types.js +1 -0
- package/node_modules/@tracken/sdk/dist/version.d.ts +2 -0
- package/node_modules/@tracken/sdk/dist/version.js +2 -0
- package/node_modules/@tracken/sdk/package.json +42 -0
- package/node_modules/openapi-fetch/CHANGELOG.md +565 -0
- package/node_modules/openapi-fetch/CONTRIBUTING.md +102 -0
- package/node_modules/openapi-fetch/LICENSE +21 -0
- package/node_modules/openapi-fetch/README.md +122 -0
- package/node_modules/openapi-fetch/dist/index.cjs +547 -0
- package/node_modules/openapi-fetch/dist/index.cjs.map +1 -0
- package/node_modules/openapi-fetch/dist/index.d.cts +337 -0
- package/node_modules/openapi-fetch/dist/index.d.mts +335 -0
- package/node_modules/openapi-fetch/dist/index.d.ts +337 -0
- package/node_modules/openapi-fetch/dist/index.mjs +531 -0
- package/node_modules/openapi-fetch/dist/index.mjs.map +1 -0
- package/node_modules/openapi-fetch/package.json +77 -0
- package/node_modules/openapi-fetch/src/index.d.ts +345 -0
- package/node_modules/openapi-fetch/src/index.js +689 -0
- package/node_modules/openapi-typescript-helpers/CHANGELOG.md +98 -0
- package/node_modules/openapi-typescript-helpers/LICENSE +21 -0
- package/node_modules/openapi-typescript-helpers/README.md +5 -0
- package/node_modules/openapi-typescript-helpers/dist/index.cjs +3 -0
- package/node_modules/openapi-typescript-helpers/dist/index.cjs.map +1 -0
- package/node_modules/openapi-typescript-helpers/dist/index.d.cts +167 -0
- package/node_modules/openapi-typescript-helpers/dist/index.d.mts +167 -0
- package/node_modules/openapi-typescript-helpers/dist/index.d.ts +167 -0
- package/node_modules/openapi-typescript-helpers/dist/index.mjs +2 -0
- package/node_modules/openapi-typescript-helpers/dist/index.mjs.map +1 -0
- package/node_modules/openapi-typescript-helpers/package.json +39 -0
- package/openapi/SOURCE.json +10 -0
- package/openapi/openapi.yaml +30513 -0
- package/package.json +63 -4
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracken ID's OAuth endpoints as the CLI uses them: the device authorization grant (RFC 8628,
|
|
3
|
+
* D-57), refresh and revocation (RFC 7009). Client credentials (D-56) are `@tracken/sdk`'s
|
|
4
|
+
* `ClientCredentials`. Every request names the CLI in `User-Agent`; the edge refuses requests
|
|
5
|
+
* without one.
|
|
6
|
+
*/
|
|
7
|
+
import type { Clock, Fetch, TokenResponse } from "@tracken/sdk";
|
|
8
|
+
import type { Environment } from "../environments.js";
|
|
9
|
+
export { jwtClaims, jwtExpiry, systemClock, type Clock, type Fetch, type TokenResponse } from "@tracken/sdk";
|
|
10
|
+
export interface DeviceAuthorization {
|
|
11
|
+
device_code: string;
|
|
12
|
+
user_code: string;
|
|
13
|
+
verification_uri: string;
|
|
14
|
+
verification_uri_complete?: string;
|
|
15
|
+
expires_in: number;
|
|
16
|
+
interval?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
19
|
+
export declare function requestDeviceAuthorization(environment: Environment, scope: string, fetchFn: Fetch): Promise<DeviceAuthorization>;
|
|
20
|
+
export interface PollOptions {
|
|
21
|
+
fetch: Fetch;
|
|
22
|
+
clock: Clock;
|
|
23
|
+
/** Called after each `slow_down` with the new interval in seconds. */
|
|
24
|
+
onSlowDown?: (intervalSeconds: number) => void;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Polls the token endpoint until the person confirms the code (tokens), refuses it
|
|
28
|
+
* (`access_denied`) or lets it expire (`expired_token`, or the code's own lifetime passing).
|
|
29
|
+
*/
|
|
30
|
+
export declare function pollDeviceToken(environment: Environment, authorization: DeviceAuthorization, options: PollOptions): Promise<TokenResponse>;
|
|
31
|
+
export declare function refreshTokens(environment: Environment, refreshToken: string, fetchFn: Fetch): Promise<TokenResponse>;
|
|
32
|
+
export interface MachineCredential {
|
|
33
|
+
clientId: string;
|
|
34
|
+
clientSecret: string;
|
|
35
|
+
/** Space-separated scopes; absent asks for everything the credential holds (D-56). */
|
|
36
|
+
scope?: string;
|
|
37
|
+
}
|
|
38
|
+
/** RFC 7009: revoking the refresh token ends the CLI's grant; the short access token lives out its minutes. */
|
|
39
|
+
export declare function revokeToken(environment: Environment, token: string, hint: "refresh_token" | "access_token", fetchFn: Fetch): Promise<void>;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { NetworkError, OAuthError } from "../errors.js";
|
|
2
|
+
import { userAgent } from "../version.js";
|
|
3
|
+
export { jwtClaims, jwtExpiry, systemClock } from "@tracken/sdk";
|
|
4
|
+
export const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
|
|
5
|
+
/** RFC 8628 §3.5: the interval when the server names none, and what each `slow_down` adds. */
|
|
6
|
+
const DEFAULT_INTERVAL_S = 5;
|
|
7
|
+
const SLOW_DOWN_STEP_S = 5;
|
|
8
|
+
async function post(fetchFn, url, form) {
|
|
9
|
+
const headers = {
|
|
10
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
11
|
+
accept: "application/json",
|
|
12
|
+
"user-agent": userAgent(),
|
|
13
|
+
};
|
|
14
|
+
let response;
|
|
15
|
+
try {
|
|
16
|
+
response = await fetchFn(url, { method: "POST", headers, body: new URLSearchParams(form) });
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
throw new NetworkError(`Could not reach Tracken ID at ${new URL(url).origin}: ${error.message}`, error);
|
|
20
|
+
}
|
|
21
|
+
const text = await response.text();
|
|
22
|
+
let body = {};
|
|
23
|
+
try {
|
|
24
|
+
body = text ? JSON.parse(text) : {};
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
body = { error: "invalid_response", error_description: `HTTP ${response.status} from ${new URL(url).pathname}: ${text.slice(0, 200)}` };
|
|
28
|
+
}
|
|
29
|
+
return { status: response.status, body };
|
|
30
|
+
}
|
|
31
|
+
function oauthError(status, body) {
|
|
32
|
+
const error = typeof body.error === "string" ? body.error : `http_${status}`;
|
|
33
|
+
const description = typeof body.error_description === "string" ? body.error_description : undefined;
|
|
34
|
+
return new OAuthError(error, description, status);
|
|
35
|
+
}
|
|
36
|
+
function asToken(status, body) {
|
|
37
|
+
if (status !== 200 || typeof body.access_token !== "string")
|
|
38
|
+
throw oauthError(status, body);
|
|
39
|
+
return body;
|
|
40
|
+
}
|
|
41
|
+
export async function requestDeviceAuthorization(environment, scope, fetchFn) {
|
|
42
|
+
const { status, body } = await post(fetchFn, `${environment.issuer}/device/auth`, {
|
|
43
|
+
client_id: environment.cliClientId,
|
|
44
|
+
scope,
|
|
45
|
+
resource: environment.personAudience,
|
|
46
|
+
});
|
|
47
|
+
if (status !== 200 || typeof body.device_code !== "string" || typeof body.user_code !== "string")
|
|
48
|
+
throw oauthError(status, body);
|
|
49
|
+
return body;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Polls the token endpoint until the person confirms the code (tokens), refuses it
|
|
53
|
+
* (`access_denied`) or lets it expire (`expired_token`, or the code's own lifetime passing).
|
|
54
|
+
*/
|
|
55
|
+
export async function pollDeviceToken(environment, authorization, options) {
|
|
56
|
+
let interval = authorization.interval && authorization.interval > 0 ? authorization.interval : DEFAULT_INTERVAL_S;
|
|
57
|
+
const deadline = options.clock.now() + authorization.expires_in * 1000;
|
|
58
|
+
for (;;) {
|
|
59
|
+
await options.clock.sleep(interval * 1000);
|
|
60
|
+
if (options.clock.now() > deadline)
|
|
61
|
+
throw new OAuthError("expired_token", "The code expired before it was confirmed; run `tracken login` again.", 400);
|
|
62
|
+
const { status, body } = await post(options.fetch, `${environment.issuer}/token`, {
|
|
63
|
+
grant_type: DEVICE_CODE_GRANT,
|
|
64
|
+
device_code: authorization.device_code,
|
|
65
|
+
client_id: environment.cliClientId,
|
|
66
|
+
});
|
|
67
|
+
if (status === 200)
|
|
68
|
+
return asToken(status, body);
|
|
69
|
+
const error = body.error;
|
|
70
|
+
if (error === "authorization_pending")
|
|
71
|
+
continue;
|
|
72
|
+
if (error === "slow_down") {
|
|
73
|
+
interval += SLOW_DOWN_STEP_S;
|
|
74
|
+
options.onSlowDown?.(interval);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (error === "access_denied")
|
|
78
|
+
throw new OAuthError("access_denied", "The sign-in was refused or cancelled in the browser.", status);
|
|
79
|
+
if (error === "expired_token")
|
|
80
|
+
throw new OAuthError("expired_token", "The code expired before it was confirmed; run `tracken login` again.", status);
|
|
81
|
+
throw oauthError(status, body);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
export async function refreshTokens(environment, refreshToken, fetchFn) {
|
|
85
|
+
const { status, body } = await post(fetchFn, `${environment.issuer}/token`, {
|
|
86
|
+
grant_type: "refresh_token",
|
|
87
|
+
refresh_token: refreshToken,
|
|
88
|
+
client_id: environment.cliClientId,
|
|
89
|
+
});
|
|
90
|
+
return asToken(status, body);
|
|
91
|
+
}
|
|
92
|
+
/** RFC 7009: revoking the refresh token ends the CLI's grant; the short access token lives out its minutes. */
|
|
93
|
+
export async function revokeToken(environment, token, hint, fetchFn) {
|
|
94
|
+
const { status, body } = await post(fetchFn, `${environment.issuer}/revoke`, {
|
|
95
|
+
token,
|
|
96
|
+
token_type_hint: hint,
|
|
97
|
+
client_id: environment.cliClientId,
|
|
98
|
+
});
|
|
99
|
+
if (status !== 200)
|
|
100
|
+
throw oauthError(status, body);
|
|
101
|
+
}
|
|
102
|
+
//# sourceMappingURL=oauth.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Shorthand for every `*:read` scope. */
|
|
2
|
+
export declare const READ_SCOPE = "read";
|
|
3
|
+
/** OpenID scopes asked beside the API scopes, so the token names the person (email, name). */
|
|
4
|
+
export declare const IDENTITY_SCOPES: readonly ["openid", "email", "profile"];
|
|
5
|
+
/** Tracken ID's own rule (apps/idp/src/device-flow.ts `isReadOnlyScope`). */
|
|
6
|
+
export declare const isReadOnlyScope: (scope: string) => boolean;
|
|
7
|
+
/**
|
|
8
|
+
* `--write`: read everything, and every write or manage scope some live operation needs. Scopes of
|
|
9
|
+
* operations the API does not serve yet are left out, so the person approves only what can be used;
|
|
10
|
+
* a later CLI that offers more says which scope to add (403 INSUFFICIENT_SCOPE).
|
|
11
|
+
*/
|
|
12
|
+
export declare function writeScopes(): string[];
|
|
13
|
+
/** Checks explicitly named scopes against the document's catalogue; an unknown one is refused, never dropped. */
|
|
14
|
+
export declare function validateScopes(requested: string[]): string[];
|
|
15
|
+
export type SessionClass = "read" | "write";
|
|
16
|
+
export declare const sessionClass: (apiScopes: readonly string[]) => SessionClass;
|
|
17
|
+
export declare function describeSessionClass(kind: SessionClass): string;
|
|
18
|
+
/** The API scopes inside a token's space-separated `scope`. */
|
|
19
|
+
export declare const apiScopesOf: (scope: string | undefined) => string[];
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The API scopes a sign-in asks for. Tracken ID refuses a CLI sign-in that names no API scope, and
|
|
3
|
+
* how long the CLI stays signed in follows them (D-57): only read-only scopes keep the session
|
|
4
|
+
* 7 days unused and 30 days at most; any write or manage scope, 24 hours unused and 7 days at most.
|
|
5
|
+
*/
|
|
6
|
+
import { UsageError } from "../errors.js";
|
|
7
|
+
import { OPERATIONS, SCOPES } from "../../generated/operations.js";
|
|
8
|
+
/** Shorthand for every `*:read` scope. */
|
|
9
|
+
export const READ_SCOPE = "read";
|
|
10
|
+
/** OpenID scopes asked beside the API scopes, so the token names the person (email, name). */
|
|
11
|
+
export const IDENTITY_SCOPES = ["openid", "email", "profile"];
|
|
12
|
+
/** Tracken ID's own rule (apps/idp/src/device-flow.ts `isReadOnlyScope`). */
|
|
13
|
+
export const isReadOnlyScope = (scope) => scope === READ_SCOPE || scope.endsWith(":read");
|
|
14
|
+
/**
|
|
15
|
+
* `--write`: read everything, and every write or manage scope some live operation needs. Scopes of
|
|
16
|
+
* operations the API does not serve yet are left out, so the person approves only what can be used;
|
|
17
|
+
* a later CLI that offers more says which scope to add (403 INSUFFICIENT_SCOPE).
|
|
18
|
+
*/
|
|
19
|
+
export function writeScopes() {
|
|
20
|
+
const writes = new Set();
|
|
21
|
+
for (const operation of OPERATIONS) {
|
|
22
|
+
if (operation.availability !== "live")
|
|
23
|
+
continue;
|
|
24
|
+
for (const scope of operation.scopes)
|
|
25
|
+
if (!isReadOnlyScope(scope))
|
|
26
|
+
writes.add(scope);
|
|
27
|
+
}
|
|
28
|
+
return [READ_SCOPE, ...SCOPES.map((scope) => scope.name).filter((name) => writes.has(name))];
|
|
29
|
+
}
|
|
30
|
+
/** Checks explicitly named scopes against the document's catalogue; an unknown one is refused, never dropped. */
|
|
31
|
+
export function validateScopes(requested) {
|
|
32
|
+
const known = new Set(SCOPES.map((scope) => scope.name));
|
|
33
|
+
const unknown = requested.filter((scope) => !known.has(scope));
|
|
34
|
+
if (unknown.length > 0) {
|
|
35
|
+
throw new UsageError(`Unknown scope${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")}. Known scopes: ${[...known].join(", ")}.`);
|
|
36
|
+
}
|
|
37
|
+
if (requested.length === 0)
|
|
38
|
+
throw new UsageError("Name at least one scope.");
|
|
39
|
+
return [...new Set(requested)];
|
|
40
|
+
}
|
|
41
|
+
export const sessionClass = (apiScopes) => (apiScopes.length > 0 && apiScopes.every(isReadOnlyScope) ? "read" : "write");
|
|
42
|
+
export function describeSessionClass(kind) {
|
|
43
|
+
return kind === "read"
|
|
44
|
+
? "read-only: stays signed in 7 days unused, 30 days at most"
|
|
45
|
+
: "may write: stays signed in 24 hours unused, 7 days at most";
|
|
46
|
+
}
|
|
47
|
+
/** The API scopes inside a token's space-separated `scope`. */
|
|
48
|
+
export const apiScopesOf = (scope) => (scope ?? "").split(/\s+/).filter((entry) => entry && !IDENTITY_SCOPES.includes(entry) && entry !== "offline_access");
|
|
49
|
+
//# sourceMappingURL=scopes.js.map
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export interface SecretStore {
|
|
2
|
+
readonly kind: "keychain" | "file" | "memory";
|
|
3
|
+
/** Where the secrets are, for messages. */
|
|
4
|
+
readonly location: string;
|
|
5
|
+
get(key: string): Promise<string | undefined>;
|
|
6
|
+
set(key: string, value: string): Promise<void>;
|
|
7
|
+
delete(key: string): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
export declare const KEYCHAIN_SERVICE = "tracken-cli";
|
|
10
|
+
/** The part of @napi-rs/keyring the store uses; tests pass a fake. */
|
|
11
|
+
export interface KeyringEntry {
|
|
12
|
+
getPassword(): Promise<string | null | undefined>;
|
|
13
|
+
setPassword(password: string): Promise<void>;
|
|
14
|
+
deletePassword(): Promise<boolean>;
|
|
15
|
+
}
|
|
16
|
+
export interface KeyringModule {
|
|
17
|
+
AsyncEntry: new (service: string, account: string) => KeyringEntry;
|
|
18
|
+
}
|
|
19
|
+
export declare class KeychainStore implements SecretStore {
|
|
20
|
+
private readonly keyring;
|
|
21
|
+
readonly kind = "keychain";
|
|
22
|
+
readonly location = "the OS keychain";
|
|
23
|
+
constructor(keyring: KeyringModule);
|
|
24
|
+
private entry;
|
|
25
|
+
private chunkCount;
|
|
26
|
+
get(key: string): Promise<string | undefined>;
|
|
27
|
+
set(key: string, value: string): Promise<void>;
|
|
28
|
+
delete(key: string): Promise<void>;
|
|
29
|
+
private deleteChunks;
|
|
30
|
+
}
|
|
31
|
+
export declare class FileStore implements SecretStore {
|
|
32
|
+
private readonly directory;
|
|
33
|
+
private readonly warn;
|
|
34
|
+
private readonly fallbackReason?;
|
|
35
|
+
readonly kind = "file";
|
|
36
|
+
readonly location: string;
|
|
37
|
+
private warned;
|
|
38
|
+
/** `fallbackReason` is set when the file stands in for a keychain that is missing. */
|
|
39
|
+
constructor(directory: string, warn?: (message: string) => void, fallbackReason?: string | undefined);
|
|
40
|
+
private read;
|
|
41
|
+
get(key: string): Promise<string | undefined>;
|
|
42
|
+
set(key: string, value: string): Promise<void>;
|
|
43
|
+
delete(key: string): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
export declare class MemoryStore implements SecretStore {
|
|
46
|
+
readonly kind = "memory";
|
|
47
|
+
readonly location = "memory";
|
|
48
|
+
readonly values: Map<string, string>;
|
|
49
|
+
get(key: string): Promise<string | undefined>;
|
|
50
|
+
set(key: string, value: string): Promise<void>;
|
|
51
|
+
delete(key: string): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
export interface OpenStoreOptions {
|
|
54
|
+
directory: string;
|
|
55
|
+
env: NodeJS.ProcessEnv;
|
|
56
|
+
warn: (message: string) => void;
|
|
57
|
+
loadKeyring?: () => Promise<KeyringModule>;
|
|
58
|
+
}
|
|
59
|
+
/** The keychain when one answers, else the private file (with a warning on first write). */
|
|
60
|
+
export declare function openSecretStore(options: OpenStoreOptions): Promise<SecretStore>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where sessions are kept: the OS keychain (macOS Keychain, Windows Credential Manager, the Secret
|
|
3
|
+
* Service on Linux) through @napi-rs/keyring; a file readable only by its owner when there is no
|
|
4
|
+
* keychain (a headless Linux box, a container). `TRACKEN_TOKEN_STORE=file|keychain` forces one.
|
|
5
|
+
*/
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { readJson, writePrivateFile } from "../config.js";
|
|
8
|
+
export const KEYCHAIN_SERVICE = "tracken-cli";
|
|
9
|
+
/**
|
|
10
|
+
* Windows keeps at most 2 560 bytes per credential and keyring stores UTF-16 there, so about 1 280
|
|
11
|
+
* characters; an access token with many scopes is longer. Longer values go into numbered entries.
|
|
12
|
+
*/
|
|
13
|
+
const CHUNK = 1000;
|
|
14
|
+
const CHUNKED = "tracken-chunks:";
|
|
15
|
+
export class KeychainStore {
|
|
16
|
+
keyring;
|
|
17
|
+
kind = "keychain";
|
|
18
|
+
location = "the OS keychain";
|
|
19
|
+
constructor(keyring) {
|
|
20
|
+
this.keyring = keyring;
|
|
21
|
+
}
|
|
22
|
+
entry(account) {
|
|
23
|
+
return new this.keyring.AsyncEntry(KEYCHAIN_SERVICE, account);
|
|
24
|
+
}
|
|
25
|
+
async chunkCount(key) {
|
|
26
|
+
const head = (await this.entry(key).getPassword()) ?? undefined;
|
|
27
|
+
return head?.startsWith(CHUNKED) ? Number(head.slice(CHUNKED.length)) || 0 : 0;
|
|
28
|
+
}
|
|
29
|
+
async get(key) {
|
|
30
|
+
const head = (await this.entry(key).getPassword()) ?? undefined;
|
|
31
|
+
if (!head?.startsWith(CHUNKED))
|
|
32
|
+
return head;
|
|
33
|
+
const count = Number(head.slice(CHUNKED.length));
|
|
34
|
+
const parts = [];
|
|
35
|
+
for (let index = 1; index <= count; index++) {
|
|
36
|
+
const part = await this.entry(`${key}#${index}`).getPassword();
|
|
37
|
+
// A missing part means a write was interrupted: treat the whole value as absent.
|
|
38
|
+
if (part === null || part === undefined)
|
|
39
|
+
return undefined;
|
|
40
|
+
parts.push(part);
|
|
41
|
+
}
|
|
42
|
+
return parts.join("");
|
|
43
|
+
}
|
|
44
|
+
async set(key, value) {
|
|
45
|
+
const before = await this.chunkCount(key);
|
|
46
|
+
if (value.length <= CHUNK && !value.startsWith(CHUNKED)) {
|
|
47
|
+
await this.entry(key).setPassword(value);
|
|
48
|
+
await this.deleteChunks(key, 1, before);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const parts = Math.ceil(value.length / CHUNK);
|
|
52
|
+
for (let index = 1; index <= parts; index++) {
|
|
53
|
+
await this.entry(`${key}#${index}`).setPassword(value.slice((index - 1) * CHUNK, index * CHUNK));
|
|
54
|
+
}
|
|
55
|
+
await this.entry(key).setPassword(`${CHUNKED}${parts}`);
|
|
56
|
+
await this.deleteChunks(key, parts + 1, before);
|
|
57
|
+
}
|
|
58
|
+
async delete(key) {
|
|
59
|
+
const before = await this.chunkCount(key);
|
|
60
|
+
await this.entry(key).deletePassword();
|
|
61
|
+
await this.deleteChunks(key, 1, before);
|
|
62
|
+
}
|
|
63
|
+
async deleteChunks(key, from, to) {
|
|
64
|
+
for (let index = from; index <= to; index++)
|
|
65
|
+
await this.entry(`${key}#${index}`).deletePassword();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export class FileStore {
|
|
69
|
+
directory;
|
|
70
|
+
warn;
|
|
71
|
+
fallbackReason;
|
|
72
|
+
kind = "file";
|
|
73
|
+
location;
|
|
74
|
+
warned = false;
|
|
75
|
+
/** `fallbackReason` is set when the file stands in for a keychain that is missing. */
|
|
76
|
+
constructor(directory, warn = () => { }, fallbackReason) {
|
|
77
|
+
this.directory = directory;
|
|
78
|
+
this.warn = warn;
|
|
79
|
+
this.fallbackReason = fallbackReason;
|
|
80
|
+
this.location = join(directory, "credentials.json");
|
|
81
|
+
}
|
|
82
|
+
async read() {
|
|
83
|
+
return (await readJson(this.location)) ?? {};
|
|
84
|
+
}
|
|
85
|
+
async get(key) {
|
|
86
|
+
return (await this.read())[key];
|
|
87
|
+
}
|
|
88
|
+
async set(key, value) {
|
|
89
|
+
if (this.fallbackReason && !this.warned) {
|
|
90
|
+
this.warned = true;
|
|
91
|
+
this.warn(`Warning: no OS keychain is available (${this.fallbackReason}); tokens are kept in ${this.location}, readable only by you.`);
|
|
92
|
+
}
|
|
93
|
+
const all = await this.read();
|
|
94
|
+
all[key] = value;
|
|
95
|
+
await writePrivateFile(this.location, `${JSON.stringify(all, null, 2)}\n`, this.directory);
|
|
96
|
+
}
|
|
97
|
+
async delete(key) {
|
|
98
|
+
const all = await this.read();
|
|
99
|
+
if (!(key in all))
|
|
100
|
+
return;
|
|
101
|
+
delete all[key];
|
|
102
|
+
await writePrivateFile(this.location, `${JSON.stringify(all, null, 2)}\n`, this.directory);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
export class MemoryStore {
|
|
106
|
+
kind = "memory";
|
|
107
|
+
location = "memory";
|
|
108
|
+
values = new Map();
|
|
109
|
+
async get(key) {
|
|
110
|
+
return this.values.get(key);
|
|
111
|
+
}
|
|
112
|
+
async set(key, value) {
|
|
113
|
+
this.values.set(key, value);
|
|
114
|
+
}
|
|
115
|
+
async delete(key) {
|
|
116
|
+
this.values.delete(key);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const loadNativeKeyring = async () => (await import("@napi-rs/keyring"));
|
|
120
|
+
/** The keychain when one answers, else the private file (with a warning on first write). */
|
|
121
|
+
export async function openSecretStore(options) {
|
|
122
|
+
const mode = options.env.TRACKEN_TOKEN_STORE;
|
|
123
|
+
if (mode === "file")
|
|
124
|
+
return new FileStore(options.directory, options.warn);
|
|
125
|
+
if (mode !== undefined && mode !== "" && mode !== "keychain") {
|
|
126
|
+
throw new Error(`TRACKEN_TOKEN_STORE must be "keychain" or "file", not "${mode}".`);
|
|
127
|
+
}
|
|
128
|
+
try {
|
|
129
|
+
const keyring = await (options.loadKeyring ?? loadNativeKeyring)();
|
|
130
|
+
// Reading an entry that does not exist answers null on a working keychain and throws when
|
|
131
|
+
// there is none (no Secret Service on D-Bus, a locked or missing store).
|
|
132
|
+
await new keyring.AsyncEntry(KEYCHAIN_SERVICE, "probe").getPassword();
|
|
133
|
+
return new KeychainStore(keyring);
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
if (mode === "keychain")
|
|
137
|
+
throw new Error(`TRACKEN_TOKEN_STORE=keychain, but the OS keychain is unavailable: ${error.message}`);
|
|
138
|
+
return new FileStore(options.directory, options.warn, error.message.split("\n")[0] || "unavailable");
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
//# sourceMappingURL=secret-store.js.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { type Credentials } from "@tracken/sdk";
|
|
2
|
+
import type { Environment, EnvironmentName } from "../environments.js";
|
|
3
|
+
import { type Clock, type Fetch, type MachineCredential, type TokenResponse } from "./oauth.js";
|
|
4
|
+
import type { SecretStore } from "./secret-store.js";
|
|
5
|
+
export interface StoredSession {
|
|
6
|
+
version: 1;
|
|
7
|
+
environment: EnvironmentName;
|
|
8
|
+
issuer: string;
|
|
9
|
+
client_id: string;
|
|
10
|
+
access_token: string;
|
|
11
|
+
refresh_token?: string;
|
|
12
|
+
/** Epoch ms when the access token lapses. */
|
|
13
|
+
expires_at: number;
|
|
14
|
+
/** The granted scopes, space-separated, as Tracken ID answered them. */
|
|
15
|
+
scope: string;
|
|
16
|
+
obtained_at: number;
|
|
17
|
+
subject?: string;
|
|
18
|
+
email?: string;
|
|
19
|
+
name?: string;
|
|
20
|
+
}
|
|
21
|
+
/** The SDK's: a token for the next minute, and a renewal after the API refused one. */
|
|
22
|
+
export type { Credentials };
|
|
23
|
+
export declare function sessionFromTokens(environment: Environment, tokens: TokenResponse, now: number, previous?: StoredSession, requestedScope?: string): StoredSession;
|
|
24
|
+
/** Loads, saves and refreshes the person's session for one environment. */
|
|
25
|
+
export declare class SessionManager {
|
|
26
|
+
readonly environment: Environment;
|
|
27
|
+
readonly store: SecretStore;
|
|
28
|
+
private readonly directory;
|
|
29
|
+
private readonly fetchFn;
|
|
30
|
+
private readonly clock;
|
|
31
|
+
readonly key: string;
|
|
32
|
+
private readonly lockPath;
|
|
33
|
+
constructor(environment: Environment, store: SecretStore, directory: string, fetchFn: Fetch, clock: Clock);
|
|
34
|
+
load(): Promise<StoredSession | undefined>;
|
|
35
|
+
save(session: StoredSession): Promise<void>;
|
|
36
|
+
clear(): Promise<void>;
|
|
37
|
+
expiringSoon(session: StoredSession): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Refreshes under the lock, after re-reading the store: when another process already rotated the
|
|
40
|
+
* tokens, their result is used and the spent refresh token is never presented again (Tracken ID
|
|
41
|
+
* revokes the whole chain on reuse).
|
|
42
|
+
*/
|
|
43
|
+
refresh(stale: string): Promise<StoredSession>;
|
|
44
|
+
}
|
|
45
|
+
export declare class UserCredentials implements Credentials {
|
|
46
|
+
private readonly manager;
|
|
47
|
+
private session;
|
|
48
|
+
readonly kind = "user";
|
|
49
|
+
constructor(manager: SessionManager, session: StoredSession);
|
|
50
|
+
get current(): StoredSession;
|
|
51
|
+
accessToken(): Promise<string>;
|
|
52
|
+
renew(rejected: string): Promise<void>;
|
|
53
|
+
}
|
|
54
|
+
/** A machine credential: the SDK's client-credentials exchange, worded for the CLI when Tracken ID refuses it. */
|
|
55
|
+
export declare class MachineCredentials implements Credentials {
|
|
56
|
+
readonly credential: MachineCredential;
|
|
57
|
+
readonly kind = "machine";
|
|
58
|
+
private readonly exchange;
|
|
59
|
+
constructor(environment: Environment, credential: MachineCredential, fetchFn: Fetch, clock: Clock);
|
|
60
|
+
private worded;
|
|
61
|
+
accessToken(): Promise<string>;
|
|
62
|
+
/** A fresh token, once per refusal; never a person's session in its place. */
|
|
63
|
+
renew(rejected: string): Promise<void>;
|
|
64
|
+
}
|
|
65
|
+
/** `TRACKEN_CLIENT_ID` + `TRACKEN_CLIENT_SECRET` (and optional `TRACKEN_SCOPE`), when set. */
|
|
66
|
+
export declare function machineCredentialFromEnv(env: NodeJS.ProcessEnv): MachineCredential | undefined;
|
|
67
|
+
export interface ResolveCredentialsOptions {
|
|
68
|
+
environment: Environment;
|
|
69
|
+
env: NodeJS.ProcessEnv;
|
|
70
|
+
manager: SessionManager;
|
|
71
|
+
fetch: Fetch;
|
|
72
|
+
clock: Clock;
|
|
73
|
+
}
|
|
74
|
+
/** The machine credential when the environment names one, else the stored session. */
|
|
75
|
+
export declare function resolveCredentials(options: ResolveCredentialsOptions): Promise<Credentials>;
|