@camstack/develop 0.1.15 → 0.1.17

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.
@@ -1,14 +1,21 @@
1
- export type CredentialSource = 'flag' | 'token-file' | 'admin-token' | 'env' | 'session';
1
+ export type CredentialSource = 'flag' | 'token-file' | 'env' | 'session';
2
2
  /** What a credential may reach locally before the hub validates every call. */
3
3
  export type CredentialTier = 'admin' | 'protected';
4
- export declare const ADMIN_TOKEN_PREFIX = "csa_";
5
4
  export interface CredentialTierOptions {
6
5
  /** When the token came from a cached session file that recorded admin role. */
7
6
  readonly sessionIsAdmin?: boolean;
8
7
  }
9
- /** Decode a JWT payload for a local tier hint — no signature check. */
8
+ /** The claims of a JWT, without a signature check; `null` when `token` is not a JWT. */
9
+ export declare function jwtClaims(token: string): Readonly<Record<string, unknown>> | null;
10
+ /** Decode a JWT payload for a local tier hint; no signature check. */
10
11
  export declare function jwtPayloadIsAdmin(token: string): boolean;
11
- /** The tier a token buys locally; the hub still decides on every call. */
12
+ /** When a JWT expires (epoch ms), or `undefined` for a token with no `exp` claim. */
13
+ export declare function jwtExpiryMs(token: string): number | undefined;
14
+ /**
15
+ * The tier a token buys locally, from its CLAIMS only (or the session's recorded
16
+ * role). A token with no readable claims is `protected` here; the async resolver
17
+ * asks the hub (`whoami`) before settling on that. The hub still decides on every call.
18
+ */
12
19
  export declare function credentialTier(token: string, opts?: CredentialTierOptions): CredentialTier;
