@agent-watch-ai/edge 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/README.md +4 -1
- package/dist/billing/session-billing.d.ts +5 -2
- package/dist/billing/session-billing.js +27 -6
- package/dist/capture/capture-env.d.ts +3 -3
- package/dist/capture/capture-env.js +5 -5
- package/dist/capture/captured-step.js +24 -0
- package/dist/capture/constants/capture.constants.d.ts +15 -0
- package/dist/capture/constants/capture.constants.js +15 -0
- package/dist/capture/launched-runs.d.ts +27 -0
- package/dist/capture/launched-runs.js +15 -9
- package/dist/capture/python/sitecustomize.py +11 -2
- package/dist/capture/venv-loader.d.ts +68 -0
- package/dist/capture/venv-loader.js +189 -0
- package/dist/cli/constants/cli.constants.d.ts +21 -0
- package/dist/cli/constants/cli.constants.js +22 -1
- package/dist/cli/doctor-run-capture.d.ts +8 -0
- package/dist/cli/doctor-run-capture.js +14 -0
- package/dist/cli/doctor.js +6 -2
- package/dist/cli/hook-check.d.ts +7 -2
- package/dist/cli/hook-check.js +30 -15
- package/dist/cli/hook.js +44 -3
- package/dist/cli/npm-global.d.ts +24 -0
- package/dist/cli/npm-global.js +77 -0
- package/dist/cli/npx-install.js +22 -6
- package/dist/cli/replay.js +42 -7
- package/dist/cli/setup.js +71 -7
- package/dist/cli/types/cli.types.d.ts +2 -0
- package/dist/cli/uninstall.js +34 -1
- package/dist/cli/update.js +3 -2
- package/dist/cli.js +4 -1
- package/dist/config/config-store.d.ts +15 -4
- package/dist/config/config-store.js +31 -7
- package/dist/config/config.d.ts +8 -0
- package/dist/config/config.js +10 -0
- package/dist/config/constants/config.constants.d.ts +13 -1
- package/dist/config/constants/config.constants.js +13 -1
- package/dist/config/repo-config.js +7 -2
- package/dist/config/schemas/config.schema.d.ts +6 -2
- package/dist/config/schemas/config.schema.js +17 -3
- package/dist/credentials/cloud-claim.d.ts +2 -0
- package/dist/credentials/cloud-claim.js +21 -2
- package/dist/credentials/constants/credentials.constants.d.ts +8 -0
- package/dist/credentials/constants/credentials.constants.js +8 -0
- package/dist/credentials/credential-status.js +1 -1
- package/dist/credentials/credentials.d.ts +3 -3
- package/dist/credentials/credentials.js +26 -12
- package/dist/credentials/identity.d.ts +2 -2
- package/dist/credentials/identity.js +2 -2
- package/dist/credentials/install-key.d.ts +31 -0
- package/dist/credentials/install-key.js +58 -0
- package/dist/credentials/migration.d.ts +9 -7
- package/dist/credentials/migration.js +58 -18
- package/dist/credentials/secret-store.d.ts +12 -0
- package/dist/credentials/secret-store.js +18 -1
- package/dist/enforcement/enforcement.js +1 -1
- package/dist/events/enrich.d.ts +14 -0
- package/dist/events/enrich.js +1 -1
- package/dist/git/constants/git.constants.d.ts +2 -0
- package/dist/git/constants/git.constants.js +9 -0
- package/dist/git/repo-snapshot.js +8 -2
- package/dist/git/types/snapshot.types.d.ts +4 -0
- package/dist/pipeline/hook-pipeline.js +5 -2
- package/dist/providers/antigravity/antigravity.adapter.d.ts +14 -0
- package/dist/providers/antigravity/antigravity.adapter.js +86 -18
- package/dist/providers/antigravity/antigravity.provider.js +7 -4
- package/dist/providers/antigravity/constants/antigravity.constants.d.ts +10 -0
- package/dist/providers/antigravity/constants/antigravity.constants.js +10 -0
- package/dist/providers/antigravity/schemas/antigravity.schema.js +7 -13
- package/dist/providers/claude/claude.otel.d.ts +33 -1
- package/dist/providers/claude/claude.otel.js +81 -12
- package/dist/providers/claude/claude.provider.js +12 -6
- package/dist/providers/codex/codex.capture.d.ts +1 -1
- package/dist/providers/codex/codex.capture.js +3 -3
- package/dist/providers/codex/codex.otel.js +2 -2
- package/dist/providers/codex/codex.provider.js +2 -1
- package/dist/providers/gemini/gemini.capture.js +2 -2
- package/dist/providers/gemini/gemini.otel.js +2 -2
- package/dist/providers/gemini/gemini.provider.js +2 -1
- package/dist/providers/shared/terminal-capture.js +3 -3
- package/dist/providers/types/provider.types.d.ts +5 -5
- package/dist/replay/checkout-resolver.d.ts +41 -14
- package/dist/replay/checkout-resolver.js +134 -30
- package/dist/replay/replay-runner.d.ts +3 -1
- package/dist/replay/replay-runner.js +74 -22
- package/dist/replay/replay-scan.d.ts +2 -1
- package/dist/replay/replay-scan.js +14 -2
- package/dist/replay/throttle.d.ts +2 -1
- package/dist/replay/throttle.js +4 -1
- package/dist/replay/transcript-turns.js +29 -3
- package/dist/replay/turn-event.d.ts +4 -2
- package/dist/replay/turn-event.js +22 -11
- package/dist/replay/types/replay.types.d.ts +39 -3
- package/dist/replay/worktree-map.d.ts +42 -0
- package/dist/replay/worktree-map.js +134 -0
- package/dist/snapshot/snapshot-pipeline.js +15 -4
- package/dist/snapshot/types/snapshot.types.d.ts +2 -0
- package/dist/turns/antigravity-transcript.d.ts +40 -0
- package/dist/turns/antigravity-transcript.js +102 -0
- package/dist/turns/claude-transcript.d.ts +35 -1
- package/dist/turns/claude-transcript.js +185 -2
- package/dist/turns/codex-transcript.d.ts +22 -1
- package/dist/turns/codex-transcript.js +161 -2
- package/dist/turns/constants/turns.constants.d.ts +67 -0
- package/dist/turns/constants/turns.constants.js +67 -0
- package/dist/turns/gemini-transcript.d.ts +17 -1
- package/dist/turns/gemini-transcript.js +36 -2
- package/dist/turns/transcript.d.ts +31 -1
- package/dist/turns/transcript.js +74 -0
- package/dist/turns/turn-state.d.ts +51 -1
- package/dist/turns/turn-state.js +124 -10
- package/dist/turns/turn-tracker.js +156 -18
- package/dist/turns/types/transcript.types.d.ts +25 -0
- package/dist/turns/types/turn-provider.types.d.ts +18 -1
- package/dist/turns/types/turn-state.types.d.ts +10 -0
- package/docs/DATA_HANDLING.md +11 -6
- package/docs/ENTERPRISE_DEPLOYMENT.md +2 -2
- package/package.json +1 -1
|
@@ -5,7 +5,7 @@ import { debugLog } from '../core/logger.js';
|
|
|
5
5
|
import { readJsonFile } from '../storage/json-file.js';
|
|
6
6
|
import { loadConfig } from './config-store.js';
|
|
7
7
|
import { applyRootOverride } from './root-config.js';
|
|
8
|
-
import { CAPTURE_KEY, GLOBAL_ONLY_BLOCKS, GLOBAL_ONLY_EMIT_KEYS, GLOBAL_ONLY_KEYS, MAX_WALK_DEPTH, MERGE_BLOCKS, REPO_CONFIG_NAME } from './constants/config.constants.js';
|
|
8
|
+
import { CAPTURE_KEY, GLOBAL_ONLY_BLOCKS, GLOBAL_ONLY_CAPTURE_KEYS, GLOBAL_ONLY_EMIT_KEYS, GLOBAL_ONLY_KEYS, MAX_WALK_DEPTH, MERGE_BLOCKS, REPO_CONFIG_NAME } from './constants/config.constants.js';
|
|
9
9
|
import { configSchema } from './schemas/config.schema.js';
|
|
10
10
|
export { REPO_CONFIG_NAME } from './constants/config.constants.js';
|
|
11
11
|
/**
|
|
@@ -125,7 +125,12 @@ function withoutGlobalOnly(repo) {
|
|
|
125
125
|
warnings.push(`${REPO_CONFIG_NAME}: "${block}" is global-only and was ignored`);
|
|
126
126
|
refused.add(block);
|
|
127
127
|
}
|
|
128
|
-
const
|
|
128
|
+
const stripped = omitKeys(repo, refused);
|
|
129
|
+
const capture = asRecord(stripped[CAPTURE_KEY]);
|
|
130
|
+
const refusedCaptureKeys = new Set(Object.keys(capture ?? {}).filter((key) => GLOBAL_ONLY_CAPTURE_KEYS.has(key)));
|
|
131
|
+
for (const key of refusedCaptureKeys)
|
|
132
|
+
warnings.push(`${REPO_CONFIG_NAME}: "capture.${key}" is global-only and was ignored`);
|
|
133
|
+
const value = capture && refusedCaptureKeys.size > 0 ? { ...stripped, [CAPTURE_KEY]: omitKeys(capture, refusedCaptureKeys) } : stripped;
|
|
129
134
|
const emit = asRecord(value['emit']);
|
|
130
135
|
if (!emit)
|
|
131
136
|
return { value, warnings };
|
|
@@ -33,6 +33,7 @@ export declare const captureSchema: z.ZodObject<{
|
|
|
33
33
|
git: z.ZodDefault<z.ZodBoolean>;
|
|
34
34
|
files: z.ZodDefault<z.ZodBoolean>;
|
|
35
35
|
mcpNames: z.ZodDefault<z.ZodBoolean>;
|
|
36
|
+
runs: z.ZodDefault<z.ZodBoolean>;
|
|
36
37
|
}, z.core.$strip>;
|
|
37
38
|
/** Tuning for the in-hook send and the machine-global offline queue. */
|
|
38
39
|
export declare const deliverySchema: z.ZodObject<{
|
|
@@ -64,7 +65,7 @@ export declare const otelSchema: z.ZodObject<{
|
|
|
64
65
|
*/
|
|
65
66
|
export declare const enforcementSchema: z.ZodObject<{
|
|
66
67
|
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
67
|
-
timeoutMs: z.ZodDefault<z.ZodNumber
|
|
68
|
+
timeoutMs: z.ZodPipe<z.ZodDefault<z.ZodNumber>, z.ZodTransform<number, number>>;
|
|
68
69
|
cacheTtlMs: z.ZodDefault<z.ZodNumber>;
|
|
69
70
|
}, z.core.$strip>;
|
|
70
71
|
/** Which records the edge itself emits. */
|
|
@@ -239,6 +240,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
|
|
|
239
240
|
git: z.ZodDefault<z.ZodBoolean>;
|
|
240
241
|
files: z.ZodDefault<z.ZodBoolean>;
|
|
241
242
|
mcpNames: z.ZodDefault<z.ZodBoolean>;
|
|
243
|
+
runs: z.ZodDefault<z.ZodBoolean>;
|
|
242
244
|
}, z.core.$strip>>;
|
|
243
245
|
emit: z.ZodPrefault<z.ZodObject<{
|
|
244
246
|
turnSummaries: z.ZodDefault<z.ZodBoolean>;
|
|
@@ -258,7 +260,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
|
|
|
258
260
|
}, z.core.$strip>>;
|
|
259
261
|
enforcement: z.ZodPrefault<z.ZodObject<{
|
|
260
262
|
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
261
|
-
timeoutMs: z.ZodDefault<z.ZodNumber
|
|
263
|
+
timeoutMs: z.ZodPipe<z.ZodDefault<z.ZodNumber>, z.ZodTransform<number, number>>;
|
|
262
264
|
cacheTtlMs: z.ZodDefault<z.ZodNumber>;
|
|
263
265
|
}, z.core.$strip>>;
|
|
264
266
|
}, z.core.$loose>, z.ZodTransform<{
|
|
@@ -270,6 +272,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
|
|
|
270
272
|
git: boolean;
|
|
271
273
|
files: boolean;
|
|
272
274
|
mcpNames: boolean;
|
|
275
|
+
runs: boolean;
|
|
273
276
|
};
|
|
274
277
|
schemaVersion: 1;
|
|
275
278
|
ignoredRoots: string[];
|
|
@@ -347,6 +350,7 @@ export declare const configSchema: z.ZodPipe<z.ZodObject<{
|
|
|
347
350
|
git: boolean;
|
|
348
351
|
files: boolean;
|
|
349
352
|
mcpNames: boolean;
|
|
353
|
+
runs: boolean;
|
|
350
354
|
};
|
|
351
355
|
emit: {
|
|
352
356
|
turnSummaries: boolean;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { asRecord } from '../../core/object.js';
|
|
3
3
|
import { CREDENTIAL_STORE_KINDS, DEVICE_SOURCE_BATCH_CODE, RE_DEVICE_ID } from '../../credentials/constants/credentials.constants.js';
|
|
4
|
-
import { AGENT_WATCH_HOSTS, CUSTOM_ENDPOINT_MESSAGE, CUSTOM_ENDPOINTS_KEY, DELIVERABLE_URL_MESSAGE, DEVICE_URL_FIELDS, ROOTS_KEY, ROOT_URL_FIELDS, URL_FIELDS, LOOPBACK_HOSTS, DEFAULT_DRAIN_BATCH_SIZE, DEFAULT_ENFORCEMENT_CACHE_TTL_MS, DEFAULT_ENFORCEMENT_TIMEOUT_MS, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_EVENT_AGE_DAYS, DEFAULT_MAX_QUEUE_EVENTS, DEFAULT_SEND_TIMEOUT_MS } from '../constants/config.constants.js';
|
|
4
|
+
import { AGENT_WATCH_HOSTS, CUSTOM_ENDPOINT_MESSAGE, CUSTOM_ENDPOINTS_KEY, DELIVERABLE_URL_MESSAGE, DEVICE_URL_FIELDS, ROOTS_KEY, ROOT_URL_FIELDS, URL_FIELDS, LOOPBACK_HOSTS, DEFAULT_DRAIN_BATCH_SIZE, DEFAULT_ENFORCEMENT_CACHE_TTL_MS, DEFAULT_ENFORCEMENT_TIMEOUT_MS, LEGACY_ENFORCEMENT_TIMEOUT_MS, DEFAULT_MAX_ATTEMPTS, DEFAULT_MAX_EVENT_AGE_DAYS, DEFAULT_MAX_QUEUE_EVENTS, DEFAULT_SEND_TIMEOUT_MS } from '../constants/config.constants.js';
|
|
5
5
|
/**
|
|
6
6
|
* The content flags, off.
|
|
7
7
|
*
|
|
@@ -52,7 +52,13 @@ export const captureSchema = z
|
|
|
52
52
|
git: z.boolean().default(true),
|
|
53
53
|
files: z.boolean().default(true),
|
|
54
54
|
/** MCP server and tool names in `tools_used`; false folds them into `mcp`. Metadata, not content. */
|
|
55
|
-
mcpNames: z.boolean().default(true)
|
|
55
|
+
mcpNames: z.boolean().default(true),
|
|
56
|
+
/**
|
|
57
|
+
* Run capture: the shims each agent's environment loads, counting provider calls of the
|
|
58
|
+
* processes it starts. Its own switch, apart from `otel`: the calls travel as events,
|
|
59
|
+
* not OTLP, so turning native telemetry off must not stop them. Machine-wide, global-only.
|
|
60
|
+
*/
|
|
61
|
+
runs: z.boolean().default(true)
|
|
56
62
|
})
|
|
57
63
|
.strip();
|
|
58
64
|
/** Tuning for the in-hook send and the machine-global offline queue. */
|
|
@@ -93,7 +99,15 @@ export const enforcementSchema = z
|
|
|
93
99
|
.object({
|
|
94
100
|
enabled: z.boolean().default(true),
|
|
95
101
|
/** Hard ceiling for the check; it sits between enter and the agent's first call. */
|
|
96
|
-
|
|
102
|
+
// ponytail: a stored 300 is read as the old default and lifted. A developer who
|
|
103
|
+
// chose exactly 300 by hand gets 500 too; a config migration step would tell
|
|
104
|
+
// them apart if that ever matters.
|
|
105
|
+
timeoutMs: z
|
|
106
|
+
.number()
|
|
107
|
+
.int()
|
|
108
|
+
.positive()
|
|
109
|
+
.default(DEFAULT_ENFORCEMENT_TIMEOUT_MS)
|
|
110
|
+
.transform((ms) => (ms === LEGACY_ENFORCEMENT_TIMEOUT_MS ? DEFAULT_ENFORCEMENT_TIMEOUT_MS : ms)),
|
|
97
111
|
/** Mirrors the platform's own cache TTL for the same decision. */
|
|
98
112
|
cacheTtlMs: z.number().int().positive().default(DEFAULT_ENFORCEMENT_CACHE_TTL_MS)
|
|
99
113
|
})
|
|
@@ -6,6 +6,8 @@ export interface CloudIdentity {
|
|
|
6
6
|
readonly key: string;
|
|
7
7
|
/** The signed-in Claude account's email; never git's (in a cloud VM that is `noreply@anthropic.com`). */
|
|
8
8
|
readonly email: string;
|
|
9
|
+
/** The gateway the block exports usage to (the origin of its `<gateway>/v1/otlp` endpoint), when it names one. */
|
|
10
|
+
readonly gateway?: string;
|
|
9
11
|
}
|
|
10
12
|
/**
|
|
11
13
|
* What the managed settings and the Claude account give this VM to claim with,
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { createPrivateKey, randomBytes, sign } from 'node:crypto';
|
|
2
2
|
import { claudeAccountEmail } from '../billing/billing-mode.js';
|
|
3
|
-
import {
|
|
3
|
+
import { OTLP_BASE_PATH, RE_TRAILING_SLASHES } from '../config/constants/config.constants.js';
|
|
4
|
+
import { compact } from '../core/object.js';
|
|
5
|
+
import { AGENTWATCH_CLOUD_KEY, AGENTWATCH_CLOUD_ORGANIZATION, OTEL_ENDPOINT_VAR } from './constants/credentials.constants.js';
|
|
4
6
|
/**
|
|
5
7
|
* What the managed settings and the Claude account give this VM to claim with,
|
|
6
8
|
* or the one line that says why it cannot.
|
|
@@ -16,7 +18,24 @@ export async function cloudIdentity(env) {
|
|
|
16
18
|
const email = await claudeAccountEmail(env.home).catch(() => undefined);
|
|
17
19
|
if (!email)
|
|
18
20
|
return { skip: 'no Claude account email in ~/.claude.json; Agent Watch not installed' };
|
|
19
|
-
return { organizationId, key, email };
|
|
21
|
+
return compact({ organizationId, key, email, gateway: blockGateway(env.vars[OTEL_ENDPOINT_VAR]) });
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The gateway a managed block exports usage to: Settings renders its OTLP
|
|
25
|
+
* endpoint as `<gateway>/v1/otlp`, a gateway under a path prefix included.
|
|
26
|
+
* Anything else (a developer's own collector) names no Agent Watch backend.
|
|
27
|
+
*
|
|
28
|
+
* @param endpoint - The block's `OTEL_EXPORTER_OTLP_ENDPOINT`.
|
|
29
|
+
* @returns The gateway, or undefined.
|
|
30
|
+
*/
|
|
31
|
+
function blockGateway(endpoint) {
|
|
32
|
+
if (endpoint === undefined || !URL.canParse(endpoint))
|
|
33
|
+
return undefined;
|
|
34
|
+
const url = new URL(endpoint);
|
|
35
|
+
const pathname = url.pathname.replace(RE_TRAILING_SLASHES, '');
|
|
36
|
+
if (!pathname.endsWith(OTLP_BASE_PATH) || url.search || url.hash)
|
|
37
|
+
return undefined;
|
|
38
|
+
return `${url.origin}${pathname.slice(0, -OTLP_BASE_PATH.length)}`;
|
|
20
39
|
}
|
|
21
40
|
/**
|
|
22
41
|
* The claim text and its Ed25519 signature over the text's exact UTF-8 bytes
|
|
@@ -62,6 +62,8 @@ export declare const CLAUDE_CODE_REMOTE_VAR = "CLAUDE_CODE_REMOTE";
|
|
|
62
62
|
/** The managed-settings env names Settings renders (core `AGENTWATCH_CLOUD_ORGANIZATION`, `AGENTWATCH_CLOUD_KEY`): the organization's id and its base64url PKCS8 DER Ed25519 private key. */
|
|
63
63
|
export declare const AGENTWATCH_CLOUD_ORGANIZATION = "AGENTWATCH_CLOUD_ORGANIZATION";
|
|
64
64
|
export declare const AGENTWATCH_CLOUD_KEY = "AGENTWATCH_CLOUD_KEY";
|
|
65
|
+
/** The OTLP endpoint the managed block sets, `<gateway>/v1/otlp`: the block's only word on its backend. */
|
|
66
|
+
export declare const OTEL_ENDPOINT_VAR = "OTEL_EXPORTER_OTLP_ENDPOINT";
|
|
65
67
|
/** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
|
|
66
68
|
export declare const DEVICE_SOURCE_BATCH_CODE = "batch-code";
|
|
67
69
|
/** The RFC 8628 answers of a poll that are not failures: keep waiting. */
|
|
@@ -124,3 +126,9 @@ export declare const ENROLL_RETRY_MS = 3600000;
|
|
|
124
126
|
export declare const RE_PLAIN_EMAIL: RegExp;
|
|
125
127
|
/** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
|
|
126
128
|
export declare const NOT_SIGNED_IN = "AgentWatch is set up for your organization but not signed in: run `agentwatch setup` to sign in. Nothing is recorded until then";
|
|
129
|
+
/**
|
|
130
|
+
* Appended to a device id to name the account (or file) its install key is
|
|
131
|
+
* kept under, in the same store as the device secret: the key enrolls the
|
|
132
|
+
* device again when the secret expires, and is never left in the config.
|
|
133
|
+
*/
|
|
134
|
+
export declare const INSTALL_KEY_ACCOUNT_SUFFIX = ".install-key";
|
|
@@ -63,6 +63,8 @@ export const CLAUDE_CODE_REMOTE_VAR = 'CLAUDE_CODE_REMOTE';
|
|
|
63
63
|
/** The managed-settings env names Settings renders (core `AGENTWATCH_CLOUD_ORGANIZATION`, `AGENTWATCH_CLOUD_KEY`): the organization's id and its base64url PKCS8 DER Ed25519 private key. */
|
|
64
64
|
export const AGENTWATCH_CLOUD_ORGANIZATION = 'AGENTWATCH_CLOUD_ORGANIZATION';
|
|
65
65
|
export const AGENTWATCH_CLOUD_KEY = 'AGENTWATCH_CLOUD_KEY';
|
|
66
|
+
/** The OTLP endpoint the managed block sets, `<gateway>/v1/otlp`: the block's only word on its backend. */
|
|
67
|
+
export const OTEL_ENDPOINT_VAR = 'OTEL_EXPORTER_OTLP_ENDPOINT';
|
|
66
68
|
/** Recorded on a device enrolled with an admin-issued code, so `status` can say so (core `DeviceCredentialSource.BatchCode`). */
|
|
67
69
|
export const DEVICE_SOURCE_BATCH_CODE = 'batch-code';
|
|
68
70
|
/** The RFC 8628 answers of a poll that are not failures: keep waiting. */
|
|
@@ -125,3 +127,9 @@ export const ENROLL_RETRY_MS = 3_600_000;
|
|
|
125
127
|
export const RE_PLAIN_EMAIL = /^[^\s@\p{Cc}\p{Cf}]{1,64}@[^\s@\p{Cc}\p{Cf}]{1,189}$/u;
|
|
126
128
|
/** What an MDM install that has not signed in yet tells its developer, wherever it speaks. */
|
|
127
129
|
export const NOT_SIGNED_IN = 'AgentWatch is set up for your organization but not signed in: run `agentwatch setup` to sign in. Nothing is recorded until then';
|
|
130
|
+
/**
|
|
131
|
+
* Appended to a device id to name the account (or file) its install key is
|
|
132
|
+
* kept under, in the same store as the device secret: the key enrolls the
|
|
133
|
+
* device again when the secret expires, and is never left in the config.
|
|
134
|
+
*/
|
|
135
|
+
export const INSTALL_KEY_ACCOUNT_SUFFIX = '.install-key';
|
|
@@ -27,7 +27,7 @@ export async function describeCredential(paths, config, scope) {
|
|
|
27
27
|
return { level: 'warn', detail: 'none configured' };
|
|
28
28
|
const { refusal } = await readDeviceState(identityPaths(paths, identityOf(config)).deviceStateFile);
|
|
29
29
|
if (refusal) {
|
|
30
|
-
return { level: 'fail', detail: `device credential refused by the backend (${refusal.reason}) since ${refusal.since}; events are queued — enroll again with \`agentwatch setup
|
|
30
|
+
return { level: 'fail', detail: `device credential refused by the backend (${refusal.reason}) since ${refusal.since}; events are queued — enroll again with \`agentwatch setup\` (\`--token <install key>\` if the key is not kept on this machine)` };
|
|
31
31
|
}
|
|
32
32
|
// SPEC R4: an admin-assigned identity is marked as such wherever it shows.
|
|
33
33
|
const how = device.source === DEVICE_SOURCE_BATCH_CODE ? ', enrolled with an admin-issued code' : '';
|
|
@@ -4,8 +4,8 @@ import type { CredentialContext, DeviceCredentialRef, DeviceForgetResult } from
|
|
|
4
4
|
* The bearer to send for this config, doing the network work it needs.
|
|
5
5
|
*
|
|
6
6
|
* A config whose device is listed sends that device's access token, refreshed
|
|
7
|
-
* when due, and never its install key (
|
|
8
|
-
* again after the secret expires). An install key with no device yet is offered for exchange
|
|
7
|
+
* when due, and never its install key (kept in the device's secret store to
|
|
8
|
+
* enroll again after the secret expires). An install key with no device yet is offered for exchange
|
|
9
9
|
* first and presented itself only while that fails. A device the gateway
|
|
10
10
|
* refused is enrolled again when `migrateInstallKey` allows it, and its install
|
|
11
11
|
* key is never sent in its place. Undefined means "nothing to send with": the
|
|
@@ -35,7 +35,7 @@ export declare function cachedBearer(ctx: CredentialContext, config: AgentWatchC
|
|
|
35
35
|
/**
|
|
36
36
|
* The bearer an agent's own config file may hold (Codex, Gemini, AWT-357):
|
|
37
37
|
* the device access token, refreshed when due. Never the device secret. The
|
|
38
|
-
* install key while there is no access token: no device yet (its exchange
|
|
38
|
+
* install key (from the config or its device's store) while there is no access token: no device yet (its exchange
|
|
39
39
|
* is failing), or a device whose refresh is in cooldown or offline. Writing
|
|
40
40
|
* no header would get every export refused, and the hook only swaps an
|
|
41
41
|
* existing bearer. The hook replaces the key once a device token exists. For
|
|
@@ -13,14 +13,15 @@ import { readDeviceState } from './device-state.js';
|
|
|
13
13
|
import { ENROLL_LOCK_PREFIX } from './constants/credentials.constants.js';
|
|
14
14
|
import { credentialId, deviceFor, deviceRefs, identityOf } from './identity.js';
|
|
15
15
|
import { secretLocation, secretStoreFor } from './secret-store.js';
|
|
16
|
+
import { forgetInstallKey, storedInstallKey } from './install-key.js';
|
|
16
17
|
import { migrateInstallKey } from './migration.js';
|
|
17
18
|
import { cachedAccessToken, currentAccessToken } from './token-refresher.js';
|
|
18
19
|
/**
|
|
19
20
|
* The bearer to send for this config, doing the network work it needs.
|
|
20
21
|
*
|
|
21
22
|
* A config whose device is listed sends that device's access token, refreshed
|
|
22
|
-
* when due, and never its install key (
|
|
23
|
-
* again after the secret expires). An install key with no device yet is offered for exchange
|
|
23
|
+
* when due, and never its install key (kept in the device's secret store to
|
|
24
|
+
* enroll again after the secret expires). An install key with no device yet is offered for exchange
|
|
24
25
|
* first and presented itself only while that fails. A device the gateway
|
|
25
26
|
* refused is enrolled again when `migrateInstallKey` allows it, and its install
|
|
26
27
|
* key is never sent in its place. Undefined means "nothing to send with": the
|
|
@@ -41,7 +42,7 @@ export async function resolveBearer(ctx, config) {
|
|
|
41
42
|
return undefined;
|
|
42
43
|
if (deviceFor(config)) {
|
|
43
44
|
const token = await currentAccessToken(ctx, config);
|
|
44
|
-
if (token || !
|
|
45
|
+
if (token || !(await readDeviceState(identityPaths(ctx.paths, identityOf(config)).deviceStateFile)).refusal)
|
|
45
46
|
return token;
|
|
46
47
|
const renewed = await migrateInstallKey(ctx, config);
|
|
47
48
|
return renewed ? await currentAccessToken(ctx, { ...config, device: renewed }) : undefined;
|
|
@@ -82,7 +83,7 @@ export async function cachedBearer(ctx, config) {
|
|
|
82
83
|
/**
|
|
83
84
|
* The bearer an agent's own config file may hold (Codex, Gemini, AWT-357):
|
|
84
85
|
* the device access token, refreshed when due. Never the device secret. The
|
|
85
|
-
* install key while there is no access token: no device yet (its exchange
|
|
86
|
+
* install key (from the config or its device's store) while there is no access token: no device yet (its exchange
|
|
86
87
|
* is failing), or a device whose refresh is in cooldown or offline. Writing
|
|
87
88
|
* no header would get every export refused, and the hook only swaps an
|
|
88
89
|
* existing bearer. The hook replaces the key once a device token exists. For
|
|
@@ -96,7 +97,10 @@ export async function nativeExporterBearer(ctx, config) {
|
|
|
96
97
|
try {
|
|
97
98
|
if (await isUninstalled(ctx.paths))
|
|
98
99
|
return undefined;
|
|
99
|
-
|
|
100
|
+
const device = deviceFor(config);
|
|
101
|
+
if (!device)
|
|
102
|
+
return config.token;
|
|
103
|
+
return (await currentAccessToken(ctx, config)) ?? config.token ?? (await storedInstallKey(ctx, device));
|
|
100
104
|
}
|
|
101
105
|
catch (error) {
|
|
102
106
|
debugLog('credentials: resolving the native exporter bearer failed:', error);
|
|
@@ -158,8 +162,10 @@ export async function revokeDeviceIfUnused(ctx, device) {
|
|
|
158
162
|
*/
|
|
159
163
|
export async function forgetDeviceCredentials(ctx) {
|
|
160
164
|
const before = await loadConfig(ctx.paths);
|
|
161
|
-
const keys = [
|
|
162
|
-
|
|
165
|
+
const keys = [before.config.token, ...Object.values(before.config.roots ?? {}).map((root) => root.token)].filter((key) => Boolean(key));
|
|
166
|
+
// A device whose key moved to its store enrolls again under its own id.
|
|
167
|
+
const ids = new Set([...keys.map(credentialId), ...deviceRefs(before.config).map((ref) => ref.id)]);
|
|
168
|
+
const releases = await holdEnrollLocks(ctx, [...ids].sort());
|
|
163
169
|
let held = new Map();
|
|
164
170
|
let invalid = false;
|
|
165
171
|
let marked;
|
|
@@ -190,12 +196,12 @@ export async function forgetDeviceCredentials(ctx) {
|
|
|
190
196
|
return { marked, config: 'ok', revocations };
|
|
191
197
|
}
|
|
192
198
|
/**
|
|
193
|
-
* Each
|
|
199
|
+
* Each enroll lock, waiting a while for one a hook holds. A lock
|
|
194
200
|
* still taken after the wait is skipped: the exchange looks at the marker again
|
|
195
201
|
* before it attaches anything, so the lock narrows the race, it does not close it.
|
|
196
202
|
*
|
|
197
203
|
* @param ctx - Paths and clock.
|
|
198
|
-
* @param ids - The
|
|
204
|
+
* @param ids - The device ids of every install key and device the config names, sorted.
|
|
199
205
|
* @returns The releases of the locks taken.
|
|
200
206
|
*/
|
|
201
207
|
async function holdEnrollLocks(ctx, ids) {
|
|
@@ -267,12 +273,20 @@ async function revokeHeld(ctx, device) {
|
|
|
267
273
|
return { reason: result.status === undefined ? 'the platform could not be reached' : `the platform answered ${result.status}` };
|
|
268
274
|
}
|
|
269
275
|
/**
|
|
270
|
-
* Delete one device's secret and cached access token.
|
|
276
|
+
* Delete one device's secret, the install key kept beside it, and its cached access token.
|
|
271
277
|
*
|
|
272
278
|
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
273
279
|
* @param device - The device.
|
|
274
280
|
*/
|
|
275
281
|
async function forgetSecret(ctx, device) {
|
|
276
|
-
|
|
277
|
-
|
|
282
|
+
// Each part is tried whatever happened to the others: a secret the store would
|
|
283
|
+
// not let go of must not keep the install key on the machine too.
|
|
284
|
+
const results = await Promise.allSettled([
|
|
285
|
+
secretStoreFor(device.store, ctx).remove(device.id),
|
|
286
|
+
forgetInstallKey(ctx, device),
|
|
287
|
+
fs.rm(identityPaths(ctx.paths, identityOf({ device })).accessTokenFile, { force: true })
|
|
288
|
+
]);
|
|
289
|
+
const failed = results.find((result) => result.status === 'rejected');
|
|
290
|
+
if (failed)
|
|
291
|
+
throw failed.reason;
|
|
278
292
|
}
|
|
@@ -49,8 +49,8 @@ export declare function identityFingerprint(identity: string): string;
|
|
|
49
49
|
/**
|
|
50
50
|
* The device credential that stands for this config's identity, if any.
|
|
51
51
|
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
52
|
+
* A key and a device side by side are one identity until the exchange moves
|
|
53
|
+
* the key to the store (or an older edge left it there). A device whose
|
|
54
54
|
* id is not that key's is a leftover from an earlier key and stands for
|
|
55
55
|
* nothing.
|
|
56
56
|
*
|
|
@@ -63,8 +63,8 @@ export function identityFingerprint(identity) {
|
|
|
63
63
|
/**
|
|
64
64
|
* The device credential that stands for this config's identity, if any.
|
|
65
65
|
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
66
|
+
* A key and a device side by side are one identity until the exchange moves
|
|
67
|
+
* the key to the store (or an older edge left it there). A device whose
|
|
68
68
|
* id is not that key's is a leftover from an earlier key and stands for
|
|
69
69
|
* nothing.
|
|
70
70
|
*
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { CredentialContext, DeviceCredentialRef } from './types/credentials.types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Move an install key from the config into its device's secret store.
|
|
4
|
+
*
|
|
5
|
+
* The key is needed again only when the device secret expires, so it lives
|
|
6
|
+
* where the secret does, not in plain text in `config.json`. The config entry
|
|
7
|
+
* keeps it until the store has proven it holds the key, so a failed write never
|
|
8
|
+
* loses it. Never throws.
|
|
9
|
+
*
|
|
10
|
+
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
11
|
+
* @param installKey - The key that was exchanged.
|
|
12
|
+
* @param device - The device it was exchanged for.
|
|
13
|
+
* @param waitMs - How long to wait for the config lock.
|
|
14
|
+
* @returns True when the store holds the key and the config was updated.
|
|
15
|
+
*/
|
|
16
|
+
export declare function retireInstallKey(ctx: CredentialContext, installKey: string, device: DeviceCredentialRef, waitMs: number): Promise<boolean>;
|
|
17
|
+
/**
|
|
18
|
+
* The install key a device was exchanged for, from its secret store.
|
|
19
|
+
*
|
|
20
|
+
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
21
|
+
* @param device - The device.
|
|
22
|
+
* @returns The key, or undefined (a sign-in device has none).
|
|
23
|
+
*/
|
|
24
|
+
export declare function storedInstallKey(ctx: CredentialContext, device: DeviceCredentialRef): Promise<string | undefined>;
|
|
25
|
+
/**
|
|
26
|
+
* Remove the install key kept for a device, if any.
|
|
27
|
+
*
|
|
28
|
+
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
29
|
+
* @param device - The device being forgotten.
|
|
30
|
+
*/
|
|
31
|
+
export declare function forgetInstallKey(ctx: CredentialContext, device: DeviceCredentialRef): Promise<void>;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { detachInstallKey } from '../config/config-store.js';
|
|
2
|
+
import { debugLog } from '../core/logger.js';
|
|
3
|
+
import { INSTALL_KEY_ACCOUNT_SUFFIX } from './constants/credentials.constants.js';
|
|
4
|
+
import { secretStoreFor, storeVerified } from './secret-store.js';
|
|
5
|
+
/**
|
|
6
|
+
* The account (or file name) a device's install key is kept under, beside its secret.
|
|
7
|
+
*
|
|
8
|
+
* @param device - The device.
|
|
9
|
+
* @returns The account name.
|
|
10
|
+
*/
|
|
11
|
+
function installKeyAccount(device) {
|
|
12
|
+
return device.id + INSTALL_KEY_ACCOUNT_SUFFIX;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Move an install key from the config into its device's secret store.
|
|
16
|
+
*
|
|
17
|
+
* The key is needed again only when the device secret expires, so it lives
|
|
18
|
+
* where the secret does, not in plain text in `config.json`. The config entry
|
|
19
|
+
* keeps it until the store has proven it holds the key, so a failed write never
|
|
20
|
+
* loses it. Never throws.
|
|
21
|
+
*
|
|
22
|
+
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
23
|
+
* @param installKey - The key that was exchanged.
|
|
24
|
+
* @param device - The device it was exchanged for.
|
|
25
|
+
* @param waitMs - How long to wait for the config lock.
|
|
26
|
+
* @returns True when the store holds the key and the config was updated.
|
|
27
|
+
*/
|
|
28
|
+
export async function retireInstallKey(ctx, installKey, device, waitMs) {
|
|
29
|
+
try {
|
|
30
|
+
if (!(await storeVerified(ctx, device.store, installKeyAccount(device), installKey)))
|
|
31
|
+
return false;
|
|
32
|
+
return (await detachInstallKey(ctx.paths, installKey, device.id, waitMs)) !== 'busy';
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
debugLog('credentials: moving the install key out of the config failed; it stays there:', error);
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The install key a device was exchanged for, from its secret store.
|
|
41
|
+
*
|
|
42
|
+
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
43
|
+
* @param device - The device.
|
|
44
|
+
* @returns The key, or undefined (a sign-in device has none).
|
|
45
|
+
*/
|
|
46
|
+
export async function storedInstallKey(ctx, device) {
|
|
47
|
+
// Outside a hook's deadline: a read cut short would look like "no key" and back the re-enrollment off for an hour.
|
|
48
|
+
return secretStoreFor(device.store, { ...ctx, deadline: undefined }).get(installKeyAccount(device)).catch(() => undefined);
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Remove the install key kept for a device, if any.
|
|
52
|
+
*
|
|
53
|
+
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
54
|
+
* @param device - The device being forgotten.
|
|
55
|
+
*/
|
|
56
|
+
export async function forgetInstallKey(ctx, device) {
|
|
57
|
+
await secretStoreFor(device.store, ctx).remove(installKeyAccount(device));
|
|
58
|
+
}
|
|
@@ -8,17 +8,19 @@ import type { CredentialContext, DeviceCredentialRef } from './types/credentials
|
|
|
8
8
|
* run — written by an older setup, by `setup --token` or from
|
|
9
9
|
* `$AGENTWATCH_TOKEN`. Order matters: the secret is stored and the first token
|
|
10
10
|
* cached before the config names the device, so a crash in between costs one
|
|
11
|
-
* more exchange, never the credential.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
11
|
+
* more exchange, never the credential. Once the device is named, the install
|
|
12
|
+
* key moves from the config into the device's secret store, to enroll again
|
|
13
|
+
* when the secret expires (`retireInstallKey`); a config written before that
|
|
14
|
+
* loses its key the next time this runs. A failure keeps the key in the config
|
|
15
|
+
* and in use, and the next try waits an hour.
|
|
14
16
|
*
|
|
15
17
|
* A device the gateway refused counts as no device: an expired secret is
|
|
16
18
|
* enrolled again by any run, a revoked or unknown one only when setup asks
|
|
17
19
|
* (`ignoreBackoff`), so a hook never undoes an admin's revocation.
|
|
18
20
|
*
|
|
19
|
-
* Never for a scope `uninstall` marked, until setup runs for it again:
|
|
20
|
-
*
|
|
21
|
-
* revoked. Asked before the lock, under it, and once more before the device is
|
|
21
|
+
* Never for a scope `uninstall` marked, until setup runs for it again: a key
|
|
22
|
+
* still in the config is there for a reinstall, not for re-enrolling a device
|
|
23
|
+
* just revoked. Asked before the lock, under it, and once more before the device is
|
|
22
24
|
* attached; a device enrolled while uninstall marked the scope is revoked and
|
|
23
25
|
* forgotten here, since uninstall can no longer see it.
|
|
24
26
|
*
|
|
@@ -26,7 +28,7 @@ import type { CredentialContext, DeviceCredentialRef } from './types/credentials
|
|
|
26
28
|
* fit a hook's budget. Setup makes the exchange there.
|
|
27
29
|
*
|
|
28
30
|
* @param ctx - Paths, clock, timeout, fetch and keychain runner.
|
|
29
|
-
* @param config - Effective config whose `token` is the install key.
|
|
31
|
+
* @param config - Effective config whose `token` is the install key, or whose device has its key in the store.
|
|
30
32
|
* @param options - `ignoreBackoff` for setup, where someone asked for it now.
|
|
31
33
|
* @param options.ignoreBackoff - Try even within an hour of a failed attempt.
|
|
32
34
|
* @returns The device credential now standing for the key, or undefined.
|
|
@@ -7,11 +7,12 @@ import { acquireLock } from '../storage/lock.js';
|
|
|
7
7
|
import { isUninstalled } from '../storage/uninstalled.js';
|
|
8
8
|
import { BackendAuthBlock } from '../transport/auth-block.js';
|
|
9
9
|
import { identityPaths } from '../transport/queue-partition.js';
|
|
10
|
-
import { ENROLL_LOCK_PREFIX, ENROLL_RETRY_MS, REFUSAL_SECRET_EXPIRED } from './constants/credentials.constants.js';
|
|
10
|
+
import { DEVICE_IDENTITY_PREFIX, ENROLL_LOCK_PREFIX, ENROLL_RETRY_MS, REFUSAL_SECRET_EXPIRED } from './constants/credentials.constants.js';
|
|
11
11
|
import { enrollDevice, revokeDevice } from './device-api.js';
|
|
12
12
|
import { readDeviceState, writeAccessToken, writeDeviceState } from './device-state.js';
|
|
13
13
|
import { withinBudget } from './budget.js';
|
|
14
|
-
import {
|
|
14
|
+
import { deviceRefs, identityFingerprint, identityOf } from './identity.js';
|
|
15
|
+
import { forgetInstallKey, retireInstallKey, storedInstallKey } from './install-key.js';
|
|
15
16
|
import { saveSecret, secretStoreFor } from './secret-store.js';
|
|
16
17
|
/**
|
|
17
18
|
* Exchange the install key this config holds for a device credential, once.
|
|
@@ -21,17 +22,19 @@ import { saveSecret, secretStoreFor } from './secret-store.js';
|
|
|
21
22
|
* run — written by an older setup, by `setup --token` or from
|
|
22
23
|
* `$AGENTWATCH_TOKEN`. Order matters: the secret is stored and the first token
|
|
23
24
|
* cached before the config names the device, so a crash in between costs one
|
|
24
|
-
* more exchange, never the credential.
|
|
25
|
-
*
|
|
26
|
-
*
|
|
25
|
+
* more exchange, never the credential. Once the device is named, the install
|
|
26
|
+
* key moves from the config into the device's secret store, to enroll again
|
|
27
|
+
* when the secret expires (`retireInstallKey`); a config written before that
|
|
28
|
+
* loses its key the next time this runs. A failure keeps the key in the config
|
|
29
|
+
* and in use, and the next try waits an hour.
|
|
27
30
|
*
|
|
28
31
|
* A device the gateway refused counts as no device: an expired secret is
|
|
29
32
|
* enrolled again by any run, a revoked or unknown one only when setup asks
|
|
30
33
|
* (`ignoreBackoff`), so a hook never undoes an admin's revocation.
|
|
31
34
|
*
|
|
32
|
-
* Never for a scope `uninstall` marked, until setup runs for it again:
|
|
33
|
-
*
|
|
34
|
-
* revoked. Asked before the lock, under it, and once more before the device is
|
|
35
|
+
* Never for a scope `uninstall` marked, until setup runs for it again: a key
|
|
36
|
+
* still in the config is there for a reinstall, not for re-enrolling a device
|
|
37
|
+
* just revoked. Asked before the lock, under it, and once more before the device is
|
|
35
38
|
* attached; a device enrolled while uninstall marked the scope is revoked and
|
|
36
39
|
* forgotten here, since uninstall can no longer see it.
|
|
37
40
|
*
|
|
@@ -39,14 +42,15 @@ import { saveSecret, secretStoreFor } from './secret-store.js';
|
|
|
39
42
|
* fit a hook's budget. Setup makes the exchange there.
|
|
40
43
|
*
|
|
41
44
|
* @param ctx - Paths, clock, timeout, fetch and keychain runner.
|
|
42
|
-
* @param config - Effective config whose `token` is the install key.
|
|
45
|
+
* @param config - Effective config whose `token` is the install key, or whose device has its key in the store.
|
|
43
46
|
* @param options - `ignoreBackoff` for setup, where someone asked for it now.
|
|
44
47
|
* @param options.ignoreBackoff - Try even within an hour of a failed attempt.
|
|
45
48
|
* @returns The device credential now standing for the key, or undefined.
|
|
46
49
|
*/
|
|
47
50
|
export async function migrateInstallKey(ctx, config, options = {}) {
|
|
48
|
-
const
|
|
49
|
-
|
|
51
|
+
const identity = identityOf(config);
|
|
52
|
+
const id = identity === undefined ? undefined : identityFingerprint(identity);
|
|
53
|
+
if (!id || !config.endpoint)
|
|
50
54
|
return undefined;
|
|
51
55
|
if (ctx.hookPath && ctx.env.platform === 'win32')
|
|
52
56
|
return undefined;
|
|
@@ -54,22 +58,36 @@ export async function migrateInstallKey(ctx, config, options = {}) {
|
|
|
54
58
|
// enroll: only setup, which lifts the marker first, may.
|
|
55
59
|
if (await isUninstalled(ctx.paths, ctx.scope))
|
|
56
60
|
return undefined;
|
|
57
|
-
const
|
|
58
|
-
const
|
|
61
|
+
const files = identityPaths(ctx.paths, DEVICE_IDENTITY_PREFIX + id);
|
|
62
|
+
const waitMs = ctx.hookPath ? CONFIG_LOCK_HOOK_WAIT_MS : CONFIG_LOCK_WAIT_MS;
|
|
59
63
|
// Cheap checks first, so a backed-off key costs a hook no lock; both are
|
|
60
64
|
// asked again under the lock, where the answer can no longer change.
|
|
61
65
|
const settled = await settledExchange(ctx, id, files.deviceStateFile, options);
|
|
62
|
-
|
|
66
|
+
// A config written before the key left it (an older edge) still holds it beside its device.
|
|
67
|
+
// Only the entry that names the device beside it, which is what `detachInstallKey` clears.
|
|
68
|
+
const leftKey = settled.done && settled.device !== undefined && config.token !== undefined && config.device?.id === id;
|
|
69
|
+
if (settled.done && !leftKey)
|
|
63
70
|
return settled.device;
|
|
64
71
|
const release = await acquireLock(ctx.paths.locksDir, ENROLL_LOCK_PREFIX + id, ctx.env.now).catch(() => undefined);
|
|
72
|
+
// The device stands either way; moving the key waits for the next run.
|
|
65
73
|
if (!release)
|
|
66
|
-
return undefined;
|
|
74
|
+
return leftKey ? settled.device : undefined;
|
|
67
75
|
try {
|
|
68
76
|
const recheck = await settledExchange(ctx, id, files.deviceStateFile, options);
|
|
69
|
-
|
|
70
|
-
return recheck.device;
|
|
77
|
+
// Under the lock, so uninstall (which takes it) cannot remove the key from the store in between.
|
|
71
78
|
if (await isUninstalled(ctx.paths, ctx.scope))
|
|
72
79
|
return undefined;
|
|
80
|
+
if (recheck.done) {
|
|
81
|
+
if (recheck.device && config.token && config.device?.id === id)
|
|
82
|
+
await retireInstallKey(ctx, config.token, recheck.device, waitMs);
|
|
83
|
+
return recheck.device;
|
|
84
|
+
}
|
|
85
|
+
const installKey = config.token ?? (config.device ? await storedInstallKey(ctx, config.device) : undefined);
|
|
86
|
+
// A device signed in through the browser has no key: back off, so a hook does not ask the keychain every turn.
|
|
87
|
+
if (!installKey) {
|
|
88
|
+
await writeDeviceState(files.deviceStateFile, { ...recheck.state, enrollAttemptAt: ctx.env.now().toISOString() });
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
73
91
|
const now = ctx.env.now();
|
|
74
92
|
const budget = withinBudget(ctx);
|
|
75
93
|
if (!budget)
|
|
@@ -93,17 +111,38 @@ export async function migrateInstallKey(ctx, config, options = {}) {
|
|
|
93
111
|
await abandonDevice(ctx, device, result.value.deviceSecret, files.accessTokenFile);
|
|
94
112
|
return undefined;
|
|
95
113
|
}
|
|
96
|
-
const attached = await attachDevice(ctx.paths, installKey, device,
|
|
114
|
+
const attached = await attachDevice(ctx.paths, installKey, device, waitMs);
|
|
97
115
|
// Unnamed in the config (the lock was busy), the device is invisible to the
|
|
98
116
|
// next run: keep the backoff, or every hook would enroll yet another one.
|
|
99
117
|
await writeDeviceState(files.deviceStateFile, (await namesDevice(ctx, attached, device)) ? {} : { enrollAttemptAt: now.toISOString() });
|
|
100
118
|
await new BackendAuthBlock(files.authBlockFile, ctx.env.now).clear();
|
|
119
|
+
// Uninstall may have overtaken the exchange since the last look: it removes the key, so it must not come back.
|
|
120
|
+
if (await isUninstalled(ctx.paths, ctx.scope))
|
|
121
|
+
return device;
|
|
122
|
+
await keepInstallKey(ctx, installKey, config.token === undefined ? config.device : undefined, device, waitMs);
|
|
101
123
|
return device;
|
|
102
124
|
}
|
|
103
125
|
finally {
|
|
104
126
|
await release();
|
|
105
127
|
}
|
|
106
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* After an exchange, keep the key in the new device's store only. A key read
|
|
131
|
+
* from the store is written again only when the secret moved to another store
|
|
132
|
+
* (a keychain that works now), and the old copy goes once the new one is proven.
|
|
133
|
+
*
|
|
134
|
+
* @param ctx - Paths, environment, timeout and keychain runner.
|
|
135
|
+
* @param installKey - The key just exchanged.
|
|
136
|
+
* @param previous - The device whose store the key was read from, when it was.
|
|
137
|
+
* @param device - The device it was exchanged for.
|
|
138
|
+
* @param waitMs - How long to wait for the config lock.
|
|
139
|
+
*/
|
|
140
|
+
async function keepInstallKey(ctx, installKey, previous, device, waitMs) {
|
|
141
|
+
if (previous?.store === device.store)
|
|
142
|
+
return;
|
|
143
|
+
if ((await retireInstallKey(ctx, installKey, device, waitMs)) && previous)
|
|
144
|
+
await forgetInstallKey(ctx, previous).catch(() => undefined);
|
|
145
|
+
}
|
|
107
146
|
/**
|
|
108
147
|
* Undo an exchange uninstall overtook: revoke the device on the platform and
|
|
109
148
|
* forget it here, best effort. Its secret is in hand, so no keychain read.
|
|
@@ -120,6 +159,7 @@ export async function abandonDevice(ctx, device, secret, tokenFile) {
|
|
|
120
159
|
if (!revoked)
|
|
121
160
|
warnLog('a device that was enrolled but not kept (uninstall overtook it, or setup could not save it) could not be revoked; it may still be active on the platform. An admin can revoke this machine in Settings → Install.');
|
|
122
161
|
await secretStoreFor(device.store, ctx).remove(device.id).catch(() => undefined);
|
|
162
|
+
await forgetInstallKey(ctx, device).catch(() => undefined);
|
|
123
163
|
await fs.rm(tokenFile, { force: true }).catch(() => undefined);
|
|
124
164
|
debugLog('device enrollment overtaken by uninstall; revoked and forgotten');
|
|
125
165
|
}
|