@camstack/develop 0.1.3 → 0.1.4
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/dist/hub/admin-token-store.d.ts +53 -0
- package/dist/hub/admin-token-store.d.ts.map +1 -0
- package/dist/hub/admin-token-store.js +139 -0
- package/dist/hub/credentials.d.ts +53 -0
- package/dist/hub/credentials.d.ts.map +1 -0
- package/dist/hub/credentials.js +149 -0
- package/dist/hub/hub-client.d.ts +57 -0
- package/dist/hub/hub-client.d.ts.map +1 -0
- package/dist/hub/hub-client.js +176 -0
- package/dist/hub/hub-tls.d.ts +16 -0
- package/dist/hub/hub-tls.d.ts.map +1 -0
- package/dist/hub/hub-tls.js +67 -0
- package/dist/hub/hub-url.d.ts +17 -0
- package/dist/hub/hub-url.d.ts.map +1 -0
- package/dist/hub/hub-url.js +44 -0
- package/dist/hub/session-store.d.ts +38 -0
- package/dist/hub/session-store.d.ts.map +1 -0
- package/dist/hub/session-store.js +117 -0
- package/dist/index.d.ts +14 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -2
- package/dist/scaffold/addon.d.ts.map +1 -1
- package/dist/scaffold/addon.js +6 -0
- package/dist/types.d.ts +6 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/skills/README.md +3 -0
- package/skills/camstack-addon.md +376 -98
- package/skills/camstack-capability.md +184 -77
- package/skills/camstack-secrets.md +121 -34
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export interface AdminTokenMeta {
|
|
2
|
+
readonly tokenId: string;
|
|
3
|
+
readonly createdAt: number;
|
|
4
|
+
readonly expiresAt: number;
|
|
5
|
+
}
|
|
6
|
+
/** `present` carries the expiry only when the meta file could be read. */
|
|
7
|
+
export type AdminTokenStatus = {
|
|
8
|
+
readonly state: 'missing';
|
|
9
|
+
} | {
|
|
10
|
+
readonly state: 'expired';
|
|
11
|
+
readonly expiresAt: number;
|
|
12
|
+
} | {
|
|
13
|
+
readonly state: 'present';
|
|
14
|
+
readonly expiresAt?: number;
|
|
15
|
+
};
|
|
16
|
+
export declare function adminTokenMetaFileForServer(serverUrl: string, dir?: string): string;
|
|
17
|
+
/** Persist an admin token for `serverUrl`; returns the token file path. */
|
|
18
|
+
export declare function saveAdminToken(serverUrl: string, token: string, meta: AdminTokenMeta, dir?: string): string;
|
|
19
|
+
/**
|
|
20
|
+
* What `login --admin` is about to replace: no token file, a token whose hub id
|
|
21
|
+
* the meta file names (so it can be revoked), or a token it cannot identify
|
|
22
|
+
* (no meta, or a meta without an id — written before the id was kept).
|
|
23
|
+
*/
|
|
24
|
+
export type PreviousAdminToken = {
|
|
25
|
+
readonly kind: 'none';
|
|
26
|
+
} | {
|
|
27
|
+
readonly kind: 'identified';
|
|
28
|
+
readonly tokenId: string;
|
|
29
|
+
readonly expiresAt?: number;
|
|
30
|
+
} | {
|
|
31
|
+
readonly kind: 'unidentified';
|
|
32
|
+
readonly expiresAt?: number;
|
|
33
|
+
};
|
|
34
|
+
/** Read the admin token currently stored for `serverUrl`, at the path `saveAdminToken` writes. */
|
|
35
|
+
export declare function readPreviousAdminToken(serverUrl: string, dir?: string): PreviousAdminToken;
|
|
36
|
+
/**
|
|
37
|
+
* Whether an admin credential exists for `serverUrl`, and whether it is known
|
|
38
|
+
* to be expired. Honours `$CAMSTACK_ADMIN_TOKEN_FILE` like the chain does; the
|
|
39
|
+
* meta file is looked up beside whichever token file the chain would read.
|
|
40
|
+
*/
|
|
41
|
+
export declare function adminTokenStatus(serverUrl: string, env?: Readonly<Record<string, string | undefined>>, dir?: string, now?: number): AdminTokenStatus;
|
|
42
|
+
/** The checkout-local invocation: build the CLI once, then run its entry. */
|
|
43
|
+
export declare const REPO_LOCAL_LOGIN_ADMIN = "npx nx run camstack:build && node packages/cli/dist/cli.js login --admin";
|
|
44
|
+
/**
|
|
45
|
+
* The exact command that produces an admin token: `camstack login --admin` when
|
|
46
|
+
* the binary is on PATH, otherwise the checkout-local form.
|
|
47
|
+
*/
|
|
48
|
+
export declare function adminLoginCommand(env?: Readonly<Record<string, string | undefined>>): string;
|
|
49
|
+
/** The hub answered 401/403 to an admin credential: the file is stale or revoked. */
|
|
50
|
+
export declare function adminRejectedHint(command?: string): string;
|
|
51
|
+
/** Why there is no usable admin credential, with the command that fixes it; `null` when fine. */
|
|
52
|
+
export declare function adminCredentialHint(status: AdminTokenStatus, command?: string): string | null;
|
|
53
|
+
//# sourceMappingURL=admin-token-store.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admin-token-store.d.ts","sourceRoot":"","sources":["../../src/hub/admin-token-store.ts"],"names":[],"mappings":"AAmBA,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAC3B;AAED,0EAA0E;AAC1E,MAAM,MAAM,gBAAgB,GACxB;IAAE,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAA;CAAE,GAC7B;IAAE,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACzD;IAAE,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAAA;AAE9D,wBAAgB,2BAA2B,CACzC,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAA4B,GAChC,MAAM,CAER;AAmBD,2EAA2E;AAC3E,wBAAgB,cAAc,CAC5B,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,cAAc,EACpB,GAAG,GAAE,MAA4B,GAChC,MAAM,CAMR;AAiBD;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAC1B;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACzB;IAAE,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GACtF;IAAE,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAAC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,CAAA;AAElE,kGAAkG;AAClG,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAA4B,GAChC,kBAAkB,CAepB;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,EAC/D,GAAG,GAAE,MAA4B,EACjC,GAAG,GAAE,MAAmB,GACvB,gBAAgB,CAQlB;AAgBD,6EAA6E;AAC7E,eAAO,MAAM,sBAAsB,6EACyC,CAAA;AAE5E;;;GAGG;AACH,wBAAgB,iBAAiB,CAC/B,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GAC9D,MAAM,CAER;AAED,qFAAqF;AACrF,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,MAA4B,GAAG,MAAM,CAE/E;AAED,iGAAiG;AACjG,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,gBAAgB,EACxB,OAAO,GAAE,MAA4B,GACpC,MAAM,GAAG,IAAI,CAOf"}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The admin token file written by `camstack login --admin` and read by the
|
|
3
|
+
* credential chain (D816, D835): one more writer of a file the chain already
|
|
4
|
+
* reads, no new decision.
|
|
5
|
+
*
|
|
6
|
+
* Two files, both 0600, beside the session cache:
|
|
7
|
+
* - `<host>.admin-token` the bare `csa_` token (what the chain reads)
|
|
8
|
+
* - `<host>.admin-token.meta` `{ tokenId, createdAt, expiresAt }` — NO secret.
|
|
9
|
+
* Present only so `whoami` and the operator MCP can say "expired" without
|
|
10
|
+
* calling the hub. The chain never needs it: a missing or unreadable meta
|
|
11
|
+
* file only means "expiry unknown".
|
|
12
|
+
*
|
|
13
|
+
* Neither extension is `.json`, so the newest-session fallback never mistakes
|
|
14
|
+
* them for a session.
|
|
15
|
+
*/
|
|
16
|
+
import * as fs from 'node:fs';
|
|
17
|
+
import * as path from 'node:path';
|
|
18
|
+
import { adminTokenFileForServer, defaultSessionDir, findAdminTokenFile } from './session-store.js';
|
|
19
|
+
export function adminTokenMetaFileForServer(serverUrl, dir = defaultSessionDir()) {
|
|
20
|
+
return `${adminTokenFileForServer(serverUrl, dir)}.meta`;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Write `content` to `file` with mode 0600, atomically: a sibling temp file is
|
|
24
|
+
* created exclusively (`wx`, 0600), then renamed over the target. A crash leaves
|
|
25
|
+
* the old file or the new one, never a half-written token.
|
|
26
|
+
*/
|
|
27
|
+
function writeFileAtomic0600(file, content) {
|
|
28
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
29
|
+
try {
|
|
30
|
+
fs.writeFileSync(tmp, content, { mode: 0o600, flag: 'wx' });
|
|
31
|
+
fs.chmodSync(tmp, 0o600);
|
|
32
|
+
fs.renameSync(tmp, file);
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
fs.rmSync(tmp, { force: true });
|
|
36
|
+
throw err;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Persist an admin token for `serverUrl`; returns the token file path. */
|
|
40
|
+
export function saveAdminToken(serverUrl, token, meta, dir = defaultSessionDir()) {
|
|
41
|
+
if (!fs.existsSync(dir))
|
|
42
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
43
|
+
const file = adminTokenFileForServer(serverUrl, dir);
|
|
44
|
+
writeFileAtomic0600(file, `${token}\n`);
|
|
45
|
+
writeFileAtomic0600(adminTokenMetaFileForServer(serverUrl, dir), JSON.stringify(meta, null, 2));
|
|
46
|
+
return file;
|
|
47
|
+
}
|
|
48
|
+
function readMeta(file) {
|
|
49
|
+
try {
|
|
50
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
51
|
+
if (parsed === null || typeof parsed !== 'object')
|
|
52
|
+
return null;
|
|
53
|
+
const tokenId = Reflect.get(parsed, 'tokenId');
|
|
54
|
+
const createdAt = Reflect.get(parsed, 'createdAt');
|
|
55
|
+
const expiresAt = Reflect.get(parsed, 'expiresAt');
|
|
56
|
+
if (typeof tokenId !== 'string' || typeof createdAt !== 'number')
|
|
57
|
+
return null;
|
|
58
|
+
if (typeof expiresAt !== 'number')
|
|
59
|
+
return null;
|
|
60
|
+
return { tokenId, createdAt, expiresAt };
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Read the admin token currently stored for `serverUrl`, at the path `saveAdminToken` writes. */
|
|
67
|
+
export function readPreviousAdminToken(serverUrl, dir = defaultSessionDir()) {
|
|
68
|
+
if (!fs.existsSync(adminTokenFileForServer(serverUrl, dir)))
|
|
69
|
+
return { kind: 'none' };
|
|
70
|
+
let parsed;
|
|
71
|
+
try {
|
|
72
|
+
parsed = JSON.parse(fs.readFileSync(adminTokenMetaFileForServer(serverUrl, dir), 'utf8'));
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return { kind: 'unidentified' };
|
|
76
|
+
}
|
|
77
|
+
if (parsed === null || typeof parsed !== 'object')
|
|
78
|
+
return { kind: 'unidentified' };
|
|
79
|
+
const tokenId = Reflect.get(parsed, 'tokenId');
|
|
80
|
+
const expiresAt = Reflect.get(parsed, 'expiresAt');
|
|
81
|
+
const expiry = typeof expiresAt === 'number' ? { expiresAt } : {};
|
|
82
|
+
return typeof tokenId === 'string' && tokenId !== ''
|
|
83
|
+
? { kind: 'identified', tokenId, ...expiry }
|
|
84
|
+
: { kind: 'unidentified', ...expiry };
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Whether an admin credential exists for `serverUrl`, and whether it is known
|
|
88
|
+
* to be expired. Honours `$CAMSTACK_ADMIN_TOKEN_FILE` like the chain does; the
|
|
89
|
+
* meta file is looked up beside whichever token file the chain would read.
|
|
90
|
+
*/
|
|
91
|
+
export function adminTokenStatus(serverUrl, env = process.env, dir = defaultSessionDir(), now = Date.now()) {
|
|
92
|
+
const file = findAdminTokenFile(serverUrl, env, dir);
|
|
93
|
+
if (!file || !fs.existsSync(file))
|
|
94
|
+
return { state: 'missing' };
|
|
95
|
+
const meta = readMeta(`${file}.meta`);
|
|
96
|
+
if (!meta)
|
|
97
|
+
return { state: 'present' };
|
|
98
|
+
return meta.expiresAt <= now
|
|
99
|
+
? { state: 'expired', expiresAt: meta.expiresAt }
|
|
100
|
+
: { state: 'present', expiresAt: meta.expiresAt };
|
|
101
|
+
}
|
|
102
|
+
/** Is `name` an executable file in one of the `PATH` directories? */
|
|
103
|
+
function onPath(name, pathEnv) {
|
|
104
|
+
if (!pathEnv)
|
|
105
|
+
return false;
|
|
106
|
+
return pathEnv.split(path.delimiter).some((d) => {
|
|
107
|
+
if (d === '')
|
|
108
|
+
return false;
|
|
109
|
+
try {
|
|
110
|
+
fs.accessSync(path.join(d, name), fs.constants.X_OK);
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
/** The checkout-local invocation: build the CLI once, then run its entry. */
|
|
119
|
+
export const REPO_LOCAL_LOGIN_ADMIN = 'npx nx run camstack:build && node packages/cli/dist/cli.js login --admin';
|
|
120
|
+
/**
|
|
121
|
+
* The exact command that produces an admin token: `camstack login --admin` when
|
|
122
|
+
* the binary is on PATH, otherwise the checkout-local form.
|
|
123
|
+
*/
|
|
124
|
+
export function adminLoginCommand(env = process.env) {
|
|
125
|
+
return onPath('camstack', env['PATH']) ? 'camstack login --admin' : REPO_LOCAL_LOGIN_ADMIN;
|
|
126
|
+
}
|
|
127
|
+
/** The hub answered 401/403 to an admin credential: the file is stale or revoked. */
|
|
128
|
+
export function adminRejectedHint(command = adminLoginCommand()) {
|
|
129
|
+
return `the hub rejected the admin token (revoked, expired, or its creator is no longer an admin). Run \`${command}\` in a terminal to create a new one.`;
|
|
130
|
+
}
|
|
131
|
+
/** Why there is no usable admin credential, with the command that fixes it; `null` when fine. */
|
|
132
|
+
export function adminCredentialHint(status, command = adminLoginCommand()) {
|
|
133
|
+
if (status.state === 'present')
|
|
134
|
+
return null;
|
|
135
|
+
const why = status.state === 'expired'
|
|
136
|
+
? `the admin token expired at ${new Date(status.expiresAt).toISOString()}`
|
|
137
|
+
: 'there is no admin token for this hub';
|
|
138
|
+
return `${why}. Run \`${command}\` in a terminal (it asks for your password; the MCP never does).`;
|
|
139
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export type CredentialSource = 'flag' | 'token-file' | 'admin-token' | 'env' | 'session';
|
|
2
|
+
/** What a credential may reach: `admin` only for a `csa_` token (D816). */
|
|
3
|
+
export type CredentialTier = 'admin' | 'protected';
|
|
4
|
+
export declare const ADMIN_TOKEN_PREFIX = "csa_";
|
|
5
|
+
/** The tier a token buys. Prefix only: the hub still decides on every call. */
|
|
6
|
+
export declare function credentialTier(token: string): CredentialTier;
|
|
7
|
+
export interface ResolvedCredentials {
|
|
8
|
+
readonly server: string | undefined;
|
|
9
|
+
readonly token: string;
|
|
10
|
+
readonly source: CredentialSource;
|
|
11
|
+
/** `admin` only for a `csa_` admin token; every other credential is `protected`. */
|
|
12
|
+
readonly tier: CredentialTier;
|
|
13
|
+
/** A non-fatal note for stderr (e.g. a world-readable token file). */
|
|
14
|
+
readonly warning?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface CachedSessionLike {
|
|
17
|
+
readonly server: string;
|
|
18
|
+
readonly token: string;
|
|
19
|
+
}
|
|
20
|
+
export interface CredentialInputs {
|
|
21
|
+
readonly server?: string;
|
|
22
|
+
readonly token?: string;
|
|
23
|
+
readonly tokenFile?: string;
|
|
24
|
+
/** An owner-only file holding a `csa_` admin token (D816); resolved after `tokenFile`. */
|
|
25
|
+
readonly adminTokenFile?: string;
|
|
26
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
27
|
+
/** The session lookup — `loadSession` from `auth.ts`, injectable for tests. */
|
|
28
|
+
readonly loadSession: (server?: string) => CachedSessionLike | null;
|
|
29
|
+
}
|
|
30
|
+
export interface TokenFileContents {
|
|
31
|
+
readonly token: string;
|
|
32
|
+
readonly server?: string;
|
|
33
|
+
readonly warning?: string;
|
|
34
|
+
}
|
|
35
|
+
/** No token could be resolved from any source. The message tells the operator what to do. */
|
|
36
|
+
export declare class MissingCredentialsError extends Error {
|
|
37
|
+
constructor(server: string | undefined);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Read a token file: a single bare token, or a JSON session file
|
|
41
|
+
* (`{ "server": "...", "token": "..." }`, extra fields ignored).
|
|
42
|
+
*/
|
|
43
|
+
export declare function readTokenFile(filePath: string): TokenFileContents;
|
|
44
|
+
/** Resolve `{server, token}` for a hub command. Throws {@link MissingCredentialsError}. */
|
|
45
|
+
export declare function resolveCredentials(inputs: CredentialInputs): ResolvedCredentials;
|
|
46
|
+
/**
|
|
47
|
+
* The line to append to an HTTP failure when it was an auth rejection,
|
|
48
|
+
* or `null` for any other status.
|
|
49
|
+
*/
|
|
50
|
+
export declare function authRejectedHint(status: number, source: CredentialSource): string | null;
|
|
51
|
+
/** `message`, plus the {@link authRejectedHint} on its own line when one applies. */
|
|
52
|
+
export declare function withAuthHint(message: string, status: number, source: CredentialSource | undefined): string;
|
|
53
|
+
//# sourceMappingURL=credentials.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../src/hub/credentials.ts"],"names":[],"mappings":"AA6BA,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,YAAY,GAAG,aAAa,GAAG,KAAK,GAAG,SAAS,CAAA;AAExF,2EAA2E;AAC3E,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,WAAW,CAAA;AAElD,eAAO,MAAM,kBAAkB,SAAS,CAAA;AAExC,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,CAE5D;AAED,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IACnC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAA;IACjC,oFAAoF;IACpF,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAA;IAC7B,sEAAsE;IACtE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,0FAA0F;IAC1F,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;IAChC,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;IAC3D,+EAA+E;IAC/E,QAAQ,CAAC,WAAW,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,KAAK,iBAAiB,GAAG,IAAI,CAAA;CACpE;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,6FAA6F;AAC7F,qBAAa,uBAAwB,SAAQ,KAAK;gBACpC,MAAM,EAAE,MAAM,GAAG,SAAS;CAWvC;AAID;;;GAGG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAkBjE;AA6BD,2FAA2F;AAC3F,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,gBAAgB,GAAG,mBAAmB,CAehF;AA4BD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,MAAM,GAAG,IAAI,CAGxF;AAED,qFAAqF;AACrF,wBAAgB,YAAY,CAC1B,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,MAAM,CAGR"}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Credential resolution shared by every hub-talking tool: the CLI commands
|
|
3
|
+
* (`deploy`, `deploy-server`, `dev`, `watch`), `scripts/hub/hub.mjs` and the
|
|
4
|
+
* private operator MCP (`@camstack/mcp-dev`). One chain, no copy (D835 sibling
|
|
5
|
+
* of D816).
|
|
6
|
+
*
|
|
7
|
+
* `camstack login` caches a long-lived scoped token in
|
|
8
|
+
* `~/.camstack/<host>.json` (0600); every command picks that session up on
|
|
9
|
+
* its own, so a terminal that ran `login` once needs no further flags.
|
|
10
|
+
*
|
|
11
|
+
* Token precedence (first hit wins):
|
|
12
|
+
* 1. `--token <token>` — explicit one-off
|
|
13
|
+
* 2. `--token-file <path>` — a file the operator handed to a script/CI:
|
|
14
|
+
* a bare token, or a session file in the
|
|
15
|
+
* `~/.camstack/<host>.json` format
|
|
16
|
+
* 3. the admin token file — an expiring, audited `csa_` token (D816) in an
|
|
17
|
+
* owner-only file (`adminTokenFile`)
|
|
18
|
+
* 4. `$CAMSTACK_TOKEN` — still read by the CLI; ops tools pass an env
|
|
19
|
+
* without it (no secret through the environment)
|
|
20
|
+
* 5. the cached session — `camstack login`
|
|
21
|
+
*
|
|
22
|
+
* A password is never an input: nothing here logs in.
|
|
23
|
+
*
|
|
24
|
+
* Server precedence: `--server`, `$CAMSTACK_SERVER`, the token file's
|
|
25
|
+
* `server` (session-format files only), the cached session's `server`.
|
|
26
|
+
* The caller applies its own default when none of these is set.
|
|
27
|
+
*/
|
|
28
|
+
import * as fs from 'node:fs';
|
|
29
|
+
export const ADMIN_TOKEN_PREFIX = 'csa_';
|
|
30
|
+
/** The tier a token buys. Prefix only: the hub still decides on every call. */
|
|
31
|
+
export function credentialTier(token) {
|
|
32
|
+
return token.startsWith(ADMIN_TOKEN_PREFIX) ? 'admin' : 'protected';
|
|
33
|
+
}
|
|
34
|
+
/** No token could be resolved from any source. The message tells the operator what to do. */
|
|
35
|
+
export class MissingCredentialsError extends Error {
|
|
36
|
+
constructor(server) {
|
|
37
|
+
super([
|
|
38
|
+
`Not logged in to ${server ?? 'any hub'}.`,
|
|
39
|
+
' Run `camstack login`: it caches a token in ~/.camstack/<host>.json that every',
|
|
40
|
+
' command reuses automatically. For scripts/CI, pass --token-file <path> with a',
|
|
41
|
+
' token issued on Identity → Tokens (or a copied ~/.camstack session file).',
|
|
42
|
+
].join('\n'));
|
|
43
|
+
this.name = 'MissingCredentialsError';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const GROUP_OR_OTHER_BITS = 0o077;
|
|
47
|
+
/**
|
|
48
|
+
* Read a token file: a single bare token, or a JSON session file
|
|
49
|
+
* (`{ "server": "...", "token": "..." }`, extra fields ignored).
|
|
50
|
+
*/
|
|
51
|
+
export function readTokenFile(filePath) {
|
|
52
|
+
let raw;
|
|
53
|
+
let mode;
|
|
54
|
+
try {
|
|
55
|
+
raw = fs.readFileSync(filePath, 'utf8');
|
|
56
|
+
mode = fs.statSync(filePath).mode;
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
60
|
+
throw new Error(`Cannot read token file ${filePath}: ${reason}`, {
|
|
61
|
+
cause: err,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
const warning = process.platform !== 'win32' && (mode & GROUP_OR_OTHER_BITS) !== 0
|
|
65
|
+
? `Token file ${filePath} is readable by other users — run \`chmod 600 ${filePath}\`.`
|
|
66
|
+
: undefined;
|
|
67
|
+
const parsed = parseTokenFile(raw.trim(), filePath);
|
|
68
|
+
return warning ? { ...parsed, warning } : parsed;
|
|
69
|
+
}
|
|
70
|
+
function parseTokenFile(content, filePath) {
|
|
71
|
+
if (content.length === 0)
|
|
72
|
+
throw new Error(`Token file ${filePath} is empty.`);
|
|
73
|
+
if (content.startsWith('{'))
|
|
74
|
+
return parseSessionJson(content, filePath);
|
|
75
|
+
if (/\s/.test(content)) {
|
|
76
|
+
throw new Error(`Token file ${filePath} must hold exactly one token (found several lines).`);
|
|
77
|
+
}
|
|
78
|
+
return { token: content };
|
|
79
|
+
}
|
|
80
|
+
function parseSessionJson(content, filePath) {
|
|
81
|
+
let json;
|
|
82
|
+
try {
|
|
83
|
+
json = JSON.parse(content);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
throw new Error(`Token file ${filePath} looks like JSON but does not parse.`);
|
|
87
|
+
}
|
|
88
|
+
if (json === null || typeof json !== 'object') {
|
|
89
|
+
throw new Error(`Token file ${filePath}: expected a JSON object with a "token" field.`);
|
|
90
|
+
}
|
|
91
|
+
const token = Reflect.get(json, 'token');
|
|
92
|
+
const server = Reflect.get(json, 'server');
|
|
93
|
+
if (typeof token !== 'string' || token.length === 0) {
|
|
94
|
+
throw new Error(`Token file ${filePath}: the JSON has no string "token" field.`);
|
|
95
|
+
}
|
|
96
|
+
return typeof server === 'string' && server.length > 0 ? { token, server } : { token };
|
|
97
|
+
}
|
|
98
|
+
/** Resolve `{server, token}` for a hub command. Throws {@link MissingCredentialsError}. */
|
|
99
|
+
export function resolveCredentials(inputs) {
|
|
100
|
+
const env = inputs.env ?? process.env;
|
|
101
|
+
const file = inputs.tokenFile ? readTokenFile(inputs.tokenFile) : null;
|
|
102
|
+
// Key the session lookup on the hub actually targeted: with no explicit
|
|
103
|
+
// server, `loadSession` falls back to the NEWEST session file, which may
|
|
104
|
+
// belong to a different hub than $CAMSTACK_SERVER.
|
|
105
|
+
const targeted = inputs.server ?? env['CAMSTACK_SERVER'] ?? file?.server;
|
|
106
|
+
const session = inputs.loadSession(targeted);
|
|
107
|
+
const server = targeted ?? session?.server;
|
|
108
|
+
const adminFile = inputs.adminTokenFile ? readTokenFile(inputs.adminTokenFile) : null;
|
|
109
|
+
const picked = pickToken(inputs.token, file, adminFile, env['CAMSTACK_TOKEN'], session);
|
|
110
|
+
if (!picked)
|
|
111
|
+
throw new MissingCredentialsError(server);
|
|
112
|
+
const warning = picked.source === 'admin-token' ? adminFile?.warning : file?.warning;
|
|
113
|
+
const tier = credentialTier(picked.token);
|
|
114
|
+
return warning ? { server, ...picked, tier, warning } : { server, ...picked, tier };
|
|
115
|
+
}
|
|
116
|
+
function pickToken(flag, file, adminFile, envToken, session) {
|
|
117
|
+
if (flag)
|
|
118
|
+
return { token: flag, source: 'flag' };
|
|
119
|
+
if (file)
|
|
120
|
+
return { token: file.token, source: 'token-file' };
|
|
121
|
+
if (adminFile)
|
|
122
|
+
return { token: adminFile.token, source: 'admin-token' };
|
|
123
|
+
if (envToken)
|
|
124
|
+
return { token: envToken, source: 'env' };
|
|
125
|
+
if (session)
|
|
126
|
+
return { token: session.token, source: 'session' };
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
const REJECTION_ADVICE = {
|
|
130
|
+
session: 'The hub rejected the cached session token (revoked or expired). Run `camstack login` again.',
|
|
131
|
+
'token-file': 'The hub rejected the token from the token file (revoked, expired or lacking scope) — ask the operator who issued it for a new one.',
|
|
132
|
+
'admin-token': 'The hub rejected the admin token (revoked, expired, or its creator is no longer an admin) — run `camstack login --admin` for a new one.',
|
|
133
|
+
env: 'The hub rejected $CAMSTACK_TOKEN (revoked, expired or lacking scope).',
|
|
134
|
+
flag: 'The hub rejected the --token value (revoked, expired or lacking scope).',
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* The line to append to an HTTP failure when it was an auth rejection,
|
|
138
|
+
* or `null` for any other status.
|
|
139
|
+
*/
|
|
140
|
+
export function authRejectedHint(status, source) {
|
|
141
|
+
if (status !== 401 && status !== 403)
|
|
142
|
+
return null;
|
|
143
|
+
return REJECTION_ADVICE[source];
|
|
144
|
+
}
|
|
145
|
+
/** `message`, plus the {@link authRejectedHint} on its own line when one applies. */
|
|
146
|
+
export function withAuthHint(message, status, source) {
|
|
147
|
+
const hint = source ? authRejectedHint(status, source) : null;
|
|
148
|
+
return hint ? `${message}\n ${hint}` : message;
|
|
149
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type HubTlsConfig } from './hub-tls.js';
|
|
2
|
+
export type HubHttpMethod = 'GET' | 'POST';
|
|
3
|
+
export interface HubTransportRequest {
|
|
4
|
+
readonly url: string;
|
|
5
|
+
readonly method: HubHttpMethod;
|
|
6
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
7
|
+
readonly body?: string;
|
|
8
|
+
readonly timeoutMs: number;
|
|
9
|
+
readonly maxBytes: number;
|
|
10
|
+
readonly tls: HubTlsConfig;
|
|
11
|
+
}
|
|
12
|
+
export interface HubTransportResponse {
|
|
13
|
+
readonly status: number;
|
|
14
|
+
readonly text: string;
|
|
15
|
+
}
|
|
16
|
+
/** The wire, injectable so tests never open a socket. */
|
|
17
|
+
export type HubTransport = (req: HubTransportRequest) => Promise<HubTransportResponse>;
|
|
18
|
+
export declare class HubHttpError extends Error {
|
|
19
|
+
readonly status: number;
|
|
20
|
+
readonly path: string;
|
|
21
|
+
constructor(message: string, status: number, path: string);
|
|
22
|
+
}
|
|
23
|
+
/** The hub answered with a tRPC error envelope. */
|
|
24
|
+
export declare class HubRpcError extends Error {
|
|
25
|
+
readonly code: string | undefined;
|
|
26
|
+
readonly path: string;
|
|
27
|
+
readonly status: number;
|
|
28
|
+
constructor(message: string, code: string | undefined, path: string, status: number);
|
|
29
|
+
}
|
|
30
|
+
export declare const DEFAULT_TIMEOUT_MS = 60000;
|
|
31
|
+
export declare const DEFAULT_MAX_BYTES: number;
|
|
32
|
+
export declare const nodeHubTransport: HubTransport;
|
|
33
|
+
interface EncodedInput {
|
|
34
|
+
readonly json: unknown;
|
|
35
|
+
readonly meta?: {
|
|
36
|
+
readonly values: Readonly<Record<string, readonly string[]>>;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The `{ json, meta }` envelope for an input. A `Date` travels as its ISO
|
|
41
|
+
* string and is named in `meta.values` so the hub's superjson revives it.
|
|
42
|
+
*/
|
|
43
|
+
export declare function encodeTrpcInput(input: unknown): EncodedInput;
|
|
44
|
+
export interface HubClientOptions {
|
|
45
|
+
readonly baseUrl: string;
|
|
46
|
+
readonly token: string;
|
|
47
|
+
readonly tls?: HubTlsConfig;
|
|
48
|
+
readonly transport?: HubTransport;
|
|
49
|
+
readonly timeoutMs?: number;
|
|
50
|
+
readonly maxBytes?: number;
|
|
51
|
+
}
|
|
52
|
+
export interface HubClient {
|
|
53
|
+
call(method: HubHttpMethod, path: string, input?: unknown): Promise<unknown>;
|
|
54
|
+
}
|
|
55
|
+
export declare function createHubClient(options: HubClientOptions): HubClient;
|
|
56
|
+
export {};
|
|
57
|
+
//# sourceMappingURL=hub-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hub-client.d.ts","sourceRoot":"","sources":["../../src/hub/hub-client.ts"],"names":[],"mappings":"AASA,OAAO,EAAqC,KAAK,YAAY,EAAE,MAAM,cAAc,CAAA;AAEnF,MAAM,MAAM,aAAa,GAAG,KAAK,GAAG,MAAM,CAAA;AAE1C,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAA;IAC9B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAClD,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,GAAG,EAAE,YAAY,CAAA;CAC3B;AAED,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACtB;AAED,yDAAyD;AACzD,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,mBAAmB,KAAK,OAAO,CAAC,oBAAoB,CAAC,CAAA;AAEtF,qBAAa,YAAa,SAAQ,KAAK;IAGnC,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM;gBAFrB,OAAO,EAAE,MAAM,EACN,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM;CAKxB;AAED,mDAAmD;AACnD,qBAAa,WAAY,SAAQ,KAAK;IAGlC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS;IACjC,QAAQ,CAAC,IAAI,EAAE,MAAM;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM;gBAHvB,OAAO,EAAE,MAAM,EACN,IAAI,EAAE,MAAM,GAAG,SAAS,EACxB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM;CAK1B;AAED,eAAO,MAAM,kBAAkB,QAAS,CAAA;AACxC,eAAO,MAAM,iBAAiB,QAAmB,CAAA;AAEjD,eAAO,MAAM,gBAAgB,EAAE,YAwC3B,CAAA;AAEJ,UAAU,YAAY;IACpB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;IACtB,QAAQ,CAAC,IAAI,CAAC,EAAE;QACd,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,CAAA;KAC7D,CAAA;CACF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,YAAY,CAoB5D;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,GAAG,CAAC,EAAE,YAAY,CAAA;IAC3B,QAAQ,CAAC,SAAS,CAAC,EAAE,YAAY,CAAA;IACjC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAC3B;AAED,MAAM,WAAW,SAAS;IACxB,IAAI,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CAC7E;AA2BD,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,SAAS,CAqDpE"}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tRPC caller for the hub, shared by `scripts/hub/hub.mjs` and the operator
|
|
3
|
+
* MCP. It speaks the wire (`/trpc/<path>`, `{ json }` envelope, superjson Date
|
|
4
|
+
* metadata) over `node:https` with the TLS trust from `hub-tls.ts`; there is
|
|
5
|
+
* no login in here — the bearer comes from the credential chain.
|
|
6
|
+
*/
|
|
7
|
+
import * as http from 'node:http';
|
|
8
|
+
import * as https from 'node:https';
|
|
9
|
+
import { Buffer } from 'node:buffer';
|
|
10
|
+
import { createHubAgent, explainTlsFailure } from './hub-tls.js';
|
|
11
|
+
export class HubHttpError extends Error {
|
|
12
|
+
status;
|
|
13
|
+
path;
|
|
14
|
+
constructor(message, status, path) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.status = status;
|
|
17
|
+
this.path = path;
|
|
18
|
+
this.name = 'HubHttpError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** The hub answered with a tRPC error envelope. */
|
|
22
|
+
export class HubRpcError extends Error {
|
|
23
|
+
code;
|
|
24
|
+
path;
|
|
25
|
+
status;
|
|
26
|
+
constructor(message, code, path, status) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.path = path;
|
|
30
|
+
this.status = status;
|
|
31
|
+
this.name = 'HubRpcError';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export const DEFAULT_TIMEOUT_MS = 60_000;
|
|
35
|
+
export const DEFAULT_MAX_BYTES = 64 * 1024 * 1024;
|
|
36
|
+
export const nodeHubTransport = (req) => new Promise((resolve, reject) => {
|
|
37
|
+
const parsed = new URL(req.url);
|
|
38
|
+
const isHttps = parsed.protocol === 'https:';
|
|
39
|
+
const options = {
|
|
40
|
+
protocol: parsed.protocol,
|
|
41
|
+
hostname: parsed.hostname,
|
|
42
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
43
|
+
path: `${parsed.pathname}${parsed.search}`,
|
|
44
|
+
method: req.method,
|
|
45
|
+
headers: { ...req.headers },
|
|
46
|
+
timeout: req.timeoutMs,
|
|
47
|
+
...(isHttps ? { agent: createHubAgent(req.tls) } : {}),
|
|
48
|
+
};
|
|
49
|
+
const onResponse = (res) => {
|
|
50
|
+
const chunks = [];
|
|
51
|
+
let size = 0;
|
|
52
|
+
res.on('data', (chunk) => {
|
|
53
|
+
size += chunk.length;
|
|
54
|
+
if (size > req.maxBytes) {
|
|
55
|
+
res.destroy(new Error(`response larger than ${req.maxBytes} bytes — narrow the query`));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
chunks.push(chunk);
|
|
59
|
+
});
|
|
60
|
+
res.on('end', () => resolve({
|
|
61
|
+
status: res.statusCode ?? 0,
|
|
62
|
+
text: Buffer.concat(chunks).toString('utf8'),
|
|
63
|
+
}));
|
|
64
|
+
res.on('error', reject);
|
|
65
|
+
};
|
|
66
|
+
const request = isHttps ? https.request(options, onResponse) : http.request(options, onResponse);
|
|
67
|
+
request.on('error', reject);
|
|
68
|
+
request.on('timeout', () => {
|
|
69
|
+
request.destroy(new Error(`hub request to ${parsed.host} timed out after ${req.timeoutMs}ms`));
|
|
70
|
+
});
|
|
71
|
+
if (req.body !== undefined)
|
|
72
|
+
request.write(req.body);
|
|
73
|
+
request.end();
|
|
74
|
+
});
|
|
75
|
+
/**
|
|
76
|
+
* The `{ json, meta }` envelope for an input. A `Date` travels as its ISO
|
|
77
|
+
* string and is named in `meta.values` so the hub's superjson revives it.
|
|
78
|
+
*/
|
|
79
|
+
export function encodeTrpcInput(input) {
|
|
80
|
+
const dates = {};
|
|
81
|
+
const walk = (value, at) => {
|
|
82
|
+
if (value instanceof Date) {
|
|
83
|
+
dates[at] = ['Date'];
|
|
84
|
+
return value.toISOString();
|
|
85
|
+
}
|
|
86
|
+
if (Array.isArray(value))
|
|
87
|
+
return value.map((v, i) => walk(v, at === '' ? `${i}` : `${at}.${i}`));
|
|
88
|
+
if (value !== null && typeof value === 'object') {
|
|
89
|
+
const out = {};
|
|
90
|
+
for (const [k, v] of Object.entries(value)) {
|
|
91
|
+
if (v === undefined)
|
|
92
|
+
continue;
|
|
93
|
+
out[k] = walk(v, at === '' ? k : `${at}.${k}`);
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
return value;
|
|
98
|
+
};
|
|
99
|
+
const json = walk(input, '');
|
|
100
|
+
return Object.keys(dates).length > 0 ? { json, meta: { values: dates } } : { json };
|
|
101
|
+
}
|
|
102
|
+
function readError(body) {
|
|
103
|
+
if (body === null || typeof body !== 'object')
|
|
104
|
+
return null;
|
|
105
|
+
const error = Reflect.get(body, 'error');
|
|
106
|
+
if (error === null || typeof error !== 'object')
|
|
107
|
+
return null;
|
|
108
|
+
const inner = Reflect.get(error, 'json') ?? error;
|
|
109
|
+
const message = inner !== null && typeof inner === 'object' ? Reflect.get(inner, 'message') : undefined;
|
|
110
|
+
const code = inner !== null && typeof inner === 'object' ? Reflect.get(inner, 'code') : undefined;
|
|
111
|
+
return {
|
|
112
|
+
message: typeof message === 'string' ? message : JSON.stringify(error).slice(0, 400),
|
|
113
|
+
code: typeof code === 'string' ? code : undefined,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function parseJson(text) {
|
|
117
|
+
try {
|
|
118
|
+
return JSON.parse(text);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
export function createHubClient(options) {
|
|
125
|
+
const transport = options.transport ?? nodeHubTransport;
|
|
126
|
+
const base = options.baseUrl.replace(/\/+$/, '');
|
|
127
|
+
return {
|
|
128
|
+
async call(method, path, input) {
|
|
129
|
+
const headers = {
|
|
130
|
+
'content-type': 'application/json',
|
|
131
|
+
authorization: `Bearer ${options.token}`,
|
|
132
|
+
};
|
|
133
|
+
let url = `${base}/trpc/${path}`;
|
|
134
|
+
let body;
|
|
135
|
+
if (method === 'POST') {
|
|
136
|
+
body = JSON.stringify(encodeTrpcInput(input));
|
|
137
|
+
}
|
|
138
|
+
else if (input !== undefined) {
|
|
139
|
+
url += `?input=${encodeURIComponent(JSON.stringify(encodeTrpcInput(input)))}`;
|
|
140
|
+
}
|
|
141
|
+
let res;
|
|
142
|
+
try {
|
|
143
|
+
res = await transport({
|
|
144
|
+
url,
|
|
145
|
+
method,
|
|
146
|
+
headers,
|
|
147
|
+
...(body !== undefined ? { body } : {}),
|
|
148
|
+
timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
149
|
+
maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
|
|
150
|
+
tls: options.tls ?? {},
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
const explained = explainTlsFailure(base, err);
|
|
155
|
+
if (explained)
|
|
156
|
+
throw new Error(explained, { cause: err });
|
|
157
|
+
throw err;
|
|
158
|
+
}
|
|
159
|
+
const parsed = parseJson(res.text);
|
|
160
|
+
const rpcError = readError(parsed);
|
|
161
|
+
if (rpcError)
|
|
162
|
+
throw new HubRpcError(rpcError.message, rpcError.code, path, res.status);
|
|
163
|
+
if (res.status < 200 || res.status >= 300) {
|
|
164
|
+
throw new HubHttpError(`${path}: HTTP ${res.status} ${res.text.slice(0, 200)}`, res.status, path);
|
|
165
|
+
}
|
|
166
|
+
if (parsed === null || typeof parsed !== 'object') {
|
|
167
|
+
throw new HubHttpError(`${path}: response is not a tRPC envelope`, res.status, path);
|
|
168
|
+
}
|
|
169
|
+
const result = Reflect.get(parsed, 'result');
|
|
170
|
+
const data = result !== null && typeof result === 'object' ? Reflect.get(result, 'data') : undefined;
|
|
171
|
+
if (data !== null && typeof data === 'object' && 'json' in data)
|
|
172
|
+
return Reflect.get(data, 'json');
|
|
173
|
+
return data;
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import * as https from 'node:https';
|
|
2
|
+
export interface HubTlsConfig {
|
|
3
|
+
/** PEM text trusted for this hub (a pinned leaf or the hub's CA). */
|
|
4
|
+
readonly ca?: string;
|
|
5
|
+
/** Where `ca` came from, for error messages. */
|
|
6
|
+
readonly caFile?: string;
|
|
7
|
+
}
|
|
8
|
+
/** `~/.camstack/<host>.ca.pem` — the default pin file for a hub. */
|
|
9
|
+
export declare function hubCaFileForServer(serverUrl: string, dir?: string): string;
|
|
10
|
+
/** The trust configuration for `serverUrl`; empty when the system store should decide. */
|
|
11
|
+
export declare function resolveHubTls(serverUrl: string, env?: Readonly<Record<string, string | undefined>>, dir?: string): HubTlsConfig;
|
|
12
|
+
/** A TLS failure, with the one fix that applies. */
|
|
13
|
+
export declare function explainTlsFailure(serverUrl: string, err: unknown): string | null;
|
|
14
|
+
/** The https agent for hub traffic: the pinned PEM when there is one, else defaults. */
|
|
15
|
+
export declare function createHubAgent(tls: HubTlsConfig): https.Agent;
|
|
16
|
+
//# sourceMappingURL=hub-tls.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hub-tls.d.ts","sourceRoot":"","sources":["../../src/hub/hub-tls.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AAInC,MAAM,WAAW,YAAY;IAC3B,qEAAqE;IACrE,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAA;IACpB,gDAAgD;IAChD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CACzB;AAED,oEAAoE;AACpE,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,GAAE,MAA4B,GAAG,MAAM,CAE/F;AAED,0FAA0F;AAC1F,wBAAgB,aAAa,CAC3B,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,EAC/D,GAAG,GAAE,MAA4B,GAChC,YAAY,CAcd;AAED,oDAAoD;AACpD,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAiBhF;AAED,wFAAwF;AACxF,wBAAgB,cAAc,CAAC,GAAG,EAAE,YAAY,GAAG,KAAK,CAAC,KAAK,CAK7D"}
|