13
20
  export interface ResolvedCredentials {
14
21
  readonly server: string | undefined;
@@ -23,6 +30,10 @@ export interface CachedSessionLike {
23
30
  readonly token: string;
24
31
  /** Copied from `camstack login` when the hub reported an admin user. */
25
32
  readonly isAdmin?: boolean;
33
+ /** The `csr_...` token that renews the session; absent on older files. */
34
+ readonly refreshToken?: string;
35
+ /** When `token` expires (epoch ms); absent on older files (then the JWT `exp`). */
36
+ readonly expiresAt?: number;
26
37
  }
27
38
  export interface CredentialInputs {
28
39
  readonly server?: string;
@@ -39,7 +50,7 @@ export interface TokenFileContents {
39
50
  }
40
51
  /** No token could be resolved from any source. The message tells the operator what to do. */
41
52
  export declare class MissingCredentialsError extends Error {
42
- constructor(server: string | undefined);
53
+ constructor(server: string | undefined, reason?: string);
43
54
  }
44
55
  /**
45
56
  * Read a token file: a single bare token, or a JSON session file
@@ -1 +1 @@
1
- {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../src/hub/credentials.ts"],"names":[],"mappings":"AA2BA,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,YAAY,GAAG,aAAa,GAAG,KAAK,GAAG,SAAS,CAAA;AAExF,+EAA+E;AAC/E,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,WAAW,CAAA;AAElD,eAAO,MAAM,kBAAkB,SAAS,CAAA;AAGxC,MAAM,WAAW,qBAAqB;IACpC,+EAA+E;IAC/E,QAAQ,CAAC,cAAc,CAAC,EAAE,OAAO,CAAA;CAClC;AAED,uEAAuE;AACvE,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAYxD;AAED,0EAA0E;AAC1E,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,qBAAqB,GAAG,cAAc,CAK1F;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,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;IACtB,wEAAwE;IACxE,QAAQ,CAAC,OAAO,CAAC,EAAE,O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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,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,EAAE,MAAM,CAAC,EAAE,MAAM;CAWxD;AAID;;;GAGG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAkBjE;AAmCD,2FAA2F;AAC3F,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,gBAAgB,GAAG,mBAAmB,CAchF;AA6BD;;;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"}
@@ -7,14 +7,17 @@
7
7
  * every command picks that session up on its own, so a terminal that ran
8
8
  * `login` once needs no further flags.
9
9
  *
10
+ * ONE token format; only the SET OF PERMISSIONS differs (admin = everything).
11
+ * Nothing here looks for a specific token file or prefix.
12
+ *
10
13
  * Token precedence (first hit wins):
11
- * 1. `--token <token>` — explicit one-off
12
- * 2. `--token-file <path>` — a file the operator handed to a script/CI:
13
- * a bare token, or a session file in the
14
- * `~/.camstack/<host>.json` format
15
- * 3. `$CAMSTACK_TOKEN` — still read by the CLI; ops tools pass an env
14
+ * 1. `--token <token>` - explicit one-off
15
+ * 2. `--token-file <path>` - an explicit override: a bare token, or a session
16
+ * file in the `~/.camstack/<host>.json` format
17
+ * 3. `$CAMSTACK_TOKEN` - still read by the CLI; ops tools pass an env
16
18
  * without it (no secret through the environment)
17
- * 4. the cached session — `camstack login`
19
+ * 4. the cached session - `camstack login`, refreshed automatically
20
+ * (`session-refresh.ts`)
18
21
  *
19
22
  * A password is never an input: nothing here logs in.
20
23
  *
@@ -24,43 +27,50 @@
24
27
  */
25
28
  import * as fs from 'node:fs';
26
29
  import { normalizeHubAddress } from './hub-address.js';
27
- export const ADMIN_TOKEN_PREFIX = 'csa_';
28
- const SCOPED_TOKEN_PREFIX = 'cst_';
29
- /** Decode a JWT payload for a local tier hint — no signature check. */
30
- export function jwtPayloadIsAdmin(token) {
30
+ /** The claims of a JWT, without a signature check; `null` when `token` is not a JWT. */
31
+ export function jwtClaims(token) {
31
32
  const parts = token.split('.');
32
- if (parts.length < 2)
33
- return false;
33
+ if (parts.length !== 3)
34
+ return null;
34
35
  try {
35
36
  const raw = parts[1].replace(/-/g, '+').replace(/_/g, '/');
36
37
  const padded = raw.padEnd(raw.length + ((4 - (raw.length % 4)) % 4), '=');
37
38
  const json = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
38
- if (json === null || typeof json !== 'object')
39
- return false;
40
- return Reflect.get(json, 'isAdmin') === true;
39
+ if (json === null || typeof json !== 'object' || Array.isArray(json))
40
+ return null;
41
+ return Object.fromEntries(Object.entries(json));
41
42
  }
42
43
  catch {
43
- return false;
44
+ return null;
44
45
  }
45
46
  }
46
- /** The tier a token buys locally; the hub still decides on every call. */
47
+ /** Decode a JWT payload for a local tier hint; no signature check. */
48
+ export function jwtPayloadIsAdmin(token) {
49
+ return jwtClaims(token)?.['isAdmin'] === true;
50
+ }
51
+ /** When a JWT expires (epoch ms), or `undefined` for a token with no `exp` claim. */
52
+ export function jwtExpiryMs(token) {
53
+ const exp = jwtClaims(token)?.['exp'];
54
+ return typeof exp === 'number' ? exp * 1000 : undefined;
55
+ }
56
+ /**
57
+ * The tier a token buys locally, from its CLAIMS only (or the session's recorded
58
+ * role). A token with no readable claims is `protected` here; the async resolver
59
+ * asks the hub (`whoami`) before settling on that. The hub still decides on every call.
60
+ */
47
61
  export function credentialTier(token, opts) {
48
- if (token.startsWith(ADMIN_TOKEN_PREFIX))
49
- return 'admin';
50
- if (token.startsWith(SCOPED_TOKEN_PREFIX))
51
- return 'protected';
52
62
  if (opts?.sessionIsAdmin === true)
53
63
  return 'admin';
54
64
  return jwtPayloadIsAdmin(token) ? 'admin' : 'protected';
55
65
  }
56
66
  /** No token could be resolved from any source. The message tells the operator what to do. */
57
67
  export class MissingCredentialsError extends Error {
58
- constructor(server) {
68
+ constructor(server, reason) {
59
69
  super([
60
- `Not logged in to ${server ?? 'any hub'}.`,
61
- ' Run `camstack login`: it caches a token in ~/.camstack/<host>.json that every',
62
- ' command reuses automatically. For scripts/CI, pass --token-file <path> with a',
63
- ' token issued on Identity → Tokens (or a copied ~/.camstack session file).',
70
+ reason ? `${reason} (${server ?? 'any hub'}).` : `Not logged in to ${server ?? 'any hub'}.`,
71
+ ` Run \`camstack login ${server ?? '<host>'}\` once: every tool uses that session`,
72
+ ' (~/.camstack/<host>.json, refreshed automatically). --token-file is an explicit',
73
+ ' override only, for a token you were handed.',
64
74
  ].join('\n'));
65
75
  this.name = 'MissingCredentialsError';
66
76
  }
@@ -153,7 +163,6 @@ function pickToken(flag, file, envToken, session) {
153
163
  const REJECTION_ADVICE = {
154
164
  session: 'The hub rejected the cached session (revoked or expired). Run `camstack login` again.',
155
165
  '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.',
156
- 'admin-token': 'The hub rejected the admin token (revoked, expired, or its creator is no longer an admin) — pass a fresh token with --token or --token-file.',
157
166
  env: 'The hub rejected $CAMSTACK_TOKEN (revoked, expired or lacking scope).',
158
167
  flag: 'The hub rejected the --token value (revoked, expired or lacking scope).',
159
168
  };
@@ -48,6 +48,12 @@ export interface HubClientOptions {
48
48
  readonly transport?: HubTransport;
49
49
  readonly timeoutMs?: number;
50
50
  readonly maxBytes?: number;
51
+ /**
52
+ * Called ONCE per request when the hub answers 401: return a fresh token
53
+ * (the session was refreshed) to retry with, or `undefined` to surface the
54
+ * 401. Throwing surfaces that error instead.
55
+ */
56
+ readonly onUnauthorized?: () => Promise<string | undefined>;
51
57
  }
52
58
  export interface HubClient {
53
59
  call(method: HubHttpMethod, path: string, input?: unknown): Promise<unknown>;
@@ -1 +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,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AAM,GAAG,SAAS,CAAC,CAAA;CAC5D;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;AA+BD,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,SAAS,CAiEpE"}
@@ -121,56 +121,73 @@ function parseJson(text) {
121
121
  return undefined;
122
122
  }
123
123
  }
124
+ function isUnauthorized(err) {
125
+ return (err instanceof HubRpcError || err instanceof HubHttpError) && err.status === 401;
126
+ }
124
127
  export function createHubClient(options) {
125
128
  const transport = options.transport ?? nodeHubTransport;
126
129
  const base = options.baseUrl.replace(/\/+$/, '');
130
+ let token = options.token;
131
+ async function attempt(method, path, input) {
132
+ const headers = { 'content-type': 'application/json' };
133
+ if (token !== '')
134
+ headers['authorization'] = `Bearer ${token}`;
135
+ let url = `${base}/trpc/${path}`;
136
+ let body;
137
+ if (method === 'POST') {
138
+ body = JSON.stringify(encodeTrpcInput(input));
139
+ }
140
+ else if (input !== undefined) {
141
+ url += `?input=${encodeURIComponent(JSON.stringify(encodeTrpcInput(input)))}`;
142
+ }
143
+ let res;
144
+ try {
145
+ res = await transport({
146
+ url,
147
+ method,
148
+ headers,
149
+ ...(body !== undefined ? { body } : {}),
150
+ timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
151
+ maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,
152
+ tls: options.tls ?? {},
153
+ });
154
+ }
155
+ catch (err) {
156
+ const explained = explainTlsFailure(base, err);
157
+ if (explained)
158
+ throw new Error(explained, { cause: err });
159
+ throw err;
160
+ }
161
+ const parsed = parseJson(res.text);
162
+ const rpcError = readError(parsed);
163
+ if (rpcError)
164
+ throw new HubRpcError(rpcError.message, rpcError.code, path, res.status);
165
+ if (res.status < 200 || res.status >= 300) {
166
+ throw new HubHttpError(`${path}: HTTP ${res.status} ${res.text.slice(0, 200)}`, res.status, path);
167
+ }
168
+ if (parsed === null || typeof parsed !== 'object') {
169
+ throw new HubHttpError(`${path}: response is not a tRPC envelope`, res.status, path);
170
+ }
171
+ const result = Reflect.get(parsed, 'result');
172
+ const data = result !== null && typeof result === 'object' ? Reflect.get(result, 'data') : undefined;
173
+ if (data !== null && typeof data === 'object' && 'json' in data)
174
+ return Reflect.get(data, 'json');
175
+ return data;
176
+ }
127
177
  return {
128
178
  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
179
  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
- });
180
+ return await attempt(method, path, input);
152
181
  }
153
182
  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);
183
+ if (!isUnauthorized(err) || !options.onUnauthorized)
184
+ throw err;
185
+ const fresh = await options.onUnauthorized();
186
+ if (fresh === undefined || fresh === token)
187
+ throw err;
188
+ token = fresh;
189
+ return attempt(method, path, input);
168
190
  }
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
191
  },
175
192
  };
176
193
  }
