@camstack/develop 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/hub/admin-token-store.d.ts +53 -0
  2. package/dist/hub/admin-token-store.d.ts.map +1 -0
  3. package/dist/hub/admin-token-store.js +139 -0
  4. package/dist/hub/credentials.d.ts +53 -0
  5. package/dist/hub/credentials.d.ts.map +1 -0
  6. package/dist/hub/credentials.js +151 -0
  7. package/dist/hub/hub-address.d.ts +24 -0
  8. package/dist/hub/hub-address.d.ts.map +1 -0
  9. package/dist/hub/hub-address.js +87 -0
  10. package/dist/hub/hub-client.d.ts +57 -0
  11. package/dist/hub/hub-client.d.ts.map +1 -0
  12. package/dist/hub/hub-client.js +176 -0
  13. package/dist/hub/hub-tls.d.ts +16 -0
  14. package/dist/hub/hub-tls.d.ts.map +1 -0
  15. package/dist/hub/hub-tls.js +67 -0
  16. package/dist/hub/hub-url.d.ts +17 -0
  17. package/dist/hub/hub-url.d.ts.map +1 -0
  18. package/dist/hub/hub-url.js +54 -0
  19. package/dist/hub/session-store.d.ts +55 -0
  20. package/dist/hub/session-store.d.ts.map +1 -0
  21. package/dist/hub/session-store.js +178 -0
  22. package/dist/hub-discovery/hub-candidates.d.ts +53 -0
  23. package/dist/hub-discovery/hub-candidates.d.ts.map +1 -0
  24. package/dist/hub-discovery/hub-candidates.js +103 -0
  25. package/dist/hub-discovery/index.d.ts +4 -0
  26. package/dist/hub-discovery/index.d.ts.map +1 -0
  27. package/dist/hub-discovery/index.js +3 -0
  28. package/dist/hub-discovery/mdns-browse.d.ts +51 -0
  29. package/dist/hub-discovery/mdns-browse.d.ts.map +1 -0
  30. package/dist/hub-discovery/mdns-browse.js +116 -0
  31. package/dist/index.d.ts +15 -2
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +11 -2
  34. package/dist/scaffold/addon.d.ts.map +1 -1
  35. package/dist/scaffold/addon.js +6 -0
  36. package/dist/types.d.ts +6 -1
  37. package/dist/types.d.ts.map +1 -1
  38. package/package.json +10 -1
  39. package/skills/README.md +3 -0
  40. package/skills/camstack-addon.md +376 -98
  41. package/skills/camstack-capability.md +184 -77
  42. 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":"AA8BA,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,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,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,CAgBhF;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,151 @@
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
+ import { normalizeHubAddress } from './hub-address.js';
30
+ export const ADMIN_TOKEN_PREFIX = 'csa_';
31
+ /** The tier a token buys. Prefix only: the hub still decides on every call. */
32
+ export function credentialTier(token) {
33
+ return token.startsWith(ADMIN_TOKEN_PREFIX) ? 'admin' : 'protected';
34
+ }
35
+ /** No token could be resolved from any source. The message tells the operator what to do. */
36
+ export class MissingCredentialsError extends Error {
37
+ constructor(server) {
38
+ super([
39
+ `Not logged in to ${server ?? 'any hub'}.`,
40
+ ' Run `camstack login`: it caches a token in ~/.camstack/<host>.json that every',
41
+ ' command reuses automatically. For scripts/CI, pass --token-file <path> with a',
42
+ ' token issued on Identity → Tokens (or a copied ~/.camstack session file).',
43
+ ].join('\n'));
44
+ this.name = 'MissingCredentialsError';
45
+ }
46
+ }
47
+ const GROUP_OR_OTHER_BITS = 0o077;
48
+ /**
49
+ * Read a token file: a single bare token, or a JSON session file
50
+ * (`{ "server": "...", "token": "..." }`, extra fields ignored).
51
+ */
52
+ export function readTokenFile(filePath) {
53
+ let raw;
54
+ let mode;
55
+ try {
56
+ raw = fs.readFileSync(filePath, 'utf8');
57
+ mode = fs.statSync(filePath).mode;
58
+ }
59
+ catch (err) {
60
+ const reason = err instanceof Error ? err.message : String(err);
61
+ throw new Error(`Cannot read token file ${filePath}: ${reason}`, {
62
+ cause: err,
63
+ });
64
+ }
65
+ const warning = process.platform !== 'win32' && (mode & GROUP_OR_OTHER_BITS) !== 0
66
+ ? `Token file ${filePath} is readable by other users — run \`chmod 600 ${filePath}\`.`
67
+ : undefined;
68
+ const parsed = parseTokenFile(raw.trim(), filePath);
69
+ return warning ? { ...parsed, warning } : parsed;
70
+ }
71
+ function parseTokenFile(content, filePath) {
72
+ if (content.length === 0)
73
+ throw new Error(`Token file ${filePath} is empty.`);
74
+ if (content.startsWith('{'))
75
+ return parseSessionJson(content, filePath);
76
+ if (/\s/.test(content)) {
77
+ throw new Error(`Token file ${filePath} must hold exactly one token (found several lines).`);
78
+ }
79
+ return { token: content };
80
+ }
81
+ function parseSessionJson(content, filePath) {
82
+ let json;
83
+ try {
84
+ json = JSON.parse(content);
85
+ }
86
+ catch {
87
+ throw new Error(`Token file ${filePath} looks like JSON but does not parse.`);
88
+ }
89
+ if (json === null || typeof json !== 'object') {
90
+ throw new Error(`Token file ${filePath}: expected a JSON object with a "token" field.`);
91
+ }
92
+ const token = Reflect.get(json, 'token');
93
+ const server = Reflect.get(json, 'server');
94
+ if (typeof token !== 'string' || token.length === 0) {
95
+ throw new Error(`Token file ${filePath}: the JSON has no string "token" field.`);
96
+ }
97
+ return typeof server === 'string' && server.length > 0 ? { token, server } : { token };
98
+ }
99
+ /** Resolve `{server, token}` for a hub command. Throws {@link MissingCredentialsError}. */
100
+ export function resolveCredentials(inputs) {
101
+ const env = inputs.env ?? process.env;
102
+ const file = inputs.tokenFile ? readTokenFile(inputs.tokenFile) : null;
103
+ // Key the session lookup on the hub actually targeted: with no explicit
104
+ // server, `loadSession` falls back to the NEWEST session file, which may
105
+ // belong to a different hub than $CAMSTACK_SERVER.
106
+ const typed = inputs.server ?? env['CAMSTACK_SERVER'];
107
+ const targeted = typed ? normalizeHubAddress(typed) : file?.server;
108
+ const session = inputs.loadSession(targeted);
109
+ const server = targeted ?? session?.server;
110
+ const adminFile = inputs.adminTokenFile ? readTokenFile(inputs.adminTokenFile) : null;
111
+ const picked = pickToken(inputs.token, file, adminFile, env['CAMSTACK_TOKEN'], session);
112
+ if (!picked)
113
+ throw new MissingCredentialsError(server);
114
+ const warning = picked.source === 'admin-token' ? adminFile?.warning : file?.warning;
115
+ const tier = credentialTier(picked.token);
116
+ return warning ? { server, ...picked, tier, warning } : { server, ...picked, tier };
117
+ }
118
+ function pickToken(flag, file, adminFile, envToken, session) {
119
+ if (flag)
120
+ return { token: flag, source: 'flag' };
121
+ if (file)
122
+ return { token: file.token, source: 'token-file' };
123
+ if (adminFile)
124
+ return { token: adminFile.token, source: 'admin-token' };
125
+ if (envToken)
126
+ return { token: envToken, source: 'env' };
127
+ if (session)
128
+ return { token: session.token, source: 'session' };
129
+ return null;
130
+ }
131
+ const REJECTION_ADVICE = {
132
+ session: 'The hub rejected the cached session token (revoked or expired). Run `camstack login` again.',
133
+ '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.',
134
+ '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.',
135
+ env: 'The hub rejected $CAMSTACK_TOKEN (revoked, expired or lacking scope).',
136
+ flag: 'The hub rejected the --token value (revoked, expired or lacking scope).',
137
+ };
138
+ /**
139
+ * The line to append to an HTTP failure when it was an auth rejection,
140
+ * or `null` for any other status.
141
+ */
142
+ export function authRejectedHint(status, source) {
143
+ if (status !== 401 && status !== 403)
144
+ return null;
145
+ return REJECTION_ADVICE[source];
146
+ }
147
+ /** `message`, plus the {@link authRejectedHint} on its own line when one applies. */
148
+ export function withAuthHint(message, status, source) {
149
+ const hint = source ? authRejectedHint(status, source) : null;
150
+ return hint ? `${message}\n ${hint}` : message;
151
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The ONE parser for "which hub": every tool that takes a server (the CLI's
3
+ * login/whoami/deploy/dev/watch, `scripts/hub/hub.mjs`, the operator MCP)
4
+ * passes its input through {@link normalizeHubAddress}, so `192.168.1.50`,
5
+ * `hub.local:4443` and `https://[fe80::1]:4443/` all name the same canonical
6
+ * `https://<host>:<port>` and a typo fails the same way everywhere.
7
+ *
8
+ * The hub API is https only (self-signed on the LAN, trusted per hub): an
9
+ * `http://` address is refused with a message instead of being rewritten, so
10
+ * the operator learns the scheme rather than silently talking to another port.
11
+ */
12
+ export declare const DEFAULT_HUB_PORT = 4443;
13
+ export declare class HubAddressError extends Error {
14
+ constructor(message: string);
15
+ }
16
+ /**
17
+ * `https://<host>:<port>` (default port 4443, scheme https, lower-case host,
18
+ * no path or trailing slash). Throws {@link HubAddressError} on an empty value,
19
+ * an `http://` or other scheme, a bad port or an unparsable host.
20
+ */
21
+ export declare function normalizeHubAddress(input: string): string;
22
+ /** {@link normalizeHubAddress} for a prompt validator: the message, or `undefined` when valid. */
23
+ export declare function validateHubAddress(input: string): string | undefined;
24
+ //# sourceMappingURL=hub-address.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hub-address.d.ts","sourceRoot":"","sources":["../../src/hub/hub-address.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,eAAO,MAAM,gBAAgB,OAAO,CAAA;AAEpC,qBAAa,eAAgB,SAAQ,KAAK;gBAC5B,OAAO,EAAE,MAAM;CAI5B;AAgCD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CA4BzD;AAED,kGAAkG;AAClG,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOpE"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The ONE parser for "which hub": every tool that takes a server (the CLI's
3
+ * login/whoami/deploy/dev/watch, `scripts/hub/hub.mjs`, the operator MCP)
4
+ * passes its input through {@link normalizeHubAddress}, so `192.168.1.50`,
5
+ * `hub.local:4443` and `https://[fe80::1]:4443/` all name the same canonical
6
+ * `https://<host>:<port>` and a typo fails the same way everywhere.
7
+ *
8
+ * The hub API is https only (self-signed on the LAN, trusted per hub): an
9
+ * `http://` address is refused with a message instead of being rewritten, so
10
+ * the operator learns the scheme rather than silently talking to another port.
11
+ */
12
+ export const DEFAULT_HUB_PORT = 4443;
13
+ export class HubAddressError extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = 'HubAddressError';
17
+ }
18
+ }
19
+ const SCHEME = /^([a-z][a-z0-9+.-]*):\/\//i;
20
+ const BRACKETED = /^\[([^\]]+)\](?::(\d+))?$/;
21
+ const HOST_PORT = /^([^:]+)(?::(\d+))?$/;
22
+ function parsePort(raw, input) {
23
+ if (raw === undefined)
24
+ return DEFAULT_HUB_PORT;
25
+ const port = Number.parseInt(raw, 10);
26
+ if (port < 1 || port > 65535) {
27
+ throw new HubAddressError(`"${input}": port ${raw} is out of range (1-65535).`);
28
+ }
29
+ return port;
30
+ }
31
+ function splitAuthority(authority, input) {
32
+ const bracketed = BRACKETED.exec(authority);
33
+ if (bracketed)
34
+ return { host: `[${bracketed[1]}]`, port: parsePort(bracketed[2], input) };
35
+ // A bare IPv6 literal (two or more colons) carries no port: brackets are needed for that.
36
+ if ((authority.match(/:/g) ?? []).length >= 2) {
37
+ return { host: `[${authority}]`, port: DEFAULT_HUB_PORT };
38
+ }
39
+ const plain = HOST_PORT.exec(authority);
40
+ if (!plain)
41
+ throw new HubAddressError(`"${input}" is not a hub address.`);
42
+ return { host: plain[1], port: parsePort(plain[2], input) };
43
+ }
44
+ /**
45
+ * `https://<host>:<port>` (default port 4443, scheme https, lower-case host,
46
+ * no path or trailing slash). Throws {@link HubAddressError} on an empty value,
47
+ * an `http://` or other scheme, a bad port or an unparsable host.
48
+ */
49
+ export function normalizeHubAddress(input) {
50
+ const trimmed = input.trim();
51
+ if (trimmed === '')
52
+ throw new HubAddressError('The hub address is empty.');
53
+ const scheme = SCHEME.exec(trimmed);
54
+ if (scheme) {
55
+ const name = scheme[1].toLowerCase();
56
+ if (name === 'http') {
57
+ throw new HubAddressError(`"${trimmed}": the hub API is https. Use https://<host>:${DEFAULT_HUB_PORT} (or just <host>).`);
58
+ }
59
+ if (name !== 'https') {
60
+ throw new HubAddressError(`"${trimmed}": unsupported scheme "${name}", the hub API is https.`);
61
+ }
62
+ }
63
+ const rest = scheme ? trimmed.slice(scheme[0].length) : trimmed;
64
+ const authority = rest.split(/[/?#]/, 1)[0] ?? '';
65
+ if (authority === '' || authority.includes('@')) {
66
+ throw new HubAddressError(`"${trimmed}" is not a hub address (expected host[:port]).`);
67
+ }
68
+ const { host, port } = splitAuthority(authority, trimmed);
69
+ let hostname;
70
+ try {
71
+ hostname = new URL(`https://${host}`).hostname;
72
+ }
73
+ catch {
74
+ throw new HubAddressError(`"${trimmed}": "${host}" is not a valid host name or address.`);
75
+ }
76
+ return `https://${hostname}:${port}`;
77
+ }
78
+ /** {@link normalizeHubAddress} for a prompt validator: the message, or `undefined` when valid. */
79
+ export function validateHubAddress(input) {
80
+ try {
81
+ normalizeHubAddress(input);
82
+ return undefined;
83
+ }
84
+ catch (err) {
85
+ return err instanceof HubAddressError ? err.message : String(err);
86
+ }
87
+ }
@@ -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,YAA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