@skrr-ai/cli 0.1.78 → 0.1.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/base-command.js +9 -2
  2. package/dist/commands/inbox/index.js +4 -2
  3. package/dist/commands/login.d.ts +8 -3
  4. package/dist/commands/login.js +14 -4
  5. package/dist/commands/spaces/workflows/events.js +9 -2
  6. package/dist/lib/agentic-stream.js +13 -4
  7. package/dist/lib/api-fetch.js +6 -2
  8. package/dist/lib/brokered-dpop.d.ts +34 -0
  9. package/dist/lib/brokered-dpop.js +89 -0
  10. package/dist/lib/daemonBroker.d.ts +71 -2
  11. package/dist/lib/daemonBroker.js +203 -36
  12. package/dist/lib/daemonBrokerRefusal.d.ts +26 -0
  13. package/dist/lib/daemonBrokerRefusal.js +83 -4
  14. package/dist/lib/daemonRestartWait.d.ts +39 -0
  15. package/dist/lib/daemonRestartWait.js +181 -0
  16. package/dist/lib/dedicated-lease-command.js +1 -0
  17. package/dist/lib/dedicated-service.js +10 -5
  18. package/dist/lib/dedicated-ssh.js +6 -3
  19. package/dist/lib/dedicated-terminal.d.ts +3 -0
  20. package/dist/lib/dedicated-terminal.js +77 -18
  21. package/dist/lib/dpop-auth.d.ts +35 -0
  22. package/dist/lib/dpop-auth.js +57 -0
  23. package/dist/lib/login.d.ts +6 -0
  24. package/dist/lib/login.js +13 -4
  25. package/dist/lib/node-adapter.js +4 -0
  26. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/cliHandoffWire.d.ts +42 -1
  27. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/cliHandoffWire.js +35 -3
  28. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/credentialSession.d.ts +49 -1
  29. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/credentialSession.js +47 -9
  30. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/deviceKey.d.ts +56 -0
  31. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/deviceKey.js +42 -20
  32. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/dpop.d.ts +101 -0
  33. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/dpop.js +179 -0
  34. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/index.d.ts +1 -0
  35. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/index.js +19 -3
  36. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/cliHandoffWire.d.ts +42 -1
  37. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/cliHandoffWire.js +32 -2
  38. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/credentialSession.d.ts +49 -1
  39. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/credentialSession.js +47 -9
  40. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/deviceKey.d.ts +56 -0
  41. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/deviceKey.js +39 -20
  42. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/dpop.d.ts +101 -0
  43. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/dpop.js +138 -0
  44. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/index.d.ts +1 -0
  45. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/index.js +4 -0
  46. package/dist/node_modules/@skrr-ai/auth-core/package.json +1 -1
  47. package/dist/node_modules/@skrr-ai/data-provider/index.js +3422 -3407
  48. package/oclif.manifest.json +41505 -41505
  49. package/package.json +2 -2
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ /**
3
+ * dpop.ts — RFC 9449 proof-of-possession for ACCESS tokens.
4
+ *
5
+ * Sibling of `deviceKey.ts`, and deliberately a different protocol on the
6
+ * wire. A device-identity proof (`typ: oversky-dpop+jwt`, header
7
+ * `OverSky-DPoP`) proves a daemon holds its ENROLLED key and authorizes
8
+ * minting/rotating that daemon's families. An access-token proof
9
+ * (`typ: dpop+jwt`, header `DPoP`) proves the presenter of an access token
10
+ * holds the key the token is bound to (`cnf.jkt`). The `typ` keeps either
11
+ * proof from ever verifying as the other.
12
+ *
13
+ * Why a SEPARATE key, never the device key (OSK-12020): the access-token key
14
+ * signs whatever `{htm, htu, ath}` a local caller asks of the daemon's proof
15
+ * oracle (`/v1/auth/cli-handoff-dpop-proof`). Handing that oracle the device
16
+ * key would turn it into a signer for the credential that mints families —
17
+ * one confused-deputy step from the workload asking for a device proof over
18
+ * `POST /api/daemons/cli-handoff`. A dedicated key carries no authority but
19
+ * the tokens bound to it, lives only in daemon memory (`createDpopKey` never
20
+ * exposes the private half), and dies with the family it binds.
21
+ *
22
+ * Algorithm: EdDSA / Ed25519, the same primitive as the device key. RFC 9449
23
+ * lets the server advertise `dpop_signing_alg_values_supported`; ours is
24
+ * exactly `["EdDSA"]`, and the verifier refuses anything else.
25
+ */
26
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
27
+ if (k2 === undefined) k2 = k;
28
+ var desc = Object.getOwnPropertyDescriptor(m, k);
29
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
30
+ desc = { enumerable: true, get: function() { return m[k]; } };
31
+ }
32
+ Object.defineProperty(o, k2, desc);
33
+ }) : (function(o, m, k, k2) {
34
+ if (k2 === undefined) k2 = k;
35
+ o[k2] = m[k];
36
+ }));
37
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
38
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
39
+ }) : function(o, v) {
40
+ o["default"] = v;
41
+ });
42
+ var __importStar = (this && this.__importStar) || (function () {
43
+ var ownKeys = function(o) {
44
+ ownKeys = Object.getOwnPropertyNames || function (o) {
45
+ var ar = [];
46
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
47
+ return ar;
48
+ };
49
+ return ownKeys(o);
50
+ };
51
+ return function (mod) {
52
+ if (mod && mod.__esModule) return mod;
53
+ var result = {};
54
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
55
+ __setModuleDefault(result, mod);
56
+ return result;
57
+ };
58
+ })();
59
+ Object.defineProperty(exports, "__esModule", { value: true });
60
+ exports.isJwkThumbprint = exports.DPOP_PROOF_VERIFY_UNAVAILABLE = exports.DPOP_PROOF_INVALID = exports.DPOP_PROOF_REQUIRED = exports.DPOP_MAX_AGE_SECONDS = exports.DPOP_HEADER = exports.DPOP_PROOF_TYP = void 0;
61
+ exports.createDpopKey = createDpopKey;
62
+ exports.normalizeDpopHtu = normalizeDpopHtu;
63
+ exports.accessTokenHash = accessTokenHash;
64
+ exports.isAth = isAth;
65
+ exports.verifyDpopProof = verifyDpopProof;
66
+ const crypto = __importStar(require("node:crypto"));
67
+ const deviceKey_js_1 = require("./deviceKey.js");
68
+ /** RFC 9449 §4.2 — the proof's JOSE header `typ`. */
69
+ exports.DPOP_PROOF_TYP = 'dpop+jwt';
70
+ /** RFC 9449 §4.1 — the request header carrying the proof. */
71
+ exports.DPOP_HEADER = 'DPoP';
72
+ /** Default freshness window, matching the device-proof verifier. */
73
+ exports.DPOP_MAX_AGE_SECONDS = 60;
74
+ /** Server error codes for a bound token presented without a usable proof. */
75
+ exports.DPOP_PROOF_REQUIRED = 'DPOP_PROOF_REQUIRED';
76
+ exports.DPOP_PROOF_INVALID = 'DPOP_PROOF_INVALID';
77
+ exports.DPOP_PROOF_VERIFY_UNAVAILABLE = 'DPOP_PROOF_VERIFY_UNAVAILABLE';
78
+ function createDpopKey() {
79
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');
80
+ const exported = publicKey.export({ format: 'jwk' });
81
+ if (exported.kty !== 'OKP' || exported.crv !== 'Ed25519' || typeof exported.x !== 'string') {
82
+ throw new Error('createDpopKey: unexpected public JWK shape');
83
+ }
84
+ const publicJwk = Object.freeze({ kty: 'OKP', crv: 'Ed25519', x: exported.x });
85
+ const thumbprint = (0, deviceKey_js_1.jwkThumbprint)(publicJwk);
86
+ return Object.freeze({
87
+ publicJwk,
88
+ thumbprint,
89
+ sign(req) {
90
+ return buildDpopProofWithKey(privateKey, publicJwk, req);
91
+ },
92
+ });
93
+ }
94
+ function b64u(buf) {
95
+ return buf.toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
96
+ }
97
+ /**
98
+ * Sign one proof. `ath` comes from the token when the signer holds it, or is
99
+ * taken as given — the daemon's proof oracle is handed the hash and never the
100
+ * token, which is the point of the oracle.
101
+ */
102
+ function buildDpopProofWithKey(privateKey, publicJwk, req) {
103
+ if (typeof req.htm !== 'string' || !/^[A-Za-z]{3,10}$/.test(req.htm)) {
104
+ throw new Error('dpop: htm must be an HTTP method');
105
+ }
106
+ if (typeof req.htu !== 'string' || req.htu.length === 0) {
107
+ throw new Error('dpop: htu must be a URL');
108
+ }
109
+ const ath = req.accessToken !== undefined ? (0, deviceKey_js_1.tokenHash)(req.accessToken) : req.ath;
110
+ if (ath !== undefined && !isAth(ath)) {
111
+ throw new Error('dpop: ath must be a base64url SHA-256 digest');
112
+ }
113
+ const header = { alg: 'EdDSA', typ: exports.DPOP_PROOF_TYP, jwk: publicJwk };
114
+ const claims = {
115
+ htm: req.htm.toUpperCase(),
116
+ htu: normalizeDpopHtu(req.htu),
117
+ iat: req.iat ?? Math.floor(Date.now() / 1000),
118
+ jti: req.jti ?? b64u(crypto.randomBytes(16)),
119
+ ...(ath !== undefined ? { ath } : {}),
120
+ };
121
+ const signingInput = `${b64u(Buffer.from(JSON.stringify(header), 'utf-8'))}.${b64u(Buffer.from(JSON.stringify(claims), 'utf-8'))}`;
122
+ const signature = crypto.sign(null, Buffer.from(signingInput, 'utf-8'), privateKey);
123
+ return `${signingInput}.${b64u(signature)}`;
124
+ }
125
+ /** RFC 9449 §4.2 htu normalization — identical to the device proof's. */
126
+ function normalizeDpopHtu(url) {
127
+ return (0, deviceKey_js_1.normalizeHtu)(url);
128
+ }
129
+ /** `ath` for an access token: base64url(SHA-256(ascii(token))), RFC 9449 §4.2. */
130
+ function accessTokenHash(accessToken) {
131
+ return (0, deviceKey_js_1.tokenHash)(accessToken);
132
+ }
133
+ /** True for a value shaped like an `ath` / `jkt` (43-char base64url SHA-256). */
134
+ function isAth(value) {
135
+ return typeof value === 'string' && /^[A-Za-z0-9_-]{43}$/.test(value);
136
+ }
137
+ /** Same shape test, named for the `cnf.jkt` call sites. */
138
+ exports.isJwkThumbprint = isAth;
139
+ /**
140
+ * Verify an RFC 9449 proof: `typ` dpop+jwt, `alg` EdDSA, a well-formed inline
141
+ * JWK, the signature, iat window, htm, htu, `ath` (when expected) and the
142
+ * key's thumbprint against `expectedJkt` (when given).
143
+ *
144
+ * Replay (`jti`) is NOT checked here — it needs shared state, and the caller
145
+ * owns that (the API's Redis jti cache). A verifier that claimed to do it in
146
+ * process memory would be wrong on every multi-replica deployment.
147
+ */
148
+ function verifyDpopProof(jws, opts) {
149
+ const result = (0, deviceKey_js_1.verifyEd25519Proof)(jws, {
150
+ expectedHtm: opts.expectedHtm,
151
+ expectedHtu: opts.expectedHtu,
152
+ ...(opts.maxAgeSeconds !== undefined ? { maxAgeSeconds: opts.maxAgeSeconds } : {}),
153
+ ...(opts.clockSkewSeconds !== undefined ? { clockSkewSeconds: opts.clockSkewSeconds } : {}),
154
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
155
+ }, exports.DPOP_PROOF_TYP);
156
+ if (!result.valid) {
157
+ // rth/pin are device-proof-only checks the options above never request.
158
+ return { valid: false, reason: result.reason };
159
+ }
160
+ // An empty jti cannot be claimed in a replay cache, so it is not a nonce.
161
+ if (result.claims.jti.length === 0)
162
+ return { valid: false, reason: 'malformed' };
163
+ if (opts.expectedAth !== undefined) {
164
+ if (typeof result.claims.ath !== 'string')
165
+ return { valid: false, reason: 'ath_missing' };
166
+ if (result.claims.ath !== opts.expectedAth)
167
+ return { valid: false, reason: 'ath_mismatch' };
168
+ }
169
+ if (opts.expectedJkt !== undefined && result.thumbprint !== opts.expectedJkt) {
170
+ return { valid: false, reason: 'jkt_mismatch' };
171
+ }
172
+ const { htm, htu, iat, jti, ath } = result.claims;
173
+ return {
174
+ valid: true,
175
+ claims: { htm, htu, iat, jti, ...(typeof ath === 'string' ? { ath } : {}) },
176
+ thumbprint: result.thumbprint,
177
+ publicJwk: result.publicJwk,
178
+ };
179
+ }
@@ -27,6 +27,7 @@ export { formatRecoveryCode, parseRecoveryCode, normalizeRecoveryCode, isValidRe
27
27
  export { buildCredentialAad, decrypt as credEnvelopeDecrypt, deserialize as credEnvelopeDeserialize, encrypt as credEnvelopeEncrypt, ENVELOPE_MAGIC as CRED_ENVELOPE_MAGIC, generateDek, isEnvelopeString as isCredEnvelopeString, KEY_LEN as CRED_KEY_LEN, openBuffer as credOpenBuffer, sealBuffer as credSealBuffer, serialize as credEnvelopeSerialize, unwrap as credEnvelopeUnwrap, wrap as credEnvelopeWrap, type SealedBlob as CredSealedBlob, } from './credentialEnvelope.js';
28
28
  export { __setKekStrategyForTest, getKekStrategy, InMemoryKek, UnavailableKek, KekUnavailableError, LinuxKek, MacosKek, registerZeroizeHook, WindowsKek, zeroizeKekCaches, type KekStrategy, } from './kek/index.js';
29
29
  export { buildProof as buildDeviceProof, generateDeviceKeyPair, jwkThumbprint, normalizeHtu, publicJwkFromX, tokenHash, verifyProof as verifyDeviceProof, type DeviceKeyPair, type DeviceProofClaims, type DeviceProofHeader, type Ed25519PrivateJwk, type Ed25519PublicJwk, type VerifyFailureReason as DeviceProofVerifyFailureReason, type VerifyFailure as DeviceProofVerifyFailure, type VerifyOptions as DeviceProofVerifyOptions, type VerifySuccess as DeviceProofVerifySuccess, } from './deviceKey.js';
30
+ export { DPOP_HEADER, DPOP_MAX_AGE_SECONDS, DPOP_PROOF_INVALID, DPOP_PROOF_REQUIRED, DPOP_PROOF_TYP, DPOP_PROOF_VERIFY_UNAVAILABLE, accessTokenHash, createDpopKey, isAth, isJwkThumbprint, normalizeDpopHtu, verifyDpopProof, type DpopKey, type DpopProofClaims, type DpopProofRequest, type DpopVerifyFailureReason, type DpopVerifyOptions, type DpopVerifyResult, } from './dpop.js';
30
31
  export { initCredEnvelope, resetCredEnvelope, shutdownCredEnvelope, isCredEnvelopeActive, hasCredEnvelopePathConflict, describeCredEnvelopeState, splitKeyConvergencePolicy, maybeEncryptForWrite, maybeDecryptOnRead, DEFAULT_UNREADABLE_CREDENTIAL_HINT, type DecryptOnReadOptions, __wrappedDekFilePathForTest, __setStateForTest as __setCredEnvelopeStateForTest, __getStateForTest as __getCredEnvelopeStateForTest, __resetShutdownGuardForTest, type ReadTransformResult, } from './credentialEnvelopeBridge.js';
31
32
  export { initDeviceIdentity, resetDeviceIdentity, signServerRequest, enrollWithServer, clearEnrollmentMarker, isDeviceIdentityActive, getDevicePublicKey, describeDeviceIdentityState, describeDeviceKeySplit, __publicKeyPathForTest, __privateKeyPathForTest, __enrollmentMarkerPathForTest, __enrollmentBackoffPathForTest, __setStateForTest as __setDeviceIdentityStateForTest, __getStateForTest as __getDeviceIdentityStateForTest, type EnrollmentResult, } from './deviceIdentityBridge.js';
32
33
  export { getMachineUuid, hostedRuntimeIdOverride, HOSTED_RUNTIME_MACHINE_SOURCES, __resetMachineUuidCacheForTest, } from './machineUuid.js';
@@ -24,9 +24,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
25
  exports.generateVerifier = exports.invalidateHeadersHelperCache = exports.runHeadersHelper = exports.SENTINEL_TRIGGERING_FAILURES = exports.__resetAuthHelperFailureReasonForTest = exports.getLastAuthHelperFailureReason = exports.getDefaultHelperTtlMs = exports.invokeAuthHelper = exports.AuthHelperUnavailableError = exports.AuthHelperUntrustedError = exports.CI_TOKEN_PREFIX = exports.classifyTokenKind = exports.invalidateAuthHelperCache = exports.__resetCredentialResolverForTest = exports.CREDENTIAL_PRECEDENCE = exports.CredentialResolver = exports.__setFdReaderForTest = exports.readAuthFromFd = exports.createRefreshScheduler = exports.UNKNOWN_401_BUDGET = exports.__resetUnknown401StreaksForTest = exports.__refreshDiagnostics = exports.installLockExitHandlers = exports.clearReauthState = exports.needsReauthState = exports.persistReauthState = exports.withAuthLock = exports.revokeDaemonRefreshSession = exports.refreshDaemonToken = exports.classifyRefreshResponse = exports.EXIT_NEEDS_REAUTH = exports.reauthCommand = exports.formatReauthMessage = exports.handleMidStreamAuthExpiry = exports.isAuthExpiredSseEvent = exports.decodeJwtPayload = exports.decodeJwtExpiry = exports.TransientAuthFailure = exports.PermanentAuthFailure = exports.emitAuthTelemetry = exports.getAuthBinaryName = exports.getAuthKillSwitches = exports.getAuthConfigDir = exports.getAuthLogger = exports.configureAuthCore = exports.OAUTH_CLI_SCOPE = exports.isDaemonScope = exports.VALID_DAEMON_SCOPE_SET = exports.ALL_DAEMON_SCOPES = exports.SCOPES = void 0;
26
26
  exports.publicJwkFromX = exports.normalizeHtu = exports.jwkThumbprint = exports.generateDeviceKeyPair = exports.buildDeviceProof = exports.zeroizeKekCaches = exports.WindowsKek = exports.registerZeroizeHook = exports.MacosKek = exports.LinuxKek = exports.KekUnavailableError = exports.UnavailableKek = exports.InMemoryKek = exports.getKekStrategy = exports.__setKekStrategyForTest = exports.credEnvelopeWrap = exports.credEnvelopeUnwrap = exports.credEnvelopeSerialize = exports.credSealBuffer = exports.credOpenBuffer = exports.CRED_KEY_LEN = exports.isCredEnvelopeString = exports.generateDek = exports.CRED_ENVELOPE_MAGIC = exports.credEnvelopeEncrypt = exports.credEnvelopeDeserialize = exports.credEnvelopeDecrypt = exports.buildCredentialAad = exports.isValidRecoveryCode = exports.normalizeRecoveryCode = exports.parseRecoveryCode = exports.formatRecoveryCode = exports.MAX_TTL_DAYS = exports.MIN_TTL_DAYS = exports.parseTtlDays = exports.LoginExchangeError = exports.LoginInitError = exports.loginWithLocalhost = exports.LocalCallbackMalformedError = exports.LocalCallbackDeniedError = exports.LocalCallbackStateMismatchError = exports.LocalCallbackTimeoutError = exports.LocalCallbackBindError = exports.LocalCallbackError = exports.DEFAULT_LOGIN_TIMEOUT_MS = exports.startLocalCallback = exports.verifyChallenge = exports.safeEqual = exports.generateState = exports.challenge = void 0;
27
- exports.buildPairUrl = exports.buildPairAad = exports.pairBase64UrlToUint8Array = exports.pairBase64ToUint8Array = exports.assemblePairBundleBase64 = exports.PairBundleError = exports.PAIR_SECRET_LEN = exports.PAIR_PUBKEY_LEN = exports.PAIR_NONCE_LEN = exports.PAIR_BUNDLE_MAX_BASE64_LEN = exports.PAIR_AAD_MAX_LEN = exports.PAIR_AAD_PREFIX = exports.__resetCachedDaemonIdForTest = exports.legacyDaemonUuids = exports.ensureMachineDaemonId = exports.__resetMachineUuidCacheForTest = exports.HOSTED_RUNTIME_MACHINE_SOURCES = exports.hostedRuntimeIdOverride = exports.getMachineUuid = exports.__getDeviceIdentityStateForTest = exports.__setDeviceIdentityStateForTest = exports.__enrollmentBackoffPathForTest = exports.__enrollmentMarkerPathForTest = exports.__privateKeyPathForTest = exports.__publicKeyPathForTest = exports.describeDeviceKeySplit = exports.describeDeviceIdentityState = exports.getDevicePublicKey = exports.isDeviceIdentityActive = exports.clearEnrollmentMarker = exports.enrollWithServer = exports.signServerRequest = exports.resetDeviceIdentity = exports.initDeviceIdentity = exports.__resetShutdownGuardForTest = exports.__getCredEnvelopeStateForTest = exports.__setCredEnvelopeStateForTest = exports.__wrappedDekFilePathForTest = exports.DEFAULT_UNREADABLE_CREDENTIAL_HINT = exports.maybeDecryptOnRead = exports.maybeEncryptForWrite = exports.splitKeyConvergencePolicy = exports.describeCredEnvelopeState = exports.hasCredEnvelopePathConflict = exports.isCredEnvelopeActive = exports.shutdownCredEnvelope = exports.resetCredEnvelope = exports.initCredEnvelope = exports.verifyDeviceProof = exports.tokenHash = void 0;
28
- exports.resolveChannelManifestUrl = exports.isFirstPartyHarnessChannel = exports.firstPartyHarnessFeedCandidates = exports.firstPartyHarnessFeedBase = exports.firstPartyHarnessChannelPrefix = exports.FIRST_PARTY_HARNESS_CHANNELS = exports.DEFAULT_FIRST_PARTY_HARNESS_CHANNEL = exports.migrateFirstPartyHarnessHome = exports.linkFirstPartyHarnessAliases = exports.firstPartyHarnessInstalledBinaryPath = exports.firstPartyHarnessHomeDir = exports.firstPartyHarnessBinDir = exports.FIRST_PARTY_HARNESS_PROVENANCE_SUFFIX = exports.FIRST_PARTY_HARNESS_PREVIOUS_SUFFIX = exports.describeLegacyState = exports.findLegacyLocalState = exports.DEFAULT_BINARY_NAME = exports.LEGACY_NATIVE_ID_PREFIXES = exports.NATIVE_ID_PREFIX = exports.LEGACY_CONFIG_DIR_NAMES = exports.CONFIG_DIR_NAME = exports.LOOPBACK_DEFAULT_MAX_BODY_BYTES = exports.LoopbackTargetRefusedError = exports.isLoopbackAddress = exports.isLoopbackHostname = exports.assertLoopbackHttpUrl = exports.loopbackFetch = exports.withLoopbackNoProxy = exports.envHasProxy = exports.LOOPBACK_NO_PROXY_HOSTS = exports.SENSITIVE_ENV_PREFIX_EXCEPTIONS = exports.SENSITIVE_ENV_NAME_TOKENS = exports.SENSITIVE_ENV_SUFFIXES = exports.SENSITIVE_ENV_PREFIXES = exports.SENSITIVE_ENV_VARS = exports.sanitizeSpawnEnv = exports.harnessLoadsClaudeSkillsLayout = exports.claudeSkillsLayoutEvidence = exports.HARNESSES_LOADING_CLAUDE_SKILLS_LAYOUT = exports.tierPermitsConfiguredAutoMode = exports.credentialPolicyForTier = exports.getHarnessTier = exports.HARNESS_TIERS = exports.pairUint8ArrayToBase64Url = exports.pairUint8ArrayToBase64 = exports.parsePairUrl = exports.parsePairPlaintext = exports.parsePairBundle = exports.openPairBundleBase64 = exports.generatePairKeyPair = void 0;
29
- exports.consolidateProfileState = exports.profileStateFilePathsToClear = exports.profileStateFileLocations = exports.resolveProfileStateFile = exports.resolveProfileStateDir = exports.legacyProfileStateDir = exports.profileStateDir = exports.SUPERSEDED_COPY_SUFFIX = exports.SUPERSEDED_MARKER_SUFFIX = exports.PROFILES_SEGMENT = exports.isConfigRootOverridden = exports.configRootPath = exports.resolveConfigRoot = exports.verifyManifest = exports.verifyArtifact = exports.isTrustedArtifactOrigin = exports.getDeltaFor = exports.buildManifestMessage = exports.buildArtifactMessage = exports.TRUSTED_FEED_ORIGINS = exports.MAX_SIGS = exports.OVERSKY_RELEASE_PUBLIC_KEYS = exports.resolveFirstPartyHarnessChannel = void 0;
27
+ exports.__resetCachedDaemonIdForTest = exports.legacyDaemonUuids = exports.ensureMachineDaemonId = exports.__resetMachineUuidCacheForTest = exports.HOSTED_RUNTIME_MACHINE_SOURCES = exports.hostedRuntimeIdOverride = exports.getMachineUuid = exports.__getDeviceIdentityStateForTest = exports.__setDeviceIdentityStateForTest = exports.__enrollmentBackoffPathForTest = exports.__enrollmentMarkerPathForTest = exports.__privateKeyPathForTest = exports.__publicKeyPathForTest = exports.describeDeviceKeySplit = exports.describeDeviceIdentityState = exports.getDevicePublicKey = exports.isDeviceIdentityActive = exports.clearEnrollmentMarker = exports.enrollWithServer = exports.signServerRequest = exports.resetDeviceIdentity = exports.initDeviceIdentity = exports.__resetShutdownGuardForTest = exports.__getCredEnvelopeStateForTest = exports.__setCredEnvelopeStateForTest = exports.__wrappedDekFilePathForTest = exports.DEFAULT_UNREADABLE_CREDENTIAL_HINT = exports.maybeDecryptOnRead = exports.maybeEncryptForWrite = exports.splitKeyConvergencePolicy = exports.describeCredEnvelopeState = exports.hasCredEnvelopePathConflict = exports.isCredEnvelopeActive = exports.shutdownCredEnvelope = exports.resetCredEnvelope = exports.initCredEnvelope = exports.verifyDpopProof = exports.normalizeDpopHtu = exports.isJwkThumbprint = exports.isAth = exports.createDpopKey = exports.accessTokenHash = exports.DPOP_PROOF_VERIFY_UNAVAILABLE = exports.DPOP_PROOF_TYP = exports.DPOP_PROOF_REQUIRED = exports.DPOP_PROOF_INVALID = exports.DPOP_MAX_AGE_SECONDS = exports.DPOP_HEADER = exports.verifyDeviceProof = exports.tokenHash = void 0;
28
+ exports.FIRST_PARTY_HARNESS_PROVENANCE_SUFFIX = exports.FIRST_PARTY_HARNESS_PREVIOUS_SUFFIX = exports.describeLegacyState = exports.findLegacyLocalState = exports.DEFAULT_BINARY_NAME = exports.LEGACY_NATIVE_ID_PREFIXES = exports.NATIVE_ID_PREFIX = exports.LEGACY_CONFIG_DIR_NAMES = exports.CONFIG_DIR_NAME = exports.LOOPBACK_DEFAULT_MAX_BODY_BYTES = exports.LoopbackTargetRefusedError = exports.isLoopbackAddress = exports.isLoopbackHostname = exports.assertLoopbackHttpUrl = exports.loopbackFetch = exports.withLoopbackNoProxy = exports.envHasProxy = exports.LOOPBACK_NO_PROXY_HOSTS = exports.SENSITIVE_ENV_PREFIX_EXCEPTIONS = exports.SENSITIVE_ENV_NAME_TOKENS = exports.SENSITIVE_ENV_SUFFIXES = exports.SENSITIVE_ENV_PREFIXES = exports.SENSITIVE_ENV_VARS = exports.sanitizeSpawnEnv = exports.harnessLoadsClaudeSkillsLayout = exports.claudeSkillsLayoutEvidence = exports.HARNESSES_LOADING_CLAUDE_SKILLS_LAYOUT = exports.tierPermitsConfiguredAutoMode = exports.credentialPolicyForTier = exports.getHarnessTier = exports.HARNESS_TIERS = exports.pairUint8ArrayToBase64Url = exports.pairUint8ArrayToBase64 = exports.parsePairUrl = exports.parsePairPlaintext = exports.parsePairBundle = exports.openPairBundleBase64 = exports.generatePairKeyPair = exports.buildPairUrl = exports.buildPairAad = exports.pairBase64UrlToUint8Array = exports.pairBase64ToUint8Array = exports.assemblePairBundleBase64 = exports.PairBundleError = exports.PAIR_SECRET_LEN = exports.PAIR_PUBKEY_LEN = exports.PAIR_NONCE_LEN = exports.PAIR_BUNDLE_MAX_BASE64_LEN = exports.PAIR_AAD_MAX_LEN = exports.PAIR_AAD_PREFIX = void 0;
29
+ exports.consolidateProfileState = exports.profileStateFilePathsToClear = exports.profileStateFileLocations = exports.resolveProfileStateFile = exports.resolveProfileStateDir = exports.legacyProfileStateDir = exports.profileStateDir = exports.SUPERSEDED_COPY_SUFFIX = exports.SUPERSEDED_MARKER_SUFFIX = exports.PROFILES_SEGMENT = exports.isConfigRootOverridden = exports.configRootPath = exports.resolveConfigRoot = exports.verifyManifest = exports.verifyArtifact = exports.isTrustedArtifactOrigin = exports.getDeltaFor = exports.buildManifestMessage = exports.buildArtifactMessage = exports.TRUSTED_FEED_ORIGINS = exports.MAX_SIGS = exports.OVERSKY_RELEASE_PUBLIC_KEYS = exports.resolveFirstPartyHarnessChannel = exports.resolveChannelManifestUrl = exports.isFirstPartyHarnessChannel = exports.firstPartyHarnessFeedCandidates = exports.firstPartyHarnessFeedBase = exports.firstPartyHarnessChannelPrefix = exports.FIRST_PARTY_HARNESS_CHANNELS = exports.DEFAULT_FIRST_PARTY_HARNESS_CHANNEL = exports.migrateFirstPartyHarnessHome = exports.linkFirstPartyHarnessAliases = exports.firstPartyHarnessInstalledBinaryPath = exports.firstPartyHarnessHomeDir = exports.firstPartyHarnessBinDir = void 0;
30
30
  // Daemon scope vocabulary — single source of truth for non-Mongoose tiers
31
31
  // (daemon, desktop, cli). Schema-bound canonical lives in
32
32
  // `@skrr-ai/data-schemas/common/daemonScopes`; the two are kept byte-equal
@@ -222,6 +222,22 @@ Object.defineProperty(exports, "normalizeHtu", { enumerable: true, get: function
222
222
  Object.defineProperty(exports, "publicJwkFromX", { enumerable: true, get: function () { return deviceKey_js_1.publicJwkFromX; } });
223
223
  Object.defineProperty(exports, "tokenHash", { enumerable: true, get: function () { return deviceKey_js_1.tokenHash; } });
224
224
  Object.defineProperty(exports, "verifyDeviceProof", { enumerable: true, get: function () { return deviceKey_js_1.verifyProof; } });
225
+ // OSK-12020 — RFC 9449 access-token binding (`cnf.jkt` + `DPoP` proof). A
226
+ // different protocol from the device proof above (`typ: dpop+jwt`, header
227
+ // `DPoP`), signed by a dedicated in-memory key the daemon holds.
228
+ var dpop_js_1 = require("./dpop.js");
229
+ Object.defineProperty(exports, "DPOP_HEADER", { enumerable: true, get: function () { return dpop_js_1.DPOP_HEADER; } });
230
+ Object.defineProperty(exports, "DPOP_MAX_AGE_SECONDS", { enumerable: true, get: function () { return dpop_js_1.DPOP_MAX_AGE_SECONDS; } });
231
+ Object.defineProperty(exports, "DPOP_PROOF_INVALID", { enumerable: true, get: function () { return dpop_js_1.DPOP_PROOF_INVALID; } });
232
+ Object.defineProperty(exports, "DPOP_PROOF_REQUIRED", { enumerable: true, get: function () { return dpop_js_1.DPOP_PROOF_REQUIRED; } });
233
+ Object.defineProperty(exports, "DPOP_PROOF_TYP", { enumerable: true, get: function () { return dpop_js_1.DPOP_PROOF_TYP; } });
234
+ Object.defineProperty(exports, "DPOP_PROOF_VERIFY_UNAVAILABLE", { enumerable: true, get: function () { return dpop_js_1.DPOP_PROOF_VERIFY_UNAVAILABLE; } });
235
+ Object.defineProperty(exports, "accessTokenHash", { enumerable: true, get: function () { return dpop_js_1.accessTokenHash; } });
236
+ Object.defineProperty(exports, "createDpopKey", { enumerable: true, get: function () { return dpop_js_1.createDpopKey; } });
237
+ Object.defineProperty(exports, "isAth", { enumerable: true, get: function () { return dpop_js_1.isAth; } });
238
+ Object.defineProperty(exports, "isJwkThumbprint", { enumerable: true, get: function () { return dpop_js_1.isJwkThumbprint; } });
239
+ Object.defineProperty(exports, "normalizeDpopHtu", { enumerable: true, get: function () { return dpop_js_1.normalizeDpopHtu; } });
240
+ Object.defineProperty(exports, "verifyDpopProof", { enumerable: true, get: function () { return dpop_js_1.verifyDpopProof; } });
225
241
  // L11/L12 — composed runtime: init, transforms, sign, enroll, locks.
226
242
  // Daemon and CLI consume these; the underlying primitives live above.
227
243
  var credentialEnvelopeBridge_js_1 = require("./credentialEnvelopeBridge.js");
@@ -22,7 +22,7 @@
22
22
  * - `access_token`: broker mode — a short-lived access token from a
23
23
  * daemon-owned family; nothing durable leaves the daemon.
24
24
  */
25
- export declare const CLI_HANDOFF_MODES: readonly ["refresh_family", "access_token"];
25
+ export declare const CLI_HANDOFF_MODES: readonly ["refresh_family", "access_token", "access_token_dpop"];
26
26
  export type CliHandoffMode = (typeof CLI_HANDOFF_MODES)[number];
27
27
  /** Broker-mode redeem route on the daemon's loopback server. */
28
28
  export declare const CLI_HANDOFF_TOKEN_PATH = "/v1/auth/cli-handoff-token";
@@ -74,10 +74,26 @@ export declare function normalizeHandoffModes(value: unknown): CliHandoffMode[];
74
74
  */
75
75
  export declare function advertisedHandoffModes(d: CliHandoffDescriptor): CliHandoffMode[];
76
76
  export declare function descriptorOffersAccessToken(d: CliHandoffDescriptor): boolean;
77
+ /** True when the token route can serve DPoP-bound tokens (OSK-12020). */
78
+ export declare function descriptorOffersDpop(d: CliHandoffDescriptor): boolean;
77
79
  export interface CliHandoffTokenRequest {
78
80
  /** Bypass the daemon broker's cached token (the 401-recovery path). */
79
81
  forceRefresh?: boolean;
82
+ /**
83
+ * The caller can fetch per-request proofs from `CLI_HANDOFF_DPOP_PROOF_PATH`
84
+ * and wants a DPoP-bound token. Sent only to a descriptor that advertises
85
+ * `access_token_dpop`; a daemon that does not know the field ignores it and
86
+ * answers an unbound token, which `tokenType` then says.
87
+ */
88
+ dpop?: boolean;
80
89
  }
90
+ /**
91
+ * How the token must be presented. `DPoP` means the token carries `cnf.jkt`
92
+ * and every request needs a fresh proof; absent or `Bearer` means an ordinary
93
+ * bearer token. Read from the RESPONSE, never assumed from the request: an
94
+ * older server ignores the binding request and mints an unbound token.
95
+ */
96
+ export type CliHandoffTokenType = 'Bearer' | 'DPoP';
81
97
  export interface CliHandoffTokenResponse {
82
98
  accessToken: string;
83
99
  /** Absolute expiry in ms since epoch, when the daemon knows it. */
@@ -85,6 +101,31 @@ export interface CliHandoffTokenResponse {
85
101
  /** Server the minted credential belongs to — lets the caller verify it is
86
102
  * about to use a token for the API it thinks it is talking to. */
87
103
  serverUrl?: string;
104
+ tokenType?: CliHandoffTokenType;
88
105
  }
89
106
  /** Parse the redeem response; null when the token itself is absent. */
90
107
  export declare function parseCliHandoffTokenResponse(value: unknown): CliHandoffTokenResponse | null;
108
+ /** The daemon refuses an UNBOUND token because its posture requires binding. */
109
+ export declare const CLI_HANDOFF_ERROR_DPOP_REQUIRED = "HANDOFF_DPOP_REQUIRED";
110
+ /**
111
+ * The daemon signs RFC 9449 proofs for a bound token with a key that never
112
+ * leaves it. Same descriptor secret as the token route: using a stolen bound
113
+ * token therefore needs live loopback access to THIS daemon, which is the
114
+ * boundary the capability already has.
115
+ */
116
+ export declare const CLI_HANDOFF_DPOP_PROOF_PATH = "/v1/auth/cli-handoff-dpop-proof";
117
+ /** The oracle refused to sign (bad htm/htu, or `ath` names no token it issued). */
118
+ export declare const CLI_HANDOFF_ERROR_DPOP_PROOF_REFUSED = "HANDOFF_DPOP_PROOF_REFUSED";
119
+ /** The daemon holds no DPoP key (binding is off on this daemon). */
120
+ export declare const CLI_HANDOFF_ERROR_DPOP_UNAVAILABLE = "HANDOFF_DPOP_UNAVAILABLE";
121
+ export interface CliHandoffDpopProofRequest {
122
+ htm: string;
123
+ htu: string;
124
+ /** base64url SHA-256 of the bound access token. The token itself is never
125
+ * sent: the oracle commits to a hash, and only to one it issued. */
126
+ ath: string;
127
+ }
128
+ export interface CliHandoffDpopProofResponse {
129
+ proof: string;
130
+ }
131
+ export declare function parseCliHandoffDpopProofResponse(value: unknown): CliHandoffDpopProofResponse | null;
@@ -22,7 +22,7 @@
22
22
  * - `access_token`: broker mode — a short-lived access token from a
23
23
  * daemon-owned family; nothing durable leaves the daemon.
24
24
  */
25
- export const CLI_HANDOFF_MODES = ['refresh_family', 'access_token'];
25
+ export const CLI_HANDOFF_MODES = ['refresh_family', 'access_token', 'access_token_dpop'];
26
26
  /** Broker-mode redeem route on the daemon's loopback server. */
27
27
  export const CLI_HANDOFF_TOKEN_PATH = '/v1/auth/cli-handoff-token';
28
28
  /** Error codes this contract emits. String literals so both ends compare
@@ -88,7 +88,12 @@ export function advertisedHandoffModes(d) {
88
88
  return declared.length > 0 ? declared : ['refresh_family'];
89
89
  }
90
90
  export function descriptorOffersAccessToken(d) {
91
- return advertisedHandoffModes(d).includes('access_token');
91
+ const modes = advertisedHandoffModes(d);
92
+ return modes.includes('access_token') || modes.includes('access_token_dpop');
93
+ }
94
+ /** True when the token route can serve DPoP-bound tokens (OSK-12020). */
95
+ export function descriptorOffersDpop(d) {
96
+ return advertisedHandoffModes(d).includes('access_token_dpop');
92
97
  }
93
98
  /** Parse the redeem response; null when the token itself is absent. */
94
99
  export function parseCliHandoffTokenResponse(value) {
@@ -101,5 +106,30 @@ export function parseCliHandoffTokenResponse(value) {
101
106
  accessToken: v.accessToken,
102
107
  ...(typeof v.accessExpiresAt === 'number' ? { accessExpiresAt: v.accessExpiresAt } : {}),
103
108
  ...(typeof v.serverUrl === 'string' ? { serverUrl: v.serverUrl } : {}),
109
+ ...(v.tokenType === 'DPoP' || v.tokenType === 'Bearer' ? { tokenType: v.tokenType } : {}),
104
110
  };
105
111
  }
112
+ /** The daemon refuses an UNBOUND token because its posture requires binding. */
113
+ export const CLI_HANDOFF_ERROR_DPOP_REQUIRED = 'HANDOFF_DPOP_REQUIRED';
114
+ // ---------------------------------------------------------------------
115
+ // Proof oracle — POST CLI_HANDOFF_DPOP_PROOF_PATH (OSK-12020)
116
+ // ---------------------------------------------------------------------
117
+ /**
118
+ * The daemon signs RFC 9449 proofs for a bound token with a key that never
119
+ * leaves it. Same descriptor secret as the token route: using a stolen bound
120
+ * token therefore needs live loopback access to THIS daemon, which is the
121
+ * boundary the capability already has.
122
+ */
123
+ export const CLI_HANDOFF_DPOP_PROOF_PATH = '/v1/auth/cli-handoff-dpop-proof';
124
+ /** The oracle refused to sign (bad htm/htu, or `ath` names no token it issued). */
125
+ export const CLI_HANDOFF_ERROR_DPOP_PROOF_REFUSED = 'HANDOFF_DPOP_PROOF_REFUSED';
126
+ /** The daemon holds no DPoP key (binding is off on this daemon). */
127
+ export const CLI_HANDOFF_ERROR_DPOP_UNAVAILABLE = 'HANDOFF_DPOP_UNAVAILABLE';
128
+ export function parseCliHandoffDpopProofResponse(value) {
129
+ if (value == null || typeof value !== 'object')
130
+ return null;
131
+ const v = value;
132
+ if (typeof v.proof !== 'string' || v.proof.split('.').length !== 3)
133
+ return null;
134
+ return { proof: v.proof };
135
+ }
@@ -13,6 +13,20 @@
13
13
  * Deliberately thin: no persistence, no retry policy, no logging. Callers
14
14
  * own their store and their error surfaces; this owns the cache/single-
15
15
  * flight/invalidate invariants so they cannot drift between surfaces.
16
+ *
17
+ * Two policies are options because mechanisms genuinely need different ones,
18
+ * and both default to the original behaviour:
19
+ *
20
+ * - `forcedAcquire: 'join'` — a forced acquire joins whatever is in flight,
21
+ * for a mechanism where a second concurrent renewal is itself the hazard
22
+ * (a refresh-family rotation or a family mint);
23
+ * - `classifyAcquireError` — stale-on-degrade: a TRANSIENT failure serves the
24
+ * still-unexpired cached credential instead of failing, a PERMANENT one
25
+ * drops it.
26
+ *
27
+ * Mechanism-specific limits — how often a new family may be minted, which
28
+ * failures retire it — stay in the mechanism. The daemon's task token broker
29
+ * (`daemon/src/task/token-broker.ts`) is the consumer that uses both options.
16
30
  */
17
31
  /** What an acquire returns. `expiresAtMs` absent means "no known expiry" —
18
32
  * the token is served until `invalidate()` or an acquire replaces it. */
@@ -26,13 +40,45 @@ export interface CredentialSessionOptions {
26
40
  * The mechanism. Called with `forceRefresh: true` when the caller asked to
27
41
  * bypass the cache (the 401-recovery path) — implementations should renew
28
42
  * rather than serve their own cache. A rejected promise propagates to every
29
- * waiter and is never cached.
43
+ * waiter and is never cached (`classifyAcquireError` is the one way a waiter
44
+ * can be served the previous credential instead).
30
45
  */
31
46
  acquire: (forceRefresh: boolean) => Promise<AcquiredCredential>;
32
47
  /** Serve the cached token until this many ms before expiry. Default 30s. */
33
48
  skewMs?: number;
34
49
  /** Injectable clock for tests. */
35
50
  now?: () => number;
51
+ /**
52
+ * What a forced acquire does when an acquire is already in flight.
53
+ *
54
+ * - `'supersede'` (default): a forced acquire never joins a NON-forced
55
+ * in-flight one — that could serve the very credential a 401 just
56
+ * invalidated — so it starts a second operation, and the superseded one
57
+ * cannot write its result back. Right for a mechanism whose plain
58
+ * acquire may serve its own cache.
59
+ * - `'join'`: every acquire, forced or not, joins the one in flight. Right
60
+ * — and required — for a mechanism whose acquire ALWAYS renews (it never
61
+ * serves a cache of its own), and for which a second concurrent renewal
62
+ * is itself the hazard: a rotation that burns a refresh family, a mint
63
+ * that creates a new one. Whatever is in flight was started after the
64
+ * credential being replaced was issued, so its result is not that
65
+ * credential.
66
+ */
67
+ forcedAcquire?: 'supersede' | 'join';
68
+ /**
69
+ * Classify an acquire failure. Without it every failure propagates and the
70
+ * cache is left as it was (the default).
71
+ *
72
+ * - `'transient'` — the renewal failed but the cached credential is still
73
+ * good: a waiter is served the cached token while it is inside its HARD
74
+ * expiry (the skew window only says when to start renewing), instead of
75
+ * the error. Nothing stale is served after `invalidate()`, after a forced
76
+ * acquire discarded it, or once it has actually expired.
77
+ * - `'permanent'` — the credential is dead upstream: the cache is dropped
78
+ * and the error propagates.
79
+ * - `undefined` — not classified: the default behaviour.
80
+ */
81
+ classifyAcquireError?: (err: unknown) => 'transient' | 'permanent' | undefined;
36
82
  }
37
83
  export interface CredentialSession {
38
84
  /**
@@ -41,6 +87,8 @@ export interface CredentialSession {
41
87
  * discards the cache first (use after a resource 401).
42
88
  */
43
89
  getToken(forceRefresh?: boolean): Promise<string>;
90
+ /** Same as getToken, but resolves the whole credential (with its expiry). */
91
+ getCredential(forceRefresh?: boolean): Promise<AcquiredCredential>;
44
92
  /** Drop the cached token; the next getToken() acquires. */
45
93
  invalidate(): void;
46
94
  }
@@ -13,11 +13,27 @@
13
13
  * Deliberately thin: no persistence, no retry policy, no logging. Callers
14
14
  * own their store and their error surfaces; this owns the cache/single-
15
15
  * flight/invalidate invariants so they cannot drift between surfaces.
16
+ *
17
+ * Two policies are options because mechanisms genuinely need different ones,
18
+ * and both default to the original behaviour:
19
+ *
20
+ * - `forcedAcquire: 'join'` — a forced acquire joins whatever is in flight,
21
+ * for a mechanism where a second concurrent renewal is itself the hazard
22
+ * (a refresh-family rotation or a family mint);
23
+ * - `classifyAcquireError` — stale-on-degrade: a TRANSIENT failure serves the
24
+ * still-unexpired cached credential instead of failing, a PERMANENT one
25
+ * drops it.
26
+ *
27
+ * Mechanism-specific limits — how often a new family may be minted, which
28
+ * failures retire it — stay in the mechanism. The daemon's task token broker
29
+ * (`daemon/src/task/token-broker.ts`) is the consumer that uses both options.
16
30
  */
17
31
  const DEFAULT_SKEW_MS = 30_000;
18
32
  export function createCredentialSession(opts) {
19
33
  const skewMs = opts.skewMs ?? DEFAULT_SKEW_MS;
20
34
  const now = opts.now ?? Date.now;
35
+ const forcedJoins = opts.forcedAcquire === 'join';
36
+ const classify = opts.classifyAcquireError;
21
37
  let cached = null;
22
38
  let inFlight = null;
23
39
  let inFlightForced = false;
@@ -26,17 +42,26 @@ export function createCredentialSession(opts) {
26
42
  // result back over the newer one.
27
43
  let generation = 0;
28
44
  const fresh = (t) => t.expiresAtMs == null || now() < t.expiresAtMs - skewMs;
45
+ /** Not yet actually expired — the bar for serving a stale credential. */
46
+ const unexpired = (t) => t.expiresAtMs == null || now() < t.expiresAtMs;
29
47
  const acquireShared = (force) => {
30
- // A forced acquire must not join a non-forced in-flight one — that would
31
- // serve the very credential a 401 just invalidated. A forced in-flight
32
- // DOES satisfy non-forced waiters: it is already renewing.
33
- if (inFlight && (inFlightForced || !force))
48
+ // Under 'supersede', a forced acquire must not join a non-forced in-flight
49
+ // one — that would serve the very credential a 401 just invalidated. A
50
+ // forced in-flight DOES satisfy non-forced waiters: it is already renewing.
51
+ // Under 'join', everything joins (see `forcedAcquire`).
52
+ if (inFlight && (forcedJoins || inFlightForced || !force))
34
53
  return inFlight;
35
54
  const gen = ++generation;
36
55
  const p = opts.acquire(force).then((t) => {
37
56
  if (gen === generation)
38
57
  cached = t;
39
58
  return t;
59
+ }, (err) => {
60
+ // Settled before any waiter resumes, so a waiter's stale check below
61
+ // already sees a permanent failure's dropped cache.
62
+ if (gen === generation && classify?.(err) === 'permanent')
63
+ cached = null;
64
+ throw err;
40
65
  });
41
66
  inFlight = p;
42
67
  inFlightForced = force;
@@ -51,13 +76,26 @@ export function createCredentialSession(opts) {
51
76
  p.then(cleanup, cleanup);
52
77
  return p;
53
78
  };
79
+ const getCredential = async (forceRefresh = false) => {
80
+ if (forceRefresh)
81
+ cached = null;
82
+ if (cached && fresh(cached))
83
+ return cached;
84
+ try {
85
+ return await acquireShared(forceRefresh);
86
+ }
87
+ catch (err) {
88
+ // Stale-on-degrade: read `cached` AFTER the failure, so an invalidate()
89
+ // or a forced discard that happened meanwhile is honoured.
90
+ if (classify?.(err) === 'transient' && cached && unexpired(cached))
91
+ return cached;
92
+ throw err;
93
+ }
94
+ };
54
95
  return {
96
+ getCredential,
55
97
  async getToken(forceRefresh = false) {
56
- if (forceRefresh)
57
- cached = null;
58
- if (cached && fresh(cached))
59
- return cached.accessToken;
60
- return (await acquireShared(forceRefresh)).accessToken;
98
+ return (await getCredential(forceRefresh)).accessToken;
61
99
  },
62
100
  invalidate() {
63
101
  cached = null;
@@ -1,3 +1,40 @@
1
+ /**
2
+ * deviceKey.ts — L11 Phase 1: Ed25519 device identity + DPoP-style proofs.
3
+ *
4
+ * The load-bearing recommendation in `docs/daemon-auth-cc-deep-comparison-
5
+ * 2026-04-24.md` §L11. Two-axis identity:
6
+ *
7
+ * user identity = OAuth refresh token (server-rotated, scope-pinned, reuse-detected)
8
+ * device identity = Ed25519 keypair (device-generated, server-revocable)
9
+ *
10
+ * Every daemon→server request carries a JWS signature over
11
+ * `{htm, htu, iat, jti, rth?, ath?}` using the device key. Server validates
12
+ * against the public key registered for this daemon.
13
+ *
14
+ * Stolen credentials require BOTH halves:
15
+ * - refresh token alone is useless without the device key
16
+ * - device key alone is useless without the refresh token
17
+ *
18
+ * Why DPoP-shaped (RFC 9449) rather than rolling our own JWS:
19
+ * - The htm/htu/iat/jti/ath claim set is well-studied. Server-side
20
+ * replay defenses, clock-skew handling, and audit-trail formats all
21
+ * have a body of prior art to copy from.
22
+ * - Future interop: if we ever expose OverSky as a third-party OAuth
23
+ * resource server, DPoP-bearer is the way clients will already
24
+ * understand.
25
+ *
26
+ * Why we extend with `rth` (refresh-token-hash):
27
+ * - RFC 9449 only mints `ath` (access-token-hash). The whole point of
28
+ * L11 is to bind the *refresh* token to the device, so the proof
29
+ * accompanying a refresh request must commit to the refresh token.
30
+ * `rth` is structurally identical to `ath`; the name disambiguates.
31
+ *
32
+ * What this module is NOT responsible for:
33
+ * - Persistence (lives in `daemon/src/deviceIdentity.ts`).
34
+ * - Server-side public-key registration (separate API in a later PR).
35
+ * - Wire-up to the daemon's outgoing HTTP path (Phase 2 of L11).
36
+ */
37
+ import crypto from 'node:crypto';
1
38
  /**
2
39
  * Ed25519 JSON Web Key — RFC 8037 §2 ("Key Type 'OKP'").
3
40
  *
@@ -123,6 +160,18 @@ export interface BuildProofOptions {
123
160
  * not a silent fallback.
124
161
  */
125
162
  export declare function buildProof(privateJwk: Ed25519PrivateJwk, publicJwk: Ed25519PublicJwk, opts: BuildProofOptions): string;
163
+ /** The header `typ` of an OverSky device-identity proof. */
164
+ export declare const DEVICE_PROOF_TYP = "oversky-dpop+jwt";
165
+ /**
166
+ * Sign a DPoP-shaped proof with an Ed25519 key under the given header `typ`.
167
+ *
168
+ * @internal Shared by the device-identity proof (`oversky-dpop+jwt`, above)
169
+ * and the RFC 9449 access-token proof (`dpop+jwt`, `dpop.ts`). `typ` is the
170
+ * only thing on the wire that separates the two protocols, which is why it is
171
+ * a required argument rather than a default: a proof signed for one must
172
+ * never verify as the other.
173
+ */
174
+ export declare function signEd25519Proof(privateKey: crypto.KeyObject, publicJwk: Ed25519PublicJwk, typ: string, opts: BuildProofOptions): string;
126
175
  export type VerifyFailureReason = 'malformed' | 'bad_alg' | 'bad_typ' | 'bad_jwk' | 'sig_invalid' | 'iat_old' | 'iat_future' | 'htm_mismatch' | 'htu_mismatch' | 'rth_mismatch' | 'ath_mismatch' | 'pin_mismatch';
127
176
  export interface VerifySuccess {
128
177
  valid: true;
@@ -165,3 +214,10 @@ export interface VerifyOptions {
165
214
  * `sig_invalid` to keep the failure surface narrow.
166
215
  */
167
216
  export declare function verifyProof(jws: string, opts?: VerifyOptions): VerifySuccess | VerifyFailure;
217
+ /**
218
+ * Verify a DPoP-shaped Ed25519 proof whose header `typ` must equal `typ`.
219
+ *
220
+ * @internal See `signEd25519Proof`. `verifyProof` (device identity) and
221
+ * `verifyDpopProof` (`dpop.ts`, RFC 9449) are the two public doors.
222
+ */
223
+ export declare function verifyEd25519Proof(jws: string, opts: VerifyOptions, typ: string): VerifySuccess | VerifyFailure;