@@ -0,0 +1,12 @@
1
+ /** The checkout-local invocation: build the CLI once, then run its entry. */
2
+ export declare const REPO_LOCAL_LOGIN = "npx nx run camstack:build && node packages/cli/dist/cli.js login";
3
+ /**
4
+ * The exact command that refreshes the CLI session: `camstack login` when the
5
+ * binary is on PATH, otherwise the checkout-local form.
6
+ */
7
+ export declare function sessionLoginCommand(env?: Readonly<Record<string, string | undefined>>): string;
8
+ /** The hub answered 401/403 to an admin-tier credential. */
9
+ export declare function adminRejectedHint(command?: string): string;
10
+ /** Why admin-tier ops are blocked locally. */
11
+ export declare function adminCredentialHint(command?: string): string;
12
+ //# sourceMappingURL=login-hints.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"login-hints.d.ts","sourceRoot":"","sources":["../../src/hub/login-hints.ts"],"names":[],"mappings":"AAuBA,6EAA6E;AAC7E,eAAO,MAAM,gBAAgB,qEAAqE,CAAA;AAElG;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GAC9D,MAAM,CAER;AAED,4DAA4D;AAC5D,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,MAA8B,GAAG,MAAM,CAEjF;AAED,8CAA8C;AAC9C,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,MAA8B,GAAG,MAAM,CAEnF"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The one sentence every hub tool gives when a credential is missing, refused
3
+ * or not strong enough: run `camstack login <host>` once; every tool then uses
4
+ * that session (refreshed automatically). There is no second credential file
5
+ * to look for.
6
+ */
7
+ import * as fs from 'node:fs';
8
+ import * as path from 'node:path';
9
+ /** Is `name` an executable file in one of the `PATH` directories? */
10
+ function onPath(name, pathEnv) {
11
+ if (!pathEnv)
12
+ return false;
13
+ return pathEnv.split(path.delimiter).some((d) => {
14
+ if (d === '')
15
+ return false;
16
+ try {
17
+ fs.accessSync(path.join(d, name), fs.constants.X_OK);
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ });
24
+ }
25
+ /** The checkout-local invocation: build the CLI once, then run its entry. */
26
+ export const REPO_LOCAL_LOGIN = 'npx nx run camstack:build && node packages/cli/dist/cli.js login';
27
+ /**
28
+ * The exact command that refreshes the CLI session: `camstack login` when the
29
+ * binary is on PATH, otherwise the checkout-local form.
30
+ */
31
+ export function sessionLoginCommand(env = process.env) {
32
+ return onPath('camstack', env['PATH']) ? 'camstack login' : REPO_LOCAL_LOGIN;
33
+ }
34
+ /** The hub answered 401/403 to an admin-tier credential. */
35
+ export function adminRejectedHint(command = sessionLoginCommand()) {
36
+ return `the hub rejected this credential (revoked or expired). Run \`${command}\` in a terminal with an admin account.`;
37
+ }
38
+ /** Why admin-tier ops are blocked locally. */
39
+ export function adminCredentialHint(command = sessionLoginCommand()) {
40
+ return `this credential is not admin-scoped. Run \`${command}\` with an admin account (the MCP never handles a password).`;
41
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The one way a tool gets a USABLE credential: `resolveCredentials` picks the
3
+ * token, this module makes sure it is still good.
4
+ *
5
+ * - A cached `camstack login` session whose access token has expired (or has
6
+ * < 60 s left) is renewed over HTTP with its refresh token
7
+ * (`auth.refreshSession`), the rotation is saved, and the caller carries on.
8
+ * A refusal (or nothing to renew with) is a {@link MissingCredentialsError}
9
+ * that says to run `camstack login`.
10
+ * - An explicit `--token` / `--token-file` / `$CAMSTACK_TOKEN` is never
11
+ * touched: it is what the operator handed over.
12
+ * - The permission tier is read from the token's CLAIMS; a token with no
13
+ * readable claims is classified by asking the hub (`whoami`), never by its
14
+ * prefix.
15
+ * - A 401 mid-flight refreshes once and retries once ({@link refreshOnUnauthorized}).
16
+ */
17
+ import { type CredentialInputs, type ResolvedCredentials } from './credentials.js';
18
+ import { type HubTransport } from './hub-client.js';
19
+ import { type HubTlsConfig } from './hub-tls.js';
20
+ /** Renew when the access token has less than this left. */
21
+ export declare const REFRESH_SKEW_MS = 60000;
22
+ export interface RefreshOptions {
23
+ readonly server: string;
24
+ /** The session cache directory; defaults to `~/.camstack`. */
25
+ readonly dir?: string;
26
+ readonly transport?: HubTransport;
27
+ readonly tls?: HubTlsConfig;
28
+ readonly now?: number;
29
+ }
30
+ export interface FreshCredentialInputs extends CredentialInputs {
31
+ readonly dir?: string;
32
+ readonly transport?: HubTransport;
33
+ readonly tls?: HubTlsConfig;
34
+ readonly now?: number;
35
+ }
36
+ /** Renew the saved session for `opts.server` now, whatever its expiry says; returns the new token. */
37
+ export declare function forceRefreshSession(opts: RefreshOptions): Promise<string>;
38
+ /** The `onUnauthorized` hook of {@link createHubClient}: a 401 renews the session, once. */
39
+ export declare function refreshOnUnauthorized(opts: RefreshOptions): () => Promise<string | undefined>;
40
+ /**
41
+ * `resolveCredentials`, then: renew an expiring cached session, and settle the
42
+ * tier from claims (or the hub, for a token that carries none).
43
+ */
44
+ export declare function resolveFreshCredentials(inputs: FreshCredentialInputs): Promise<ResolvedCredentials>;
45
+ //# sourceMappingURL=session-refresh.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-refresh.d.ts","sourceRoot":"","sources":["../../src/hub/session-refresh.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAML,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACzB,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAKL,KAAK,YAAY,EAClB,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAiB,KAAK,YAAY,EAAE,MAAM,cAAc,CAAA;AAG/D,2DAA2D;AAC3D,eAAO,MAAM,eAAe,QAAS,CAAA;AAIrC,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,8DAA8D;IAC9D,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,SAAS,CAAC,EAAE,YAAY,CAAA;IACjC,QAAQ,CAAC,GAAG,CAAC,EAAE,YAAY,CAAA;IAC3B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CACtB;AAED,MAAM,WAAW,qBAAsB,SAAQ,gBAAgB;IAC7D,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,SAAS,CAAC,EAAE,YAAY,CAAA;IACjC,QAAQ,CAAC,GAAG,CAAC,EAAE,YAAY,CAAA;IAC3B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CACtB;AA6DD,sGAAsG;AACtG,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CAK/E;AAED,4FAA4F;AAC5F,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAO7F;AAiCD;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,qBAAqB,GAC5B,OAAO,CAAC,mBAAmB,CAAC,CAyB9B"}
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The one way a tool gets a USABLE credential: `resolveCredentials` picks the
3
+ * token, this module makes sure it is still good.
4
+ *
5
+ * - A cached `camstack login` session whose access token has expired (or has
6
+ * < 60 s left) is renewed over HTTP with its refresh token
7
+ * (`auth.refreshSession`), the rotation is saved, and the caller carries on.
8
+ * A refusal (or nothing to renew with) is a {@link MissingCredentialsError}
9
+ * that says to run `camstack login`.
10
+ * - An explicit `--token` / `--token-file` / `$CAMSTACK_TOKEN` is never
11
+ * touched: it is what the operator handed over.
12
+ * - The permission tier is read from the token's CLAIMS; a token with no
13
+ * readable claims is classified by asking the hub (`whoami`), never by its
14
+ * prefix.
15
+ * - A 401 mid-flight refreshes once and retries once ({@link refreshOnUnauthorized}).
16
+ */
17
+ import { credentialTier, jwtClaims, jwtExpiryMs, MissingCredentialsError, resolveCredentials, } from './credentials.js';
18
+ import { createHubClient, HubHttpError, HubRpcError, nodeHubTransport, } from './hub-client.js';
19
+ import { resolveHubTls } from './hub-tls.js';
20
+ import { defaultSessionDir, loadSession, saveSession } from './session-store.js';
21
+ /** Renew when the access token has less than this left. */
22
+ export const REFRESH_SKEW_MS = 60_000;
23
+ const REFRESH_TIMEOUT_MS = 15_000;
24
+ const WHOAMI_TIMEOUT_MS = 5_000;
25
+ function readRefreshed(value) {
26
+ if (value === null || typeof value !== 'object')
27
+ return null;
28
+ const token = Reflect.get(value, 'token');
29
+ const refreshToken = Reflect.get(value, 'refreshToken');
30
+ const expiresAt = Reflect.get(value, 'expiresAt');
31
+ if (typeof token !== 'string' || typeof refreshToken !== 'string')
32
+ return null;
33
+ if (typeof expiresAt !== 'number')
34
+ return null;
35
+ return { token, refreshToken, expiresAt };
36
+ }
37
+ function tlsFor(opts, dir) {
38
+ return opts.tls ?? resolveHubTls(opts.server, process.env, dir);
39
+ }
40
+ /** Exchange the saved refresh token, persist the rotation, return the new session. */
41
+ async function renew(session, opts) {
42
+ const dir = opts.dir ?? defaultSessionDir();
43
+ const refreshToken = session.refreshToken;
44
+ if (refreshToken === undefined || refreshToken === '') {
45
+ throw new MissingCredentialsError(session.server, 'The session expired and has no refresh token');
46
+ }
47
+ const client = createHubClient({
48
+ baseUrl: session.server,
49
+ token: '',
50
+ tls: tlsFor(opts, dir),
51
+ timeoutMs: REFRESH_TIMEOUT_MS,
52
+ ...(opts.transport ? { transport: opts.transport } : {}),
53
+ });
54
+ let refreshed;
55
+ try {
56
+ refreshed = readRefreshed(await client.call('POST', 'auth.refreshSession', { refreshToken }));
57
+ }
58
+ catch (err) {
59
+ if (err instanceof HubRpcError || err instanceof HubHttpError) {
60
+ throw new MissingCredentialsError(session.server, 'The hub refused to refresh the session');
61
+ }
62
+ throw err;
63
+ }
64
+ if (!refreshed) {
65
+ throw new MissingCredentialsError(session.server, 'The hub refused to refresh the session');
66
+ }
67
+ const next = {
68
+ ...session,
69
+ token: refreshed.token,
70
+ refreshToken: refreshed.refreshToken,
71
+ expiresAt: refreshed.expiresAt,
72
+ };
73
+ saveSession(next, dir);
74
+ return next;
75
+ }
76
+ /** Renew the saved session for `opts.server` now, whatever its expiry says; returns the new token. */
77
+ export async function forceRefreshSession(opts) {
78
+ const dir = opts.dir ?? defaultSessionDir();
79
+ const session = loadSession(opts.server, dir);
80
+ if (!session)
81
+ throw new MissingCredentialsError(opts.server);
82
+ return (await renew(session, opts)).token;
83
+ }
84
+ /** The `onUnauthorized` hook of {@link createHubClient}: a 401 renews the session, once. */
85
+ export function refreshOnUnauthorized(opts) {
86
+ return async () => {
87
+ const dir = opts.dir ?? defaultSessionDir();
88
+ const session = loadSession(opts.server, dir);
89
+ if (!session?.refreshToken)
90
+ return undefined;
91
+ return forceRefreshSession(opts);
92
+ };
93
+ }
94
+ function needsRefresh(session, now) {
95
+ const expiresAt = session.expiresAt ?? jwtExpiryMs(session.token);
96
+ return expiresAt !== undefined && expiresAt - now < REFRESH_SKEW_MS;
97
+ }
98
+ /** Ask the hub who a token with no readable claims is. Any failure means "not admin". */
99
+ async function tierFromHub(server, token, opts) {
100
+ const transport = opts.transport ?? nodeHubTransport;
101
+ try {
102
+ const res = await transport({
103
+ url: `${server.replace(/\/+$/, '')}/api/auth/whoami`,
104
+ method: 'GET',
105
+ headers: { authorization: `Bearer ${token}` },
106
+ timeoutMs: WHOAMI_TIMEOUT_MS,
107
+ maxBytes: 64 * 1024,
108
+ tls: opts.tls ?? resolveHubTls(server, process.env, opts.dir ?? defaultSessionDir()),
109
+ });
110
+ if (res.status < 200 || res.status >= 300)
111
+ return 'protected';
112
+ const body = JSON.parse(res.text);
113
+ return body !== null && typeof body === 'object' && Reflect.get(body, 'isAdmin') === true
114
+ ? 'admin'
115
+ : 'protected';
116
+ }
117
+ catch {
118
+ return 'protected';
119
+ }
120
+ }
121
+ /**
122
+ * `resolveCredentials`, then: renew an expiring cached session, and settle the
123
+ * tier from claims (or the hub, for a token that carries none).
124
+ */
125
+ export async function resolveFreshCredentials(inputs) {
126
+ const now = inputs.now ?? Date.now();
127
+ let creds = resolveCredentials(inputs);
128
+ if (creds.source === 'session' && creds.server !== undefined) {
129
+ const dir = inputs.dir ?? defaultSessionDir();
130
+ const stored = loadSession(creds.server, dir);
131
+ if (stored !== null && stored.token === creds.token && needsRefresh(stored, now)) {
132
+ const next = await renew(stored, {
133
+ server: stored.server,
134
+ dir,
135
+ now,
136
+ ...(inputs.transport ? { transport: inputs.transport } : {}),
137
+ ...(inputs.tls ? { tls: inputs.tls } : {}),
138
+ });
139
+ creds = {
140
+ ...creds,
141
+ token: next.token,
142
+ tier: credentialTier(next.token, { sessionIsAdmin: next.isAdmin === true }),
143
+ };
144
+ }
145
+ }
146
+ if (creds.tier === 'protected' && jwtClaims(creds.token) === null && creds.server !== undefined) {
147
+ return { ...creds, tier: await tierFromHub(creds.server, creds.token, inputs) };
148
+ }
149
+ return creds;
150
+ }
@@ -12,24 +12,16 @@ export interface SessionFile {
12
12
  readonly isAdmin?: boolean;
13
13
  /** Last time a command used this session (`touchSession`); absent on older files. */
14
14
  readonly lastUsedAt?: number;
15
+ /** The `csr_...` token that renews `token` (`auth.refreshSession`); absent on older files. */
16
+ readonly refreshToken?: string;
17
+ /** When `token` expires (epoch ms); absent on older files (then the JWT `exp` is used). */
18
+ readonly expiresAt?: number;
15
19
  }
16
20
  /** Where the cache lives; injectable so a test never touches the real home. */
17
21
  export declare function defaultSessionDir(): string;
18
22
  /** Slug a server URL into a single filesystem-safe filename component. */
19
23
  export declare function slugForServer(serverUrl: string): string;
20
24
  export declare function sessionFileForServer(serverUrl: string, dir?: string): string;
21
- /**
22
- * Where an operator drops a `csa_` admin token for a hub (owner-only file,
23
- * D816). The extension is not `.json`, so the newest-session fallback below
24
- * never mistakes it for a session.
25
- */
26
- export declare function adminTokenFileForServer(serverUrl: string, dir?: string): string;
27
- /**
28
- * The admin token file to use, or `undefined` when none exists: the path named
29
- * by `$CAMSTACK_ADMIN_TOKEN_FILE` (a PATH, never the token), else the default
30
- * file for `serverUrl`.
31
- */
32
- export declare function findAdminTokenFile(serverUrl: string | undefined, env?: Readonly<Record<string, string | undefined>>, dir?: string): string | undefined;
33
25
  /** When a session was last used: `lastUsedAt`, else when it was created. */
34
26
  export declare function sessionRecency(session: SessionFile): number;
35
27
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"session-store.d.ts","sourceRoot":"","sources":["../../src/hub/session-store.ts"],"names":[],"mappings":"AAYA,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC5D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,wEAAwE;IACxE,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;IAC1B,qFAAqF;IACrF,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAC7B;AAED,+EAA+E;AAC/E,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C;AAED,0EAA0E;AAC1E,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAKvD;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,GAAE,MAA4B,GAAG,MAAM,CAEjG;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CACrC,SAAS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AAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAalE;AAED,wBAAgB,WAAW,CACzB,SAAS,CAAC,EAAE,MAAM,EAClB,GAAG,GAAE,MAA4B,GAChC,WAAW,GAAG,IAAI,CASpB;AAED,wBAAgB,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE,GAAG,GAAE,MAA4B,GAAG,MAAM,CAK3F;AAED,+EAA+E;AAC/E,wBAAgB,YAAY,CAC1B,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAA4B,EACjC,GAAG,GAAE,MAAmB,GACvB,IAAI,CAQN;AAED,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,GAAE,MAA4B,GAAG,OAAO,CAK1F"}
@@ -2,8 +2,8 @@
2
2
  * The `camstack login` session cache — `~/.camstack/<host>.json` (0600), one
3
3
  * file per hub. Moved here from the CLI so every hub-talking tool (CLI,
4
4
  * `scripts/hub/hub.mjs`, the operator MCP) reads the SAME cache through the
5
- * SAME code. The cache holds the login JWT from `camstack login` (or a legacy
6
- * `cst_` scoped token), never a password.
5
+ * SAME code. The cache holds the login JWT and its refresh token from `camstack login`,
6
+ * never a password.
7
7
  */
8
8
  import * as fs from 'node:fs';
9
9
  import * as os from 'node:os';
@@ -23,28 +23,6 @@ export function slugForServer(serverUrl) {
23
23
  export function sessionFileForServer(serverUrl, dir = defaultSessionDir()) {
24
24
  return path.join(dir, `${slugForServer(serverUrl)}.json`);
25
25
  }
26
- /**
27
- * Where an operator drops a `csa_` admin token for a hub (owner-only file,
28
- * D816). The extension is not `.json`, so the newest-session fallback below
29
- * never mistakes it for a session.
30
- */
31
- export function adminTokenFileForServer(serverUrl, dir = defaultSessionDir()) {
32
- return path.join(dir, `${slugForServer(serverUrl)}.admin-token`);
33
- }
34
- /**
35
- * The admin token file to use, or `undefined` when none exists: the path named
36
- * by `$CAMSTACK_ADMIN_TOKEN_FILE` (a PATH, never the token), else the default
37
- * file for `serverUrl`.
38
- */
39
- export function findAdminTokenFile(serverUrl, env = process.env, dir = defaultSessionDir()) {
40
- const named = env['CAMSTACK_ADMIN_TOKEN_FILE'];
41
- if (named && named.trim() !== '')
42
- return named;
43
- if (!serverUrl)
44
- return undefined;
45
- const candidate = adminTokenFileForServer(serverUrl, dir);
46
- return fs.existsSync(candidate) ? candidate : undefined;
47
- }
48
26
  /**
49
27
  * Resolve the right session file for the operator-supplied server URL.
50
28
  * With no server, fall back to the most recently touched session — an
@@ -138,6 +116,10 @@ export function isSessionFile(value) {
138
116
  return false;
139
117
  if (v.isAdmin !== undefined && typeof v.isAdmin !== 'boolean')
140
118
  return false;
119
+ if (v.refreshToken !== undefined && typeof v.refreshToken !== 'string')
120
+ return false;
121
+ if (v.expiresAt !== undefined && typeof v.expiresAt !== 'number')
122
+ return false;
141
123
  return true;
142
124
  }
143
125
  export function loadSession(serverUrl, dir = defaultSessionDir()) {
package/dist/index.d.ts CHANGED
@@ -12,12 +12,13 @@ export { scaffoldAddon } from './scaffold/addon.js';
12
12
  export { scaffoldCapStub } from './scaffold/cap-stub.js';
13
13
  export { extendAddon } from './scaffold/extend.js';
14
14
  export { listSkills, readSkill, resolveSkillsDir } from './skills.js';
15
- export { ADMIN_TOKEN_PREFIX, authRejectedHint, credentialTier, jwtPayloadIsAdmin, MissingCredentialsError, readTokenFile, resolveCredentials, withAuthHint, } from './hub/credentials.js';
15
+ export { authRejectedHint, credentialTier, jwtClaims, jwtExpiryMs, jwtPayloadIsAdmin, MissingCredentialsError, readTokenFile, resolveCredentials, withAuthHint, } from './hub/credentials.js';
16
16
  export type { CachedSessionLike, CredentialInputs, CredentialSource, CredentialTier, ResolvedCredentials, TokenFileContents, } from './hub/credentials.js';
17
- export { adminTokenFileForServer, clearSession, defaultSession, defaultSessionDir, findAdminTokenFile, isSessionFile, listSessions, loadSession, saveSession, sessionFileForServer, sessionRecency, slugForServer, touchSession, } from './hub/session-store.js';
17
+ export { clearSession, defaultSession, defaultSessionDir, isSessionFile, listSessions, loadSession, saveSession, sessionFileForServer, sessionRecency, slugForServer, touchSession, } from './hub/session-store.js';
18
18
  export type { SessionFile } from './hub/session-store.js';
19
- export { adminCredentialHint, adminLoginCommand, adminRejectedHint, adminTokenMetaFileForServer, adminTokenStatus, readPreviousAdminToken, REPO_LOCAL_LOGIN, REPO_LOCAL_LOGIN_ADMIN, saveAdminToken, sessionLoginCommand, } from './hub/admin-token-store.js';
20
- export type { AdminTokenMeta, AdminTokenStatus, PreviousAdminToken, } from './hub/admin-token-store.js';
19
+ export { adminCredentialHint, adminRejectedHint, REPO_LOCAL_LOGIN, sessionLoginCommand, } from './hub/login-hints.js';
20
+ export { forceRefreshSession, refreshOnUnauthorized, resolveFreshCredentials, } from './hub/session-refresh.js';
21
+ export type { FreshCredentialInputs, RefreshOptions, } from './hub/session-refresh.js';
21
22
  export { DEFAULT_HUB_PORT, HubAddressError, normalizeHubAddress, validateHubAddress, } from './hub/hub-address.js';
22
23
  export { resolveHubUrl } from './hub/hub-url.js';
23
24
  export type { HubUrlInputs, HubUrlSource, ResolvedHubUrl, } from './hub/hub-url.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAElE,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,GACf,MAAM,YAAY,CAAA;AAEnB,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EACL,WAAW,EACX,eAAe,EACf,WAAW,EACX,UAAU,GACX,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,G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nC,YAAY,EACV,cAAc,EACd,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,4BAA4B,CAAA;AACnC,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAChD,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,cAAc,GACf,MAAM,kBAAkB,CAAA;AACzB,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,GACd,MAAM,kBAAkB,CAAA;AACzB,YAAY,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EACL,eAAe,EACf,eAAe,EACf,YAAY,EACZ,WAAW,EACX,gBAAgB,GACjB,MAAM,qBAAqB,CAAA;AAC5B,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,qBAAqB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAElE,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,GACf,MAAM,YAAY,CAAA;AAEnB,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EACL,WAAW,EACX,eAAe,EACf,WAAW,EACX,UAAU,GACX,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,GACZ,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAA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OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAA;AAChD,YAAY,EACV,YAAY,EACZ,YAAY,EACZ,cAAc,GACf,MAAM,kBAAkB,CAAA;AACzB,OAAO,EACL,cAAc,EACd,iBAAiB,EACjB,kBAAkB,EAClB,aAAa,GACd,MAAM,kBAAkB,CAAA;AACzB,YAAY,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,EACL,eAAe,EACf,eAAe,EACf,YAAY,EACZ,WAAW,EACX,gBAAgB,GACjB,MAAM,qBAAqB,CAAA;AAC5B,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,qBAAqB,CAAA"}
package/dist/index.js CHANGED
@@ -13,9 +13,10 @@ export { extendAddon } from './scaffold/extend.js';
13
13
  export { listSkills, readSkill, resolveSkillsDir } from './skills.js';
14
14
  // Hub access — the one credential chain, session cache, address and TLS trust
15
15
  // shared by the CLI, scripts/hub/hub.mjs and the operator MCP (D835).
16
- export { ADMIN_TOKEN_PREFIX, authRejectedHint, credentialTier, jwtPayloadIsAdmin, MissingCredentialsError, readTokenFile, resolveCredentials, withAuthHint, } from './hub/credentials.js';
17
- export { adminTokenFileForServer, clearSession, defaultSession, defaultSessionDir, findAdminTokenFile, isSessionFile, listSessions, loadSession, saveSession, sessionFileForServer, sessionRecency, slugForServer, touchSession, } from './hub/session-store.js';
18
- export { adminCredentialHint, adminLoginCommand, adminRejectedHint, adminTokenMetaFileForServer, adminTokenStatus, readPreviousAdminToken, REPO_LOCAL_LOGIN, REPO_LOCAL_LOGIN_ADMIN, saveAdminToken, sessionLoginCommand, } from './hub/admin-token-store.js';
16
+ export { authRejectedHint, credentialTier, jwtClaims, jwtExpiryMs, jwtPayloadIsAdmin, MissingCredentialsError, readTokenFile, resolveCredentials, withAuthHint, } from './hub/credentials.js';
17
+ export { clearSession, defaultSession, defaultSessionDir, isSessionFile, listSessions, loadSession, saveSession, sessionFileForServer, sessionRecency, slugForServer, touchSession, } from './hub/session-store.js';
18
+ export { adminCredentialHint, adminRejectedHint, REPO_LOCAL_LOGIN, sessionLoginCommand, } from './hub/login-hints.js';
19
+ export { forceRefreshSession, refreshOnUnauthorized, resolveFreshCredentials, } from './hub/session-refresh.js';
19
20
  export { DEFAULT_HUB_PORT, HubAddressError, normalizeHubAddress, validateHubAddress, } from './hub/hub-address.js';
20
21
  export { resolveHubUrl } from './hub/hub-url.js';
21
22
  export { createHubAgent, explainTlsFailure, hubCaFileForServer, resolveHubTls, } from './hub/hub-tls.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/develop",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "CamStack developer tooling — catalogue, scaffold, validate, and example lookup shared by the CLI and MCP server.",
5
5
  "keywords": [
6
6
  "camstack",
@@ -1,57 +0,0 @@
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 = "npx nx run camstack:build && node packages/cli/dist/cli.js login";
44
- /** @deprecated Use {@link sessionLoginCommand}. */
45
- export declare const REPO_LOCAL_LOGIN_ADMIN = "npx nx run camstack:build && node packages/cli/dist/cli.js login";
46
- /**
47
- * The exact command that refreshes the CLI session: `camstack login` when the
48
- * binary is on PATH, otherwise the checkout-local form.
49
- */
50
- export declare function sessionLoginCommand(env?: Readonly<Record<string, string | undefined>>): string;
51
- /** @deprecated Use {@link sessionLoginCommand}. */
52
- export declare function adminLoginCommand(env?: Readonly<Record<string, string | undefined>>): string;
53
- /** The hub answered 401/403 to an admin-tier credential. */
54
- export declare function adminRejectedHint(command?: string): string;
55
- /** Why admin-tier ops are blocked locally; `null` when the credential is already admin. */
56
- export declare function adminCredentialHint(_status: AdminTokenStatus, command?: string): string | null;
57
- //# sourceMappingURL=admin-token-store.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"admin-token-store.d.ts","sourceRoot":"","sources":["../../src/hub/admin-token-store.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,SA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E,MAAmB,GACvB,gBAAgB,CAQlB;AAgBD,6EAA6E;AAC7E,eAAO,MAAM,gBAAgB,qEACuC,CAAA;AAEpE,mDAAmD;AACnD,eAAO,MAAM,sBAAsB,qEAAmB,CAAA;AAEtD;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GAC9D,MAAM,CAER;AAED,mDAAmD;AACnD,wBAAgB,iBAAiB,CAC/B,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GAC9D,MAAM,CAER;AAED,4DAA4D;AAC5D,wBAAgB,iBAAiB,CAAC,OAAO,GAAE,MAA8B,GAAG,MAAM,CAEjF;AAED,2FAA2F;AAC3F,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,gBAAgB,EACzB,OAAO,GAAE,MAA8B,GACtC,MAAM,GAAG,IAAI,CAEf"}
@@ -1,139 +0,0 @@
1
- /**
2
- * Legacy `csa_` admin token files (D816): still discoverable for hub URL hints,
3
- * but no longer auto-loaded by the credential chain — use `camstack login`.
4
- *
5
- * Two files, both 0600, beside the session cache:
6
- * - `<host>.admin-token` the bare `csa_` token (what the chain reads)
7
- * - `<host>.admin-token.meta` `{ tokenId, createdAt, expiresAt }` — NO secret.
8
- * Present only so `whoami` and the operator MCP can say "expired" without
9
- * calling the hub. The chain never needs it: a missing or unreadable meta
10
- * file only means "expiry unknown".
11
- *
12
- * Neither extension is `.json`, so the newest-session fallback never mistakes
13
- * them for a session.
14
- */
15
- import * as fs from 'node:fs';
16
- import * as path from 'node:path';
17
- import { adminTokenFileForServer, defaultSessionDir, findAdminTokenFile } from './session-store.js';
18
- export function adminTokenMetaFileForServer(serverUrl, dir = defaultSessionDir()) {
19
- return `${adminTokenFileForServer(serverUrl, dir)}.meta`;
20
- }
21
- /**
22
- * Write `content` to `file` with mode 0600, atomically: a sibling temp file is
23
- * created exclusively (`wx`, 0600), then renamed over the target. A crash leaves
24
- * the old file or the new one, never a half-written token.
25
- */
26
- function writeFileAtomic0600(file, content) {
27
- const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
28
- try {
29
- fs.writeFileSync(tmp, content, { mode: 0o600, flag: 'wx' });
30
- fs.chmodSync(tmp, 0o600);
31
- fs.renameSync(tmp, file);
32
- }
33
- catch (err) {
34
- fs.rmSync(tmp, { force: true });
35
- throw err;
36
- }
37
- }
38
- /** Persist an admin token for `serverUrl`; returns the token file path. */
39
- export function saveAdminToken(serverUrl, token, meta, dir = defaultSessionDir()) {
40
- if (!fs.existsSync(dir))
41
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
42
- const file = adminTokenFileForServer(serverUrl, dir);
43
- writeFileAtomic0600(file, `${token}\n`);
44
- writeFileAtomic0600(adminTokenMetaFileForServer(serverUrl, dir), JSON.stringify(meta, null, 2));
45
- return file;
46
- }
47
- function readMeta(file) {
48
- try {
49
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
50
- if (parsed === null || typeof parsed !== 'object')
51
- return null;
52
- const tokenId = Reflect.get(parsed, 'tokenId');
53
- const createdAt = Reflect.get(parsed, 'createdAt');
54
- const expiresAt = Reflect.get(parsed, 'expiresAt');
55
- if (typeof tokenId !== 'string' || typeof createdAt !== 'number')
56
- return null;
57
- if (typeof expiresAt !== 'number')
58
- return null;
59
- return { tokenId, createdAt, expiresAt };
60
- }
61
- catch {
62
- return null;
63
- }
64
- }
65
- /** Read the admin token currently stored for `serverUrl`, at the path `saveAdminToken` writes. */
66
- export function readPreviousAdminToken(serverUrl, dir = defaultSessionDir()) {
67
- if (!fs.existsSync(adminTokenFileForServer(serverUrl, dir)))
68
- return { kind: 'none' };
69
- let parsed;
70
- try {
71
- parsed = JSON.parse(fs.readFileSync(adminTokenMetaFileForServer(serverUrl, dir), 'utf8'));
72
- }
73
- catch {
74
- return { kind: 'unidentified' };
75
- }
76
- if (parsed === null || typeof parsed !== 'object')
77
- return { kind: 'unidentified' };
78
- const tokenId = Reflect.get(parsed, 'tokenId');
79
- const expiresAt = Reflect.get(parsed, 'expiresAt');
80
- const expiry = typeof expiresAt === 'number' ? { expiresAt } : {};
81
- return typeof tokenId === 'string' && tokenId !== ''
82
- ? { kind: 'identified', tokenId, ...expiry }
83
- : { kind: 'unidentified', ...expiry };
84
- }
85
- /**
86
- * Whether an admin credential exists for `serverUrl`, and whether it is known
87
- * to be expired. Honours `$CAMSTACK_ADMIN_TOKEN_FILE` like the chain does; the
88
- * meta file is looked up beside whichever token file the chain would read.
89
- */
90
- export function adminTokenStatus(serverUrl, env = process.env, dir = defaultSessionDir(), now = Date.now()) {
91
- const file = findAdminTokenFile(serverUrl, env, dir);
92
- if (!file || !fs.existsSync(file))
93
- return { state: 'missing' };
94
- const meta = readMeta(`${file}.meta`);
95
- if (!meta)
96
- return { state: 'present' };
97
- return meta.expiresAt <= now
98
- ? { state: 'expired', expiresAt: meta.expiresAt }
99
- : { state: 'present', expiresAt: meta.expiresAt };
100
- }
101
- /** Is `name` an executable file in one of the `PATH` directories? */
102
- function onPath(name, pathEnv) {
103
- if (!pathEnv)
104
- return false;
105
- return pathEnv.split(path.delimiter).some((d) => {
106
- if (d === '')
107
- return false;
108
- try {
109
- fs.accessSync(path.join(d, name), fs.constants.X_OK);
110
- return true;
111
- }
112
- catch {
113
- return false;
114
- }
115
- });
116
- }
117
- /** The checkout-local invocation: build the CLI once, then run its entry. */
118
- export const REPO_LOCAL_LOGIN = 'npx nx run camstack:build && node packages/cli/dist/cli.js login';
119
- /** @deprecated Use {@link sessionLoginCommand}. */
120
- export const REPO_LOCAL_LOGIN_ADMIN = REPO_LOCAL_LOGIN;
121
- /**
122
- * The exact command that refreshes the CLI session: `camstack login` when the
123
- * binary is on PATH, otherwise the checkout-local form.
124
- */
125
- export function sessionLoginCommand(env = process.env) {
126
- return onPath('camstack', env['PATH']) ? 'camstack login' : REPO_LOCAL_LOGIN;
127
- }
128
- /** @deprecated Use {@link sessionLoginCommand}. */
129
- export function adminLoginCommand(env = process.env) {
130
- return sessionLoginCommand(env);
131
- }
132
- /** The hub answered 401/403 to an admin-tier credential. */
133
- export function adminRejectedHint(command = sessionLoginCommand()) {
134
- return `the hub rejected this credential (revoked or expired). Run \`${command}\` in a terminal with an admin account.`;
135
- }
136
- /** Why admin-tier ops are blocked locally; `null` when the credential is already admin. */
137
- export function adminCredentialHint(_status, command = sessionLoginCommand()) {
138
- return `this credential is not admin-scoped. Run \`${command}\` with an admin account (the MCP never handles a password).`;
139
- }