@sjawhar/codex-envoy 5.0.0 → 5.1.1
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/.codex-plugin/plugin.json +2 -1
- package/dist/THIRD_PARTY_NOTICES +30 -0
- package/dist/codex-hook.js +2114 -363
- package/dist/dispatch.js +10024 -8151
- package/dist/envoy-channel.js +2110 -361
- package/dist/session-hook.js +2100 -349
- package/package.json +1 -1
package/dist/session-hook.js
CHANGED
|
@@ -981,7 +981,7 @@ __export(exports_coerce, {
|
|
|
981
981
|
|
|
982
982
|
// hooks/session-hook.ts
|
|
983
983
|
import { appendFileSync, mkdirSync as mkdirSync2, readFileSync as readFileSync6, rmSync as rmSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
984
|
-
import { join as
|
|
984
|
+
import { join as join10 } from "path";
|
|
985
985
|
|
|
986
986
|
// ../contracts/src/held-secrets.ts
|
|
987
987
|
var WITHHELD = "<withheld>";
|
|
@@ -17815,6 +17815,8 @@ function commandsHelp() {
|
|
|
17815
17815
|
}),
|
|
17816
17816
|
"",
|
|
17817
17817
|
"Run dispatch <command> --help for its flags and an example; --dry-run checks a command's arguments as the call would and prints them as given, sending nothing, except that dispatch result's dry run of a record also prints the pull-request body line Dispatch would write for it, recording nothing.",
|
|
17818
|
+
"",
|
|
17819
|
+
"dispatch login --device logs a machine with no identity of its own, such as a laptop, in at the secrets broker, once per machine; it is no Dispatch call, and needs no host or session (dispatch login --help).",
|
|
17818
17820
|
""
|
|
17819
17821
|
].join(`
|
|
17820
17822
|
`);
|
|
@@ -18613,6 +18615,15 @@ var SUBJECT_TOKEN_TYPE_GOOGLE = "urn:envoy:params:oauth:token-type:google-identi
|
|
|
18613
18615
|
var SUBJECT_TOKEN_TYPE_PERSON = "urn:envoy:params:oauth:token-type:person-google-identity";
|
|
18614
18616
|
var ACTOR_TOKEN_TYPE_MACHINE = "urn:envoy:params:oauth:token-type:machine-google-identity";
|
|
18615
18617
|
var TOKEN_TYPE_DPOP = "DPoP";
|
|
18618
|
+
var SUBJECT_TYPE_ACCESS = "urn:ietf:params:oauth:token-type:access_token";
|
|
18619
|
+
var DEVICE_AUTHORIZATION_PATH = "/v1/oauth/device_authorization";
|
|
18620
|
+
var GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code";
|
|
18621
|
+
var GRANT_TYPE_REFRESH = "refresh_token";
|
|
18622
|
+
var MACHINE_LOGIN_CLIENT_ID = "agent-secrets-helper";
|
|
18623
|
+
var MACHINE_LOGIN_SCOPE = "machine";
|
|
18624
|
+
var REQUEST_OBJECT_TYPE = "agent-secrets-request+jwt";
|
|
18625
|
+
var LAUNCHER_CREDENTIAL_DETAIL = "launcher_credential";
|
|
18626
|
+
var REQUEST_OBJECT_LIFETIME_SECONDS = 600;
|
|
18616
18627
|
var POD_SESSION_NOT_REGISTERED = "pod_session_not_registered";
|
|
18617
18628
|
var SESSION_NAME_NOT_THIS_REGISTRARS = "session_name_not_this_registrars";
|
|
18618
18629
|
|
|
@@ -18945,6 +18956,8 @@ var INVALID_DPOP_PROOF = "invalid_dpop_proof";
|
|
|
18945
18956
|
var USE_DPOP_NONCE = "use_dpop_nonce";
|
|
18946
18957
|
var INVALID_GRANT = "invalid_grant";
|
|
18947
18958
|
var MEMBERSHIP_HELD = "membership_held";
|
|
18959
|
+
var TOKEN_NOT_VALID = "Token is not valid or has expired.";
|
|
18960
|
+
var MACHINE_LOGIN_ENDED = "The machine login the subject token belongs to has ended.";
|
|
18948
18961
|
|
|
18949
18962
|
class BrokerRefusedError extends Error {
|
|
18950
18963
|
status;
|
|
@@ -18952,6 +18965,7 @@ class BrokerRefusedError extends Error {
|
|
|
18952
18965
|
code;
|
|
18953
18966
|
shownCode;
|
|
18954
18967
|
podSessionUnregistered;
|
|
18968
|
+
subjectNotHonoured;
|
|
18955
18969
|
constructor(status, code, description, refused, context = {}) {
|
|
18956
18970
|
const shownCode = shownOAuthCode(code);
|
|
18957
18971
|
const said = description === "" ? "" : isKnownBrokerRefusal(description, context) ? scrub(description) : REFUSAL_TEXT_WITHHELD;
|
|
@@ -18962,6 +18976,7 @@ class BrokerRefusedError extends Error {
|
|
|
18962
18976
|
this.shownCode = shownCode;
|
|
18963
18977
|
this.said = said;
|
|
18964
18978
|
this.podSessionUnregistered = code === INVALID_GRANT && description.startsWith(`${POD_SESSION_NOT_REGISTERED}:`);
|
|
18979
|
+
this.subjectNotHonoured = status === 400 && (code === "invalid_request" && description.endsWith(TOKEN_NOT_VALID) || code === INVALID_GRANT && description.endsWith(MACHINE_LOGIN_ENDED));
|
|
18965
18980
|
}
|
|
18966
18981
|
get permanent() {
|
|
18967
18982
|
return this.status !== TOO_MANY_REQUESTS && this.code !== INVALID_DPOP_PROOF && this.code !== USE_DPOP_NONCE && this.code !== MEMBERSHIP_HELD && !this.podSessionUnregistered;
|
|
@@ -19015,8 +19030,23 @@ class SignInEndedError extends Error {
|
|
|
19015
19030
|
this.name = "SignInEndedError";
|
|
19016
19031
|
}
|
|
19017
19032
|
}
|
|
19033
|
+
var DEVICE_LOGIN_COMMAND = "dispatch login --device";
|
|
19034
|
+
|
|
19035
|
+
class DeviceLoginEndedError extends Error {
|
|
19036
|
+
constructor(login) {
|
|
19037
|
+
super(`the secrets broker no longer honours ${login}: it was revoked or ran out; run: ${DEVICE_LOGIN_COMMAND}`);
|
|
19038
|
+
this.name = "DeviceLoginEndedError";
|
|
19039
|
+
}
|
|
19040
|
+
}
|
|
19041
|
+
|
|
19042
|
+
class LockHeldError extends Error {
|
|
19043
|
+
constructor(lock, options) {
|
|
19044
|
+
super(`another process of this machine held ${lock} for all of this trade's time, so nothing was sent to the secrets broker`, options);
|
|
19045
|
+
this.name = "LockHeldError";
|
|
19046
|
+
}
|
|
19047
|
+
}
|
|
19018
19048
|
function isFinalRefusal(error) {
|
|
19019
|
-
return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError;
|
|
19049
|
+
return error instanceof BrokerRefusedError && error.permanent || error instanceof SignInEndedError || error instanceof DeviceLoginEndedError;
|
|
19020
19050
|
}
|
|
19021
19051
|
|
|
19022
19052
|
// ../envoy-client/src/envoy-config.ts
|
|
@@ -26952,249 +26982,808 @@ function readDispatchFirstContext(skillFile) {
|
|
|
26952
26982
|
`);
|
|
26953
26983
|
}
|
|
26954
26984
|
|
|
26955
|
-
// ../cipher-client/src/
|
|
26956
|
-
import {
|
|
26957
|
-
|
|
26958
|
-
|
|
26959
|
-
|
|
26960
|
-
|
|
26961
|
-
|
|
26962
|
-
|
|
26963
|
-
|
|
26964
|
-
|
|
26965
|
-
|
|
26966
|
-
|
|
26967
|
-
|
|
26968
|
-
|
|
26969
|
-
|
|
26970
|
-
|
|
26971
|
-
return
|
|
26985
|
+
// ../cipher-client/src/device-login.ts
|
|
26986
|
+
import { generateKeyPairSync as generateKeyPairSync2, randomUUID as randomUUID5 } from "crypto";
|
|
26987
|
+
|
|
26988
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/buffer_utils.js
|
|
26989
|
+
var encoder2 = new TextEncoder;
|
|
26990
|
+
var decoder = new TextDecoder;
|
|
26991
|
+
var strictDecoder = new TextDecoder("utf-8", { fatal: true });
|
|
26992
|
+
var MAX_INT32 = 2 ** 32;
|
|
26993
|
+
function concat(...buffers) {
|
|
26994
|
+
const size = buffers.reduce((acc, { length }) => acc + length, 0);
|
|
26995
|
+
const buf = new Uint8Array(size);
|
|
26996
|
+
let i = 0;
|
|
26997
|
+
for (const buffer of buffers) {
|
|
26998
|
+
buf.set(buffer, i);
|
|
26999
|
+
i += buffer.length;
|
|
27000
|
+
}
|
|
27001
|
+
return buf;
|
|
27002
|
+
}
|
|
27003
|
+
function encode4(string) {
|
|
27004
|
+
const bytes = new Uint8Array(string.length);
|
|
27005
|
+
for (let i = 0;i < string.length; i++) {
|
|
27006
|
+
const code = string.charCodeAt(i);
|
|
27007
|
+
if (code > 127) {
|
|
27008
|
+
throw new TypeError("non-ASCII string encountered in encode()");
|
|
27009
|
+
}
|
|
27010
|
+
bytes[i] = code;
|
|
27011
|
+
}
|
|
27012
|
+
return bytes;
|
|
26972
27013
|
}
|
|
26973
|
-
|
|
26974
|
-
|
|
26975
|
-
|
|
26976
|
-
|
|
26977
|
-
|
|
26978
|
-
|
|
26979
|
-
|
|
26980
|
-
iat: Math.floor(Date.now() / 1000)
|
|
26981
|
-
};
|
|
26982
|
-
if (nonce !== undefined && nonce !== "")
|
|
26983
|
-
claims["nonce"] = nonce;
|
|
26984
|
-
if (accessToken !== undefined && accessToken !== "") {
|
|
26985
|
-
claims["ath"] = createHash("sha256").update(accessToken).digest("base64url");
|
|
26986
|
-
}
|
|
26987
|
-
const signingInput = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`;
|
|
26988
|
-
const signature = sign("sha256", Buffer.from(signingInput), {
|
|
26989
|
-
key: privateKey,
|
|
26990
|
-
dsaEncoding: "ieee-p1363"
|
|
26991
|
-
});
|
|
26992
|
-
return `${signingInput}.${signature.toString("base64url")}`;
|
|
26993
|
-
};
|
|
26994
|
-
return {
|
|
26995
|
-
publicJwk,
|
|
26996
|
-
async proof(request) {
|
|
26997
|
-
return signed(request.method.toUpperCase(), targetUri(request.url), request.nonce, request.accessToken);
|
|
26998
|
-
},
|
|
26999
|
-
connectionProof({ accessToken, nonce }) {
|
|
27000
|
-
if (accessToken === "")
|
|
27001
|
-
throw new Error("no access token to prove a NATS connection for");
|
|
27002
|
-
if (nonce === "")
|
|
27003
|
-
throw new Error("the NATS server sent no nonce to sign");
|
|
27004
|
-
return signed(CONNECTION_PROOF_METHOD, CONNECTION_PROOF_TARGET, nonce, accessToken);
|
|
27005
|
-
}
|
|
27006
|
-
};
|
|
27014
|
+
|
|
27015
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/crypto_key.js
|
|
27016
|
+
var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
27017
|
+
function checkUsage(key, usage) {
|
|
27018
|
+
if (usage && !key.usages.includes(usage)) {
|
|
27019
|
+
throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
27020
|
+
}
|
|
27007
27021
|
}
|
|
27008
|
-
function
|
|
27009
|
-
const {
|
|
27010
|
-
if (
|
|
27011
|
-
throw new
|
|
27022
|
+
function checkModulusLength(alg, key) {
|
|
27023
|
+
const { modulusLength } = key.algorithm;
|
|
27024
|
+
if (typeof modulusLength !== "number" || modulusLength < 2048) {
|
|
27025
|
+
throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
27012
27026
|
}
|
|
27013
|
-
return { kty, crv, x, y };
|
|
27014
27027
|
}
|
|
27015
|
-
|
|
27016
|
-
const
|
|
27017
|
-
|
|
27028
|
+
function checkCryptoKey(key, expected, usage) {
|
|
27029
|
+
const algorithm = key.algorithm;
|
|
27030
|
+
if (algorithm.name !== expected.name) {
|
|
27031
|
+
throw unusable(expected.name);
|
|
27032
|
+
}
|
|
27033
|
+
if (expected.hash && algorithm.hash?.name !== expected.hash) {
|
|
27034
|
+
throw unusable(expected.hash, "algorithm.hash");
|
|
27035
|
+
}
|
|
27036
|
+
if (expected.namedCurve && algorithm.namedCurve !== expected.namedCurve) {
|
|
27037
|
+
throw unusable(expected.namedCurve, "algorithm.namedCurve");
|
|
27038
|
+
}
|
|
27039
|
+
if (expected.length !== undefined && algorithm.length !== expected.length) {
|
|
27040
|
+
throw unusable(expected.length, "algorithm.length");
|
|
27041
|
+
}
|
|
27042
|
+
checkUsage(key, usage);
|
|
27018
27043
|
}
|
|
27019
|
-
|
|
27020
|
-
|
|
27021
|
-
|
|
27022
|
-
|
|
27023
|
-
|
|
27024
|
-
|
|
27044
|
+
|
|
27045
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/invalid_key_input.js
|
|
27046
|
+
function message(msg, actual, ...types) {
|
|
27047
|
+
if (types.length > 2) {
|
|
27048
|
+
const last = types.pop();
|
|
27049
|
+
msg += `one of type ${types.join(", ")}, or ${last}.`;
|
|
27050
|
+
} else if (types.length === 2) {
|
|
27051
|
+
msg += `one of type ${types[0]} or ${types[1]}.`;
|
|
27052
|
+
} else {
|
|
27053
|
+
msg += `of type ${types[0]}.`;
|
|
27025
27054
|
}
|
|
27026
|
-
|
|
27055
|
+
if (actual == null) {
|
|
27056
|
+
msg += ` Received ${actual}`;
|
|
27057
|
+
} else if (typeof actual === "function" && actual.name) {
|
|
27058
|
+
msg += ` Received function ${actual.name}`;
|
|
27059
|
+
} else if (typeof actual === "object" && actual != null) {
|
|
27060
|
+
if (actual.constructor?.name) {
|
|
27061
|
+
msg += ` Received an instance of ${actual.constructor.name}`;
|
|
27062
|
+
}
|
|
27063
|
+
}
|
|
27064
|
+
return msg;
|
|
27027
27065
|
}
|
|
27066
|
+
var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
|
|
27067
|
+
var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
|
|
27028
27068
|
|
|
27029
|
-
//
|
|
27030
|
-
|
|
27031
|
-
|
|
27032
|
-
|
|
27033
|
-
|
|
27034
|
-
|
|
27035
|
-
|
|
27036
|
-
|
|
27037
|
-
|
|
27038
|
-
const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
|
|
27039
|
-
return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
|
|
27069
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/errors.js
|
|
27070
|
+
class JOSEError extends Error {
|
|
27071
|
+
static code = "ERR_JOSE_GENERIC";
|
|
27072
|
+
code = "ERR_JOSE_GENERIC";
|
|
27073
|
+
constructor(message, options) {
|
|
27074
|
+
super(message, options);
|
|
27075
|
+
this.name = this.constructor.name;
|
|
27076
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
27077
|
+
}
|
|
27040
27078
|
}
|
|
27041
|
-
|
|
27042
|
-
|
|
27079
|
+
class JOSENotSupported extends JOSEError {
|
|
27080
|
+
static code = "ERR_JOSE_NOT_SUPPORTED";
|
|
27081
|
+
code = "ERR_JOSE_NOT_SUPPORTED";
|
|
27043
27082
|
}
|
|
27044
|
-
|
|
27045
|
-
|
|
27046
|
-
|
|
27047
|
-
agent,
|
|
27048
|
-
method: "GET",
|
|
27049
|
-
headers: { "Metadata-Flavor": "Google" },
|
|
27050
|
-
timeout: TIMEOUT_MS,
|
|
27051
|
-
...signal === undefined ? {} : { signal },
|
|
27052
|
-
...lookup === undefined ? {} : { lookup }
|
|
27053
|
-
}, (answer) => {
|
|
27054
|
-
const chunks = [];
|
|
27055
|
-
let read = 0;
|
|
27056
|
-
answer.on("data", (chunk) => {
|
|
27057
|
-
read += chunk.length;
|
|
27058
|
-
if (read <= MAX_ANSWER_BYTES)
|
|
27059
|
-
chunks.push(chunk);
|
|
27060
|
-
});
|
|
27061
|
-
answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
|
|
27062
|
-
answer.on("error", reject);
|
|
27063
|
-
});
|
|
27064
|
-
call.on("timeout", () => call.destroy(Object.assign(new Error(`no answer within ${TIMEOUT_MS} ms`), { code: "ETIMEDOUT" })));
|
|
27065
|
-
call.on("error", reject);
|
|
27066
|
-
call.end();
|
|
27067
|
-
return promise;
|
|
27083
|
+
class JWSInvalid extends JOSEError {
|
|
27084
|
+
static code = "ERR_JWS_INVALID";
|
|
27085
|
+
code = "ERR_JWS_INVALID";
|
|
27068
27086
|
}
|
|
27069
|
-
|
|
27070
|
-
|
|
27071
|
-
|
|
27072
|
-
const url = tokenUrl(audience, env);
|
|
27073
|
-
const named = `the metadata server ${serverNamed(env)}`;
|
|
27074
|
-
let answer;
|
|
27075
|
-
try {
|
|
27076
|
-
answer = await get(url, signal, options.lookup);
|
|
27077
|
-
} catch (error) {
|
|
27078
|
-
throw new Error(`${named} could not be reached: ${errorClass(error)}`);
|
|
27079
|
-
}
|
|
27080
|
-
if (answer.status < 200 || answer.status > 299) {
|
|
27081
|
-
throw new Error(`${named} answered HTTP ${answer.status}`);
|
|
27082
|
-
}
|
|
27083
|
-
const token = answer.body.trim();
|
|
27084
|
-
if (token === "") {
|
|
27085
|
-
throw new Error(`${named} answered an empty identity token`);
|
|
27086
|
-
}
|
|
27087
|
-
return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
|
|
27088
|
-
},
|
|
27089
|
-
describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
|
|
27090
|
-
};
|
|
27087
|
+
class JWKInvalid extends JOSEError {
|
|
27088
|
+
static code = "ERR_JWK_INVALID";
|
|
27089
|
+
code = "ERR_JWK_INVALID";
|
|
27091
27090
|
}
|
|
27092
27091
|
|
|
27093
|
-
// ../../node_modules/.bun/
|
|
27094
|
-
var
|
|
27095
|
-
if (
|
|
27096
|
-
|
|
27097
|
-
const VERSION = "v3.8.8";
|
|
27098
|
-
USER_AGENT = `${NAME}/${VERSION}`;
|
|
27099
|
-
}
|
|
27100
|
-
function looseInstanceOf(input, expected) {
|
|
27101
|
-
if (input == null) {
|
|
27102
|
-
return false;
|
|
27103
|
-
}
|
|
27092
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/is_key_like.js
|
|
27093
|
+
var isCryptoKey = (key) => {
|
|
27094
|
+
if (key?.[Symbol.toStringTag] === "CryptoKey")
|
|
27095
|
+
return true;
|
|
27104
27096
|
try {
|
|
27105
|
-
return
|
|
27097
|
+
return key instanceof CryptoKey;
|
|
27106
27098
|
} catch {
|
|
27107
27099
|
return false;
|
|
27108
27100
|
}
|
|
27109
|
-
}
|
|
27110
|
-
var
|
|
27111
|
-
var
|
|
27112
|
-
|
|
27113
|
-
|
|
27114
|
-
|
|
27115
|
-
|
|
27116
|
-
|
|
27117
|
-
var allowInsecureRequests = Symbol();
|
|
27118
|
-
var clockSkew = Symbol();
|
|
27119
|
-
var clockTolerance = Symbol();
|
|
27120
|
-
var customFetch = Symbol();
|
|
27121
|
-
var modifyAssertion = Symbol();
|
|
27122
|
-
var jweDecrypt = Symbol();
|
|
27123
|
-
var jwksCache = Symbol();
|
|
27124
|
-
var encoder2 = new TextEncoder;
|
|
27125
|
-
var decoder = new TextDecoder;
|
|
27126
|
-
function buf(input) {
|
|
27127
|
-
if (typeof input === "string") {
|
|
27128
|
-
return encoder2.encode(input);
|
|
27101
|
+
};
|
|
27102
|
+
var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
|
|
27103
|
+
var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
|
|
27104
|
+
|
|
27105
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/base64.js
|
|
27106
|
+
function encodeBase64(input) {
|
|
27107
|
+
if (Uint8Array.prototype.toBase64) {
|
|
27108
|
+
return input.toBase64();
|
|
27129
27109
|
}
|
|
27130
|
-
return decoder.decode(input);
|
|
27131
|
-
}
|
|
27132
|
-
var encodeBase64Url;
|
|
27133
|
-
if (Uint8Array.prototype.toBase64) {
|
|
27134
|
-
encodeBase64Url = (input) => {
|
|
27135
|
-
if (input instanceof ArrayBuffer) {
|
|
27136
|
-
input = new Uint8Array(input);
|
|
27137
|
-
}
|
|
27138
|
-
return input.toBase64({ alphabet: "base64url", omitPadding: true });
|
|
27139
|
-
};
|
|
27140
|
-
} else {
|
|
27141
27110
|
const CHUNK_SIZE = 32768;
|
|
27142
|
-
|
|
27143
|
-
|
|
27144
|
-
|
|
27145
|
-
|
|
27146
|
-
|
|
27147
|
-
for (let i = 0;i < input.byteLength; i += CHUNK_SIZE) {
|
|
27148
|
-
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
27149
|
-
}
|
|
27150
|
-
return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
27151
|
-
};
|
|
27111
|
+
const arr = [];
|
|
27112
|
+
for (let i = 0;i < input.length; i += CHUNK_SIZE) {
|
|
27113
|
+
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
27114
|
+
}
|
|
27115
|
+
return btoa(arr.join(""));
|
|
27152
27116
|
}
|
|
27153
|
-
|
|
27154
|
-
if (Uint8Array.fromBase64) {
|
|
27155
|
-
|
|
27156
|
-
|
|
27157
|
-
|
|
27158
|
-
|
|
27159
|
-
|
|
27160
|
-
|
|
27161
|
-
}
|
|
27162
|
-
|
|
27163
|
-
|
|
27117
|
+
function decodeBase64(encoded) {
|
|
27118
|
+
if (Uint8Array.fromBase64) {
|
|
27119
|
+
return Uint8Array.fromBase64(encoded);
|
|
27120
|
+
}
|
|
27121
|
+
const binary = atob(encoded);
|
|
27122
|
+
const bytes = new Uint8Array(binary.length);
|
|
27123
|
+
for (let i = 0;i < binary.length; i++) {
|
|
27124
|
+
bytes[i] = binary.charCodeAt(i);
|
|
27125
|
+
}
|
|
27126
|
+
return bytes;
|
|
27127
|
+
}
|
|
27128
|
+
|
|
27129
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/util/base64url.js
|
|
27130
|
+
var invalid = "The input to be decoded is not correctly encoded.";
|
|
27131
|
+
function decode3(input) {
|
|
27132
|
+
if (Uint8Array.fromBase64) {
|
|
27164
27133
|
try {
|
|
27165
|
-
|
|
27166
|
-
|
|
27167
|
-
|
|
27168
|
-
bytes[i] = binary.charCodeAt(i);
|
|
27169
|
-
}
|
|
27170
|
-
return bytes;
|
|
27134
|
+
return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
|
|
27135
|
+
alphabet: "base64url"
|
|
27136
|
+
});
|
|
27171
27137
|
} catch (cause) {
|
|
27172
|
-
throw
|
|
27138
|
+
throw new TypeError(invalid, { cause });
|
|
27173
27139
|
}
|
|
27174
|
-
}
|
|
27140
|
+
}
|
|
27141
|
+
let encoded = input;
|
|
27142
|
+
if (encoded instanceof Uint8Array) {
|
|
27143
|
+
encoded = decoder.decode(encoded);
|
|
27144
|
+
}
|
|
27145
|
+
if (encoded.includes("+") || encoded.includes("/")) {
|
|
27146
|
+
throw new TypeError(invalid);
|
|
27147
|
+
}
|
|
27148
|
+
encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
27149
|
+
try {
|
|
27150
|
+
return decodeBase64(encoded);
|
|
27151
|
+
} catch {
|
|
27152
|
+
throw new TypeError(invalid);
|
|
27153
|
+
}
|
|
27175
27154
|
}
|
|
27176
|
-
function
|
|
27177
|
-
|
|
27178
|
-
|
|
27155
|
+
function encode5(input) {
|
|
27156
|
+
let unencoded = input;
|
|
27157
|
+
if (typeof unencoded === "string") {
|
|
27158
|
+
unencoded = encoder2.encode(unencoded);
|
|
27179
27159
|
}
|
|
27180
|
-
|
|
27160
|
+
if (Uint8Array.prototype.toBase64) {
|
|
27161
|
+
return unencoded.toBase64({ alphabet: "base64url", omitPadding: true });
|
|
27162
|
+
}
|
|
27163
|
+
return encodeBase64(unencoded).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
27181
27164
|
}
|
|
27182
27165
|
|
|
27183
|
-
|
|
27184
|
-
|
|
27185
|
-
|
|
27186
|
-
|
|
27187
|
-
|
|
27188
|
-
|
|
27189
|
-
|
|
27166
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/type_checks.js
|
|
27167
|
+
function isObject3(input) {
|
|
27168
|
+
if (typeof input !== "object" || input === null || Object.prototype.toString.call(input) !== "[object Object]") {
|
|
27169
|
+
return false;
|
|
27170
|
+
}
|
|
27171
|
+
const prototype = Object.getPrototypeOf(input);
|
|
27172
|
+
if (prototype === null) {
|
|
27173
|
+
return true;
|
|
27174
|
+
}
|
|
27175
|
+
let proto = prototype;
|
|
27176
|
+
while (Object.getPrototypeOf(proto) !== null) {
|
|
27177
|
+
proto = Object.getPrototypeOf(proto);
|
|
27190
27178
|
}
|
|
27179
|
+
return prototype === proto;
|
|
27191
27180
|
}
|
|
27192
|
-
|
|
27193
|
-
|
|
27194
|
-
|
|
27195
|
-
|
|
27196
|
-
|
|
27197
|
-
|
|
27181
|
+
function isDisjoint(...headers) {
|
|
27182
|
+
const parameters = new Set;
|
|
27183
|
+
for (const header of headers) {
|
|
27184
|
+
if (!header)
|
|
27185
|
+
continue;
|
|
27186
|
+
for (const parameter of Object.keys(header)) {
|
|
27187
|
+
if (parameters.has(parameter)) {
|
|
27188
|
+
return false;
|
|
27189
|
+
}
|
|
27190
|
+
parameters.add(parameter);
|
|
27191
|
+
}
|
|
27192
|
+
}
|
|
27193
|
+
return true;
|
|
27194
|
+
}
|
|
27195
|
+
var isJWK = (key) => isObject3(key) && typeof key.kty === "string";
|
|
27196
|
+
var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
|
|
27197
|
+
var isPublicJWK = (key) => key.kty !== "oct" && key.d === undefined && key.priv === undefined;
|
|
27198
|
+
var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
|
|
27199
|
+
|
|
27200
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/helpers.js
|
|
27201
|
+
var unprotected = Symbol();
|
|
27202
|
+
function assertNotSet(value, name) {
|
|
27203
|
+
if (value) {
|
|
27204
|
+
throw new TypeError(`${name} can only be called once`);
|
|
27205
|
+
}
|
|
27206
|
+
}
|
|
27207
|
+
async function digest(algorithm, data) {
|
|
27208
|
+
const subtleDigest = `SHA-${algorithm.slice(-3)}`;
|
|
27209
|
+
return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
|
|
27210
|
+
}
|
|
27211
|
+
|
|
27212
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jwk_to_key.js
|
|
27213
|
+
async function jwkToKey(entry, jwk) {
|
|
27214
|
+
if (jwk.kty === "RSA" && "oth" in jwk && jwk.oth !== undefined) {
|
|
27215
|
+
throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
|
|
27216
|
+
}
|
|
27217
|
+
if (!entry.kty.includes(jwk.kty)) {
|
|
27218
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
27219
|
+
}
|
|
27220
|
+
const algorithm = entry.resolve?.({ kty: jwk.kty, crv: jwk.crv }) ?? entry.subtle;
|
|
27221
|
+
const isPrivate = !!(jwk.d || jwk.priv);
|
|
27222
|
+
const keyData = { ...jwk };
|
|
27223
|
+
if (keyData.kty !== "AKP") {
|
|
27224
|
+
delete keyData.alg;
|
|
27225
|
+
}
|
|
27226
|
+
delete keyData.use;
|
|
27227
|
+
return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? !isPrivate, jwk.key_ops ?? entry.usages[isPrivate ? 1 : 0]);
|
|
27228
|
+
}
|
|
27229
|
+
|
|
27230
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key.js
|
|
27231
|
+
var tag = (key) => key[Symbol.toStringTag];
|
|
27232
|
+
var jwkMatchesOp = (entry, key, usage) => {
|
|
27233
|
+
const { alg } = entry;
|
|
27234
|
+
if (key.use !== undefined) {
|
|
27235
|
+
const expected = usage === "sign" || usage === "verify" ? "sig" : "enc";
|
|
27236
|
+
if (key.use !== expected) {
|
|
27237
|
+
throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
27238
|
+
}
|
|
27239
|
+
}
|
|
27240
|
+
if (key.alg !== undefined && key.alg !== alg) {
|
|
27241
|
+
throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
27242
|
+
}
|
|
27243
|
+
if (Array.isArray(key.key_ops)) {
|
|
27244
|
+
const expectedKeyOp = usage === "encrypt" || usage === "decrypt" ? entry.ops?.[usage === "encrypt" ? 0 : 1] : usage;
|
|
27245
|
+
if (expectedKeyOp && !key.key_ops.includes(expectedKeyOp)) {
|
|
27246
|
+
throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
27247
|
+
}
|
|
27248
|
+
}
|
|
27249
|
+
};
|
|
27250
|
+
function checkKeyType(entry, key, usage) {
|
|
27251
|
+
const { alg, secret } = entry;
|
|
27252
|
+
const privateKey = usage === "decrypt" || usage === "sign";
|
|
27253
|
+
if (secret && key instanceof Uint8Array)
|
|
27254
|
+
return [BYTES, key];
|
|
27255
|
+
if (isJWK(key)) {
|
|
27256
|
+
if (secret ? !isSecretJWK(key) : !(privateKey ? isPrivateJWK(key) : isPublicJWK(key))) {
|
|
27257
|
+
throw new TypeError(secret ? `JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present` : `JSON Web Key for this operation must be a ${privateKey ? "private" : "public"} JWK`);
|
|
27258
|
+
}
|
|
27259
|
+
jwkMatchesOp(entry, key, usage);
|
|
27260
|
+
return [JWK, key];
|
|
27261
|
+
}
|
|
27262
|
+
if (!isKeyLike(key)) {
|
|
27263
|
+
throw new TypeError(secret ? withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array") : withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
27264
|
+
}
|
|
27265
|
+
if (secret) {
|
|
27266
|
+
if (key.type !== "secret") {
|
|
27267
|
+
throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
|
|
27268
|
+
}
|
|
27269
|
+
} else {
|
|
27270
|
+
if (key.type === "secret") {
|
|
27271
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
|
|
27272
|
+
}
|
|
27273
|
+
const expectedType = privateKey ? "private" : "public";
|
|
27274
|
+
if ((key.type === "public" || key.type === "private") && key.type !== expectedType) {
|
|
27275
|
+
const operation = usage === "sign" ? "signing" : usage === "verify" ? "verifying" : `${usage.slice(0, -1)}tion`;
|
|
27276
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm ${operation} must be of type "${expectedType}"`);
|
|
27277
|
+
}
|
|
27278
|
+
}
|
|
27279
|
+
return isCryptoKey(key) ? [CRYPTO, key] : [KEYOBJECT, key];
|
|
27280
|
+
}
|
|
27281
|
+
var BYTES = 0;
|
|
27282
|
+
var CRYPTO = 1;
|
|
27283
|
+
var KEYOBJECT = 2;
|
|
27284
|
+
var JWK = 3;
|
|
27285
|
+
var cache;
|
|
27286
|
+
var nist = {
|
|
27287
|
+
__proto__: null,
|
|
27288
|
+
prime256v1: "P-256",
|
|
27289
|
+
secp384r1: "P-384",
|
|
27290
|
+
secp521r1: "P-521"
|
|
27291
|
+
};
|
|
27292
|
+
function cached2(key, alg, value) {
|
|
27293
|
+
cache ||= new WeakMap;
|
|
27294
|
+
const entry = cache.get(key);
|
|
27295
|
+
if (value) {
|
|
27296
|
+
if (entry) {
|
|
27297
|
+
entry[alg] = value;
|
|
27298
|
+
} else {
|
|
27299
|
+
cache.set(key, { __proto__: null, [alg]: value });
|
|
27300
|
+
}
|
|
27301
|
+
}
|
|
27302
|
+
return value ?? entry?.[alg];
|
|
27303
|
+
}
|
|
27304
|
+
var handleJWK = async (key, jwk, entry) => cached2(key, entry.alg) ?? cached2(key, entry.alg, await jwkToKey(entry, { ...jwk, alg: entry.alg }));
|
|
27305
|
+
var handleKeyObject = (keyObject, entry) => {
|
|
27306
|
+
const hit = cached2(keyObject, entry.alg);
|
|
27307
|
+
if (hit)
|
|
27308
|
+
return hit;
|
|
27309
|
+
const isPublic = keyObject.type === "public";
|
|
27310
|
+
const usages = entry.usages[isPublic ? 0 : 1];
|
|
27311
|
+
const { asymmetricKeyType } = keyObject;
|
|
27312
|
+
const crv = nist[keyObject.asymmetricKeyDetails?.namedCurve];
|
|
27313
|
+
const params = entry.resolve?.({ crv, asymmetricKeyType }) ?? entry.subtle;
|
|
27314
|
+
return cached2(keyObject, entry.alg, keyObject.toCryptoKey(params, isPublic, usages));
|
|
27315
|
+
};
|
|
27316
|
+
async function prepareKey(entry, key, usage) {
|
|
27317
|
+
const tagged = checkKeyType(entry, key, usage);
|
|
27318
|
+
switch (tagged[0]) {
|
|
27319
|
+
case BYTES:
|
|
27320
|
+
case CRYPTO:
|
|
27321
|
+
return tagged[1];
|
|
27322
|
+
case JWK: {
|
|
27323
|
+
const key = tagged[1];
|
|
27324
|
+
if (key.k) {
|
|
27325
|
+
return decode3(key.k);
|
|
27326
|
+
}
|
|
27327
|
+
if (!Object.isFrozen(key)) {
|
|
27328
|
+
const { key_ops } = key;
|
|
27329
|
+
if (Array.isArray(key_ops))
|
|
27330
|
+
Object.freeze(key_ops);
|
|
27331
|
+
Object.freeze(key);
|
|
27332
|
+
}
|
|
27333
|
+
return handleJWK(key, key, entry);
|
|
27334
|
+
}
|
|
27335
|
+
case KEYOBJECT: {
|
|
27336
|
+
const keyObject = tagged[1];
|
|
27337
|
+
if (keyObject.type === "secret") {
|
|
27338
|
+
return keyObject.export();
|
|
27339
|
+
}
|
|
27340
|
+
if ("toCryptoKey" in keyObject && typeof keyObject.toCryptoKey === "function") {
|
|
27341
|
+
return handleKeyObject(keyObject, entry);
|
|
27342
|
+
}
|
|
27343
|
+
return handleJWK(keyObject, keyObject.export({ format: "jwk" }), entry);
|
|
27344
|
+
}
|
|
27345
|
+
}
|
|
27346
|
+
}
|
|
27347
|
+
|
|
27348
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/key_descriptor.js
|
|
27349
|
+
function table(entries) {
|
|
27350
|
+
const out = { __proto__: null };
|
|
27351
|
+
for (const alg in entries) {
|
|
27352
|
+
out[alg] = { ...entries[alg], alg };
|
|
27353
|
+
}
|
|
27354
|
+
return out;
|
|
27355
|
+
}
|
|
27356
|
+
|
|
27357
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/options.js
|
|
27358
|
+
var JWS_RECOGNIZED = { __proto__: null, b64: true };
|
|
27359
|
+
function validateCritDuplicates(Err, protectedHeader) {
|
|
27360
|
+
const { crit } = protectedHeader ?? {};
|
|
27361
|
+
if (Array.isArray(crit) && new Set(crit).size !== crit.length) {
|
|
27362
|
+
throw new Err('"crit" (Critical) Header Parameter MUST NOT contain duplicate values');
|
|
27363
|
+
}
|
|
27364
|
+
}
|
|
27365
|
+
function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
|
|
27366
|
+
if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {
|
|
27367
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
|
|
27368
|
+
}
|
|
27369
|
+
if (!protectedHeader || protectedHeader.crit === undefined) {
|
|
27370
|
+
return [];
|
|
27371
|
+
}
|
|
27372
|
+
if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
|
|
27373
|
+
throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
|
|
27374
|
+
}
|
|
27375
|
+
const recognized = recognizedOption === undefined ? recognizedDefault : { __proto__: null, ...recognizedOption, ...recognizedDefault };
|
|
27376
|
+
for (const parameter of protectedHeader.crit) {
|
|
27377
|
+
if (!(parameter in recognized)) {
|
|
27378
|
+
throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
27379
|
+
}
|
|
27380
|
+
if (!Object.hasOwn(joseHeader, parameter) || joseHeader[parameter] === undefined) {
|
|
27381
|
+
throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
27382
|
+
}
|
|
27383
|
+
if (recognized[parameter] && (!Object.hasOwn(protectedHeader, parameter) || protectedHeader[parameter] === undefined)) {
|
|
27384
|
+
throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
27385
|
+
}
|
|
27386
|
+
}
|
|
27387
|
+
return protectedHeader.crit;
|
|
27388
|
+
}
|
|
27389
|
+
|
|
27390
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/signing.js
|
|
27391
|
+
async function getSigKey(entry, key, usage) {
|
|
27392
|
+
if (key instanceof Uint8Array) {
|
|
27393
|
+
return crypto.subtle.importKey("raw", key, entry.subtle, false, [
|
|
27394
|
+
usage
|
|
27395
|
+
]);
|
|
27396
|
+
}
|
|
27397
|
+
checkCryptoKey(key, entry.subtle, usage);
|
|
27398
|
+
if (entry.minRsaBits)
|
|
27399
|
+
checkModulusLength(entry.alg, key);
|
|
27400
|
+
return key;
|
|
27401
|
+
}
|
|
27402
|
+
async function sign(entry, key, data) {
|
|
27403
|
+
const cryptoKey = await getSigKey(entry, key, "sign");
|
|
27404
|
+
const signature = await crypto.subtle.sign(entry.signing, cryptoKey, data);
|
|
27405
|
+
return new Uint8Array(signature);
|
|
27406
|
+
}
|
|
27407
|
+
|
|
27408
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_algorithms.js
|
|
27409
|
+
var sig = [["verify"], ["sign"]];
|
|
27410
|
+
function hmac(bits) {
|
|
27411
|
+
const subtle = { name: "HMAC", hash: `SHA-${bits}` };
|
|
27412
|
+
return { kty: ["oct"], secret: true, subtle, signing: subtle, usages: sig };
|
|
27413
|
+
}
|
|
27414
|
+
function rsa(bits, saltLength) {
|
|
27415
|
+
const name = saltLength ? "RSA-PSS" : "RSASSA-PKCS1-v1_5";
|
|
27416
|
+
const subtle = { name, hash: `SHA-${bits}` };
|
|
27417
|
+
return {
|
|
27418
|
+
kty: ["RSA"],
|
|
27419
|
+
subtle,
|
|
27420
|
+
signing: saltLength ? { ...subtle, saltLength } : subtle,
|
|
27421
|
+
usages: sig,
|
|
27422
|
+
minRsaBits: 2048
|
|
27423
|
+
};
|
|
27424
|
+
}
|
|
27425
|
+
function ecdsa(crv, bits) {
|
|
27426
|
+
return {
|
|
27427
|
+
kty: ["EC"],
|
|
27428
|
+
crv,
|
|
27429
|
+
subtle: { name: "ECDSA", namedCurve: crv },
|
|
27430
|
+
signing: { name: "ECDSA", hash: `SHA-${bits}` },
|
|
27431
|
+
usages: sig
|
|
27432
|
+
};
|
|
27433
|
+
}
|
|
27434
|
+
function eddsa() {
|
|
27435
|
+
const subtle = { name: "Ed25519" };
|
|
27436
|
+
return {
|
|
27437
|
+
kty: ["OKP"],
|
|
27438
|
+
crv: "Ed25519",
|
|
27439
|
+
subtle,
|
|
27440
|
+
signing: subtle,
|
|
27441
|
+
usages: sig
|
|
27442
|
+
};
|
|
27443
|
+
}
|
|
27444
|
+
function mldsa(bits) {
|
|
27445
|
+
const name = `ML-DSA-${bits}`;
|
|
27446
|
+
const subtle = { name };
|
|
27447
|
+
return {
|
|
27448
|
+
kty: ["AKP"],
|
|
27449
|
+
subtle,
|
|
27450
|
+
signing: subtle,
|
|
27451
|
+
usages: sig
|
|
27452
|
+
};
|
|
27453
|
+
}
|
|
27454
|
+
var JWS = table({
|
|
27455
|
+
HS256: hmac(256),
|
|
27456
|
+
HS384: hmac(384),
|
|
27457
|
+
HS512: hmac(512),
|
|
27458
|
+
RS256: rsa(256),
|
|
27459
|
+
RS384: rsa(384),
|
|
27460
|
+
RS512: rsa(512),
|
|
27461
|
+
PS256: rsa(256, 32),
|
|
27462
|
+
PS384: rsa(384, 48),
|
|
27463
|
+
PS512: rsa(512, 64),
|
|
27464
|
+
ES256: ecdsa("P-256", 256),
|
|
27465
|
+
ES384: ecdsa("P-384", 384),
|
|
27466
|
+
ES512: ecdsa("P-521", 512),
|
|
27467
|
+
EdDSA: eddsa(),
|
|
27468
|
+
Ed25519: eddsa(),
|
|
27469
|
+
"ML-DSA-44": mldsa(44),
|
|
27470
|
+
"ML-DSA-65": mldsa(65),
|
|
27471
|
+
"ML-DSA-87": mldsa(87)
|
|
27472
|
+
});
|
|
27473
|
+
function jwsAlgorithm(alg) {
|
|
27474
|
+
const entry = typeof alg === "string" ? JWS[alg] : undefined;
|
|
27475
|
+
if (!entry) {
|
|
27476
|
+
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
27477
|
+
}
|
|
27478
|
+
return entry;
|
|
27479
|
+
}
|
|
27480
|
+
|
|
27481
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/lib/jws_sign.js
|
|
27482
|
+
function unencodedPayload(protectedHeader) {
|
|
27483
|
+
return protectedHeader?.b64 === false && Array.isArray(protectedHeader.crit) && protectedHeader.crit.includes("b64");
|
|
27484
|
+
}
|
|
27485
|
+
async function createSignature(input, key) {
|
|
27486
|
+
const { protectedHeader, unprotectedHeader } = input;
|
|
27487
|
+
if (!protectedHeader && !unprotectedHeader) {
|
|
27488
|
+
throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
|
|
27489
|
+
}
|
|
27490
|
+
if (!isDisjoint(protectedHeader, unprotectedHeader)) {
|
|
27491
|
+
throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
27492
|
+
}
|
|
27493
|
+
const joseHeader = { ...protectedHeader, ...unprotectedHeader };
|
|
27494
|
+
validateCritDuplicates(JWSInvalid, protectedHeader);
|
|
27495
|
+
const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, input.crit, protectedHeader, joseHeader);
|
|
27496
|
+
let b64 = true;
|
|
27497
|
+
if (extensions.includes("b64")) {
|
|
27498
|
+
b64 = protectedHeader.b64;
|
|
27499
|
+
if (typeof b64 !== "boolean") {
|
|
27500
|
+
throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
|
27501
|
+
}
|
|
27502
|
+
}
|
|
27503
|
+
const { alg } = joseHeader;
|
|
27504
|
+
if (typeof alg !== "string" || !alg) {
|
|
27505
|
+
throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
27506
|
+
}
|
|
27507
|
+
const entry = jwsAlgorithm(alg);
|
|
27508
|
+
let payloadS;
|
|
27509
|
+
let payloadB;
|
|
27510
|
+
if (b64) {
|
|
27511
|
+
const encoded = input.encoded ??= [];
|
|
27512
|
+
encoded[0] ??= encode5(input.payload);
|
|
27513
|
+
encoded[1] ??= encode4(encoded[0]);
|
|
27514
|
+
payloadS = encoded[0];
|
|
27515
|
+
payloadB = encoded[1];
|
|
27516
|
+
} else {
|
|
27517
|
+
payloadB = input.payload;
|
|
27518
|
+
payloadS = "";
|
|
27519
|
+
}
|
|
27520
|
+
let protectedHeaderString;
|
|
27521
|
+
let protectedHeaderBytes;
|
|
27522
|
+
if (protectedHeader) {
|
|
27523
|
+
protectedHeaderString = encode5(JSON.stringify(protectedHeader));
|
|
27524
|
+
protectedHeaderBytes = encode4(protectedHeaderString);
|
|
27525
|
+
} else {
|
|
27526
|
+
protectedHeaderString = "";
|
|
27527
|
+
protectedHeaderBytes = new Uint8Array;
|
|
27528
|
+
}
|
|
27529
|
+
const data = concat(protectedHeaderBytes, encode4("."), payloadB);
|
|
27530
|
+
const k = await prepareKey(entry, key, "sign");
|
|
27531
|
+
const signature = await sign(entry, k, data);
|
|
27532
|
+
const jws = {
|
|
27533
|
+
signature: encode5(signature),
|
|
27534
|
+
payload: payloadS
|
|
27535
|
+
};
|
|
27536
|
+
if (protectedHeader) {
|
|
27537
|
+
jws.protected = protectedHeaderString;
|
|
27538
|
+
}
|
|
27539
|
+
if (unprotectedHeader) {
|
|
27540
|
+
jws.header = unprotectedHeader;
|
|
27541
|
+
}
|
|
27542
|
+
return jws;
|
|
27543
|
+
}
|
|
27544
|
+
|
|
27545
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/flattened/sign.js
|
|
27546
|
+
class FlattenedSign {
|
|
27547
|
+
#payload;
|
|
27548
|
+
#protectedHeader;
|
|
27549
|
+
#unprotectedHeader;
|
|
27550
|
+
constructor(payload) {
|
|
27551
|
+
if (!(payload instanceof Uint8Array)) {
|
|
27552
|
+
throw new TypeError("payload must be an instance of Uint8Array");
|
|
27553
|
+
}
|
|
27554
|
+
this.#payload = payload;
|
|
27555
|
+
}
|
|
27556
|
+
setProtectedHeader(protectedHeader) {
|
|
27557
|
+
assertNotSet(this.#protectedHeader, "setProtectedHeader");
|
|
27558
|
+
this.#protectedHeader = protectedHeader;
|
|
27559
|
+
return this;
|
|
27560
|
+
}
|
|
27561
|
+
setUnprotectedHeader(unprotectedHeader) {
|
|
27562
|
+
assertNotSet(this.#unprotectedHeader, "setUnprotectedHeader");
|
|
27563
|
+
this.#unprotectedHeader = unprotectedHeader;
|
|
27564
|
+
return this;
|
|
27565
|
+
}
|
|
27566
|
+
async sign(key, options) {
|
|
27567
|
+
return createSignature({
|
|
27568
|
+
payload: this.#payload,
|
|
27569
|
+
protectedHeader: this.#protectedHeader,
|
|
27570
|
+
unprotectedHeader: this.#unprotectedHeader,
|
|
27571
|
+
crit: options?.crit
|
|
27572
|
+
}, key);
|
|
27573
|
+
}
|
|
27574
|
+
}
|
|
27575
|
+
|
|
27576
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jws/compact/sign.js
|
|
27577
|
+
class CompactSign {
|
|
27578
|
+
#flattened;
|
|
27579
|
+
#protectedHeader;
|
|
27580
|
+
constructor(payload) {
|
|
27581
|
+
this.#flattened = new FlattenedSign(payload);
|
|
27582
|
+
}
|
|
27583
|
+
setProtectedHeader(protectedHeader) {
|
|
27584
|
+
this.#flattened.setProtectedHeader(protectedHeader);
|
|
27585
|
+
this.#protectedHeader = protectedHeader;
|
|
27586
|
+
return this;
|
|
27587
|
+
}
|
|
27588
|
+
async sign(key, options) {
|
|
27589
|
+
if (unencodedPayload(this.#protectedHeader)) {
|
|
27590
|
+
throw new TypeError("use the flattened module for creating JWS with b64: false");
|
|
27591
|
+
}
|
|
27592
|
+
const jws = await this.#flattened.sign(key, options);
|
|
27593
|
+
return `${jws.protected}.${jws.payload}.${jws.signature}`;
|
|
27594
|
+
}
|
|
27595
|
+
}
|
|
27596
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/key/export.js
|
|
27597
|
+
function omitUndefinedProperties(jwk) {
|
|
27598
|
+
return Object.fromEntries(Object.entries(jwk).filter(([, value]) => value !== undefined));
|
|
27599
|
+
}
|
|
27600
|
+
async function keyToJWK(key) {
|
|
27601
|
+
if (isKeyObject(key)) {
|
|
27602
|
+
if (key.type === "secret") {
|
|
27603
|
+
key = key.export();
|
|
27604
|
+
} else {
|
|
27605
|
+
return key.export({ format: "jwk" });
|
|
27606
|
+
}
|
|
27607
|
+
}
|
|
27608
|
+
if (key instanceof Uint8Array) {
|
|
27609
|
+
return {
|
|
27610
|
+
kty: "oct",
|
|
27611
|
+
k: encode5(key)
|
|
27612
|
+
};
|
|
27613
|
+
}
|
|
27614
|
+
if (!isCryptoKey(key)) {
|
|
27615
|
+
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
|
|
27616
|
+
}
|
|
27617
|
+
if (!key.extractable) {
|
|
27618
|
+
throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
|
|
27619
|
+
}
|
|
27620
|
+
const { ext, key_ops, alg, use, ...jwk } = omitUndefinedProperties(await crypto.subtle.exportKey("jwk", key));
|
|
27621
|
+
if (jwk.kty === "AKP") {
|
|
27622
|
+
jwk.alg = alg;
|
|
27623
|
+
}
|
|
27624
|
+
return jwk;
|
|
27625
|
+
}
|
|
27626
|
+
function exportJWK(key) {
|
|
27627
|
+
return keyToJWK(key);
|
|
27628
|
+
}
|
|
27629
|
+
|
|
27630
|
+
// ../../node_modules/.bun/jose@6.2.9/node_modules/jose/dist/webapi/jwk/thumbprint.js
|
|
27631
|
+
var check2 = (value, description) => {
|
|
27632
|
+
if (typeof value !== "string" || !value) {
|
|
27633
|
+
throw new JWKInvalid(`${description} missing or invalid`);
|
|
27634
|
+
}
|
|
27635
|
+
};
|
|
27636
|
+
async function calculateJwkThumbprint(key, digestAlgorithm) {
|
|
27637
|
+
let jwk;
|
|
27638
|
+
if (isJWK(key)) {
|
|
27639
|
+
jwk = key;
|
|
27640
|
+
} else if (isKeyLike(key)) {
|
|
27641
|
+
jwk = await exportJWK(key);
|
|
27642
|
+
} else {
|
|
27643
|
+
throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
27644
|
+
}
|
|
27645
|
+
digestAlgorithm ??= "sha256";
|
|
27646
|
+
if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") {
|
|
27647
|
+
throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');
|
|
27648
|
+
}
|
|
27649
|
+
let components;
|
|
27650
|
+
switch (jwk.kty) {
|
|
27651
|
+
case "AKP":
|
|
27652
|
+
check2(jwk.alg, '"alg" (Algorithm) Parameter');
|
|
27653
|
+
check2(jwk.pub, '"pub" (Public key) Parameter');
|
|
27654
|
+
components = { alg: jwk.alg, kty: jwk.kty, pub: jwk.pub };
|
|
27655
|
+
break;
|
|
27656
|
+
case "EC":
|
|
27657
|
+
check2(jwk.crv, '"crv" (Curve) Parameter');
|
|
27658
|
+
check2(jwk.x, '"x" (X Coordinate) Parameter');
|
|
27659
|
+
check2(jwk.y, '"y" (Y Coordinate) Parameter');
|
|
27660
|
+
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
|
|
27661
|
+
break;
|
|
27662
|
+
case "OKP":
|
|
27663
|
+
check2(jwk.crv, '"crv" (Subtype of Key Pair) Parameter');
|
|
27664
|
+
check2(jwk.x, '"x" (Public Key) Parameter');
|
|
27665
|
+
components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };
|
|
27666
|
+
break;
|
|
27667
|
+
case "RSA":
|
|
27668
|
+
check2(jwk.e, '"e" (Exponent) Parameter');
|
|
27669
|
+
check2(jwk.n, '"n" (Modulus) Parameter');
|
|
27670
|
+
components = { e: jwk.e, kty: jwk.kty, n: jwk.n };
|
|
27671
|
+
break;
|
|
27672
|
+
case "oct":
|
|
27673
|
+
check2(jwk.k, '"k" (Key Value) Parameter');
|
|
27674
|
+
components = { k: jwk.k, kty: jwk.kty };
|
|
27675
|
+
break;
|
|
27676
|
+
default:
|
|
27677
|
+
throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported');
|
|
27678
|
+
}
|
|
27679
|
+
const data = encode4(JSON.stringify(components));
|
|
27680
|
+
return encode5(await digest(digestAlgorithm, data));
|
|
27681
|
+
}
|
|
27682
|
+
// ../../node_modules/.bun/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
|
|
27683
|
+
var USER_AGENT;
|
|
27684
|
+
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
|
|
27685
|
+
const NAME = "oauth4webapi";
|
|
27686
|
+
const VERSION = "v3.8.8";
|
|
27687
|
+
USER_AGENT = `${NAME}/${VERSION}`;
|
|
27688
|
+
}
|
|
27689
|
+
function looseInstanceOf(input, expected) {
|
|
27690
|
+
if (input == null) {
|
|
27691
|
+
return false;
|
|
27692
|
+
}
|
|
27693
|
+
try {
|
|
27694
|
+
return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
|
|
27695
|
+
} catch {
|
|
27696
|
+
return false;
|
|
27697
|
+
}
|
|
27698
|
+
}
|
|
27699
|
+
var ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
|
|
27700
|
+
var ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
|
|
27701
|
+
function CodedTypeError(message, code, cause) {
|
|
27702
|
+
const err = new TypeError(message, { cause });
|
|
27703
|
+
Object.assign(err, { code });
|
|
27704
|
+
return err;
|
|
27705
|
+
}
|
|
27706
|
+
var allowInsecureRequests = Symbol();
|
|
27707
|
+
var clockSkew = Symbol();
|
|
27708
|
+
var clockTolerance = Symbol();
|
|
27709
|
+
var customFetch = Symbol();
|
|
27710
|
+
var modifyAssertion = Symbol();
|
|
27711
|
+
var jweDecrypt = Symbol();
|
|
27712
|
+
var jwksCache = Symbol();
|
|
27713
|
+
var encoder3 = new TextEncoder;
|
|
27714
|
+
var decoder2 = new TextDecoder;
|
|
27715
|
+
function buf(input) {
|
|
27716
|
+
if (typeof input === "string") {
|
|
27717
|
+
return encoder3.encode(input);
|
|
27718
|
+
}
|
|
27719
|
+
return decoder2.decode(input);
|
|
27720
|
+
}
|
|
27721
|
+
var encodeBase64Url;
|
|
27722
|
+
if (Uint8Array.prototype.toBase64) {
|
|
27723
|
+
encodeBase64Url = (input) => {
|
|
27724
|
+
if (input instanceof ArrayBuffer) {
|
|
27725
|
+
input = new Uint8Array(input);
|
|
27726
|
+
}
|
|
27727
|
+
return input.toBase64({ alphabet: "base64url", omitPadding: true });
|
|
27728
|
+
};
|
|
27729
|
+
} else {
|
|
27730
|
+
const CHUNK_SIZE = 32768;
|
|
27731
|
+
encodeBase64Url = (input) => {
|
|
27732
|
+
if (input instanceof ArrayBuffer) {
|
|
27733
|
+
input = new Uint8Array(input);
|
|
27734
|
+
}
|
|
27735
|
+
const arr = [];
|
|
27736
|
+
for (let i = 0;i < input.byteLength; i += CHUNK_SIZE) {
|
|
27737
|
+
arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
27738
|
+
}
|
|
27739
|
+
return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
27740
|
+
};
|
|
27741
|
+
}
|
|
27742
|
+
var decodeBase64Url;
|
|
27743
|
+
if (Uint8Array.fromBase64) {
|
|
27744
|
+
decodeBase64Url = (input) => {
|
|
27745
|
+
try {
|
|
27746
|
+
return Uint8Array.fromBase64(input, { alphabet: "base64url" });
|
|
27747
|
+
} catch (cause) {
|
|
27748
|
+
throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
|
|
27749
|
+
}
|
|
27750
|
+
};
|
|
27751
|
+
} else {
|
|
27752
|
+
decodeBase64Url = (input) => {
|
|
27753
|
+
try {
|
|
27754
|
+
const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
|
|
27755
|
+
const bytes = new Uint8Array(binary.length);
|
|
27756
|
+
for (let i = 0;i < binary.length; i++) {
|
|
27757
|
+
bytes[i] = binary.charCodeAt(i);
|
|
27758
|
+
}
|
|
27759
|
+
return bytes;
|
|
27760
|
+
} catch (cause) {
|
|
27761
|
+
throw CodedTypeError("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE, cause);
|
|
27762
|
+
}
|
|
27763
|
+
};
|
|
27764
|
+
}
|
|
27765
|
+
function b64u(input) {
|
|
27766
|
+
if (typeof input === "string") {
|
|
27767
|
+
return decodeBase64Url(input);
|
|
27768
|
+
}
|
|
27769
|
+
return encodeBase64Url(input);
|
|
27770
|
+
}
|
|
27771
|
+
|
|
27772
|
+
class UnsupportedOperationError extends Error {
|
|
27773
|
+
code;
|
|
27774
|
+
constructor(message, options) {
|
|
27775
|
+
super(message, options);
|
|
27776
|
+
this.name = this.constructor.name;
|
|
27777
|
+
this.code = UNSUPPORTED_OPERATION;
|
|
27778
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
27779
|
+
}
|
|
27780
|
+
}
|
|
27781
|
+
|
|
27782
|
+
class OperationProcessingError extends Error {
|
|
27783
|
+
code;
|
|
27784
|
+
constructor(message, options) {
|
|
27785
|
+
super(message, options);
|
|
27786
|
+
this.name = this.constructor.name;
|
|
27198
27787
|
if (options?.code) {
|
|
27199
27788
|
this.code = options?.code;
|
|
27200
27789
|
}
|
|
@@ -27937,6 +28526,47 @@ function checkSigningAlgorithm(client, issuer, fallback, header) {
|
|
|
27937
28526
|
}
|
|
27938
28527
|
var skipStateCheck = Symbol();
|
|
27939
28528
|
var expectNoState = Symbol();
|
|
28529
|
+
async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {
|
|
28530
|
+
assertAs(as);
|
|
28531
|
+
assertClient(client);
|
|
28532
|
+
const url = resolveEndpoint(as, "device_authorization_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests] !== true);
|
|
28533
|
+
const body = new URLSearchParams(parameters);
|
|
28534
|
+
body.set("client_id", client.client_id);
|
|
28535
|
+
const headers = prepareHeaders(options?.headers);
|
|
28536
|
+
headers.set("accept", "application/json");
|
|
28537
|
+
return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
|
|
28538
|
+
}
|
|
28539
|
+
async function processDeviceAuthorizationResponse(as, client, response) {
|
|
28540
|
+
assertAs(as);
|
|
28541
|
+
assertClient(client);
|
|
28542
|
+
if (!looseInstanceOf(response, Response)) {
|
|
28543
|
+
throw CodedTypeError('"response" must be an instance of Response', ERR_INVALID_ARG_TYPE);
|
|
28544
|
+
}
|
|
28545
|
+
await checkOAuthBodyError(response, 200, "Device Authorization Endpoint");
|
|
28546
|
+
assertReadableResponse(response);
|
|
28547
|
+
const json = await getResponseJsonBody(response);
|
|
28548
|
+
assertString(json.device_code, '"response" body "device_code" property', INVALID_RESPONSE, {
|
|
28549
|
+
body: json
|
|
28550
|
+
});
|
|
28551
|
+
assertString(json.user_code, '"response" body "user_code" property', INVALID_RESPONSE, {
|
|
28552
|
+
body: json
|
|
28553
|
+
});
|
|
28554
|
+
assertString(json.verification_uri, '"response" body "verification_uri" property', INVALID_RESPONSE, { body: json });
|
|
28555
|
+
let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
|
|
28556
|
+
assertNumber(expiresIn, true, '"response" body "expires_in" property', INVALID_RESPONSE, {
|
|
28557
|
+
body: json
|
|
28558
|
+
});
|
|
28559
|
+
json.expires_in = expiresIn;
|
|
28560
|
+
if (json.verification_uri_complete !== undefined) {
|
|
28561
|
+
assertString(json.verification_uri_complete, '"response" body "verification_uri_complete" property', INVALID_RESPONSE, { body: json });
|
|
28562
|
+
}
|
|
28563
|
+
if (json.interval !== undefined) {
|
|
28564
|
+
assertNumber(json.interval, false, '"response" body "interval" property', INVALID_RESPONSE, {
|
|
28565
|
+
body: json
|
|
28566
|
+
});
|
|
28567
|
+
}
|
|
28568
|
+
return json;
|
|
28569
|
+
}
|
|
27940
28570
|
async function getResponseJsonBody(response, check = assertApplicationJson) {
|
|
27941
28571
|
let json;
|
|
27942
28572
|
try {
|
|
@@ -28010,7 +28640,7 @@ class ClientError extends Error {
|
|
|
28010
28640
|
Error.captureStackTrace?.(this, this.constructor);
|
|
28011
28641
|
}
|
|
28012
28642
|
}
|
|
28013
|
-
var
|
|
28643
|
+
var decoder3 = new TextDecoder;
|
|
28014
28644
|
function e(msg, cause, code) {
|
|
28015
28645
|
return new ClientError(msg, { cause, code });
|
|
28016
28646
|
}
|
|
@@ -28239,6 +28869,16 @@ function getHelpers(response) {
|
|
|
28239
28869
|
function addHelpers(response) {
|
|
28240
28870
|
Object.defineProperties(response, getHelpers(response));
|
|
28241
28871
|
}
|
|
28872
|
+
async function initiateDeviceAuthorization(config, parameters) {
|
|
28873
|
+
checkConfig(config);
|
|
28874
|
+
const { as, c, auth, fetch: fetch2, tlsOnly, timeout } = int2(config);
|
|
28875
|
+
return deviceAuthorizationRequest(as, c, auth, parameters, {
|
|
28876
|
+
[customFetch]: fetch2,
|
|
28877
|
+
[allowInsecureRequests]: !tlsOnly,
|
|
28878
|
+
headers: new Headers(headers),
|
|
28879
|
+
signal: signal2(timeout)
|
|
28880
|
+
}).then((response) => processDeviceAuthorizationResponse(as, c, response)).catch(errorHandler);
|
|
28881
|
+
}
|
|
28242
28882
|
function allowInsecureRequests2(config) {
|
|
28243
28883
|
int2(config).tlsOnly = false;
|
|
28244
28884
|
}
|
|
@@ -28326,16 +28966,48 @@ async function genericGrantRequest(config, grantType, parameters, options) {
|
|
|
28326
28966
|
return result;
|
|
28327
28967
|
}
|
|
28328
28968
|
|
|
28329
|
-
// ../cipher-client/src/
|
|
28330
|
-
|
|
28331
|
-
|
|
28969
|
+
// ../cipher-client/src/device-login-file.ts
|
|
28970
|
+
import { createPrivateKey, randomUUID as randomUUID3 } from "crypto";
|
|
28971
|
+
import { constants as constants2 } from "fs";
|
|
28972
|
+
import {
|
|
28973
|
+
access,
|
|
28974
|
+
lstat as lstat2,
|
|
28975
|
+
mkdir,
|
|
28976
|
+
open as open2,
|
|
28977
|
+
readFile as readFile2,
|
|
28978
|
+
readlink,
|
|
28979
|
+
rename as rename2,
|
|
28980
|
+
rm as rm2,
|
|
28981
|
+
stat as stat2
|
|
28982
|
+
} from "fs/promises";
|
|
28983
|
+
import { userInfo } from "os";
|
|
28984
|
+
import { dirname as dirname3, isAbsolute as isAbsolute2, join as join7 } from "path";
|
|
28985
|
+
|
|
28986
|
+
// ../cipher-client/src/device-login-lock.ts
|
|
28987
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
28988
|
+
import { constants } from "fs";
|
|
28989
|
+
import {
|
|
28990
|
+
link,
|
|
28991
|
+
lstat,
|
|
28992
|
+
open,
|
|
28993
|
+
readdir as readdir2,
|
|
28994
|
+
rename,
|
|
28995
|
+
rm,
|
|
28996
|
+
stat,
|
|
28997
|
+
utimes
|
|
28998
|
+
} from "fs/promises";
|
|
28999
|
+
import { basename as basename2, dirname as dirname2, join as join6 } from "path";
|
|
29000
|
+
|
|
29001
|
+
// ../cipher-client/src/token-client.ts
|
|
29002
|
+
var DEFAULT_RENEW_BEFORE_MS = 5 * 60000;
|
|
29003
|
+
var BROKER_URL_SETTING = "the broker URL";
|
|
28332
29004
|
var RETRY_FIRST_WAIT_MS = 15000;
|
|
28333
29005
|
var RETRY_MAX_WAIT_MS = 5 * 60000;
|
|
28334
29006
|
var PENDING_FIRST_WAIT_MS = 2000;
|
|
28335
29007
|
var PENDING_MAX_WAIT_MS = 30000;
|
|
28336
29008
|
var UNREGISTERED_LOG_EVERY_MS = 30 * 60000;
|
|
28337
29009
|
var TRADE_ATTEMPT_MS = 30000;
|
|
28338
|
-
function sleep2(ms, signal) {
|
|
29010
|
+
function sleep2(ms, signal, holdsProcess = false) {
|
|
28339
29011
|
const { promise, resolve } = Promise.withResolvers();
|
|
28340
29012
|
if (signal?.aborted) {
|
|
28341
29013
|
resolve();
|
|
@@ -28347,7 +29019,8 @@ function sleep2(ms, signal) {
|
|
|
28347
29019
|
resolve();
|
|
28348
29020
|
};
|
|
28349
29021
|
const timer = setTimeout(done, ms);
|
|
28350
|
-
|
|
29022
|
+
if (!holdsProcess)
|
|
29023
|
+
timer.unref();
|
|
28351
29024
|
signal?.addEventListener("abort", done, { once: true });
|
|
28352
29025
|
return promise;
|
|
28353
29026
|
}
|
|
@@ -28356,12 +29029,24 @@ function statusOf(error) {
|
|
|
28356
29029
|
for (let depth = 0;depth < 4; depth += 1) {
|
|
28357
29030
|
if (cause instanceof Response)
|
|
28358
29031
|
return cause.status;
|
|
29032
|
+
if (cause instanceof ResponseBodyError || cause instanceof WWWAuthenticateChallengeError) {
|
|
29033
|
+
return cause.status;
|
|
29034
|
+
}
|
|
28359
29035
|
if (typeof cause !== "object" || cause === null || !("cause" in cause))
|
|
28360
29036
|
return 0;
|
|
28361
29037
|
cause = cause.cause;
|
|
28362
29038
|
}
|
|
28363
29039
|
return 0;
|
|
28364
29040
|
}
|
|
29041
|
+
function brokerRefusal(doing, refused, endpoint, error, context = {}) {
|
|
29042
|
+
if (error instanceof ResponseBodyError && error.status >= 400 && error.status < 500) {
|
|
29043
|
+
const description = error.error_description;
|
|
29044
|
+
return new BrokerRefusedError(error.status, error.error, typeof description === "string" ? description : "", refused, context);
|
|
29045
|
+
}
|
|
29046
|
+
const status = statusOf(error);
|
|
29047
|
+
const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
|
|
29048
|
+
return new BrokerTradeFailedError(`${doing} ${refused} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
|
|
29049
|
+
}
|
|
28365
29050
|
function requestInit(options, signal, headers) {
|
|
28366
29051
|
const signals = [options.signal, signal].filter((one) => one !== undefined);
|
|
28367
29052
|
return {
|
|
@@ -28372,6 +29057,24 @@ function requestInit(options, signal, headers) {
|
|
|
28372
29057
|
...signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }
|
|
28373
29058
|
};
|
|
28374
29059
|
}
|
|
29060
|
+
async function sendWithProof(proved, url, options, signal) {
|
|
29061
|
+
const send = async () => {
|
|
29062
|
+
const headers = new Headers(options.headers);
|
|
29063
|
+
headers.set("DPoP", await proved.key.proof({ method: options.method, url, nonce: proved.nonce.value }));
|
|
29064
|
+
return await proved.fetch(url, requestInit(options, signal, headers));
|
|
29065
|
+
};
|
|
29066
|
+
let answer = await send();
|
|
29067
|
+
const given = answer.headers.get("DPoP-Nonce") ?? "";
|
|
29068
|
+
if (given !== "")
|
|
29069
|
+
proved.nonce.value = given;
|
|
29070
|
+
if (answer.status === 400 && given !== "") {
|
|
29071
|
+
const body = await answer.clone().json().catch(() => null);
|
|
29072
|
+
const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
|
|
29073
|
+
if (asked)
|
|
29074
|
+
answer = await send();
|
|
29075
|
+
}
|
|
29076
|
+
return answer;
|
|
29077
|
+
}
|
|
28375
29078
|
|
|
28376
29079
|
class BrokerTokenClient {
|
|
28377
29080
|
#brokerUrl;
|
|
@@ -28388,7 +29091,7 @@ class BrokerTokenClient {
|
|
|
28388
29091
|
#log;
|
|
28389
29092
|
#fetch;
|
|
28390
29093
|
#random;
|
|
28391
|
-
#nonce = "";
|
|
29094
|
+
#nonce = { value: "" };
|
|
28392
29095
|
#held = null;
|
|
28393
29096
|
#loop = null;
|
|
28394
29097
|
#waiters = new Set;
|
|
@@ -28612,6 +29315,12 @@ class BrokerTokenClient {
|
|
|
28612
29315
|
}
|
|
28613
29316
|
return { kind: "busy", said: error.message };
|
|
28614
29317
|
}
|
|
29318
|
+
if (error instanceof LockHeldError) {
|
|
29319
|
+
return {
|
|
29320
|
+
kind: "unsent",
|
|
29321
|
+
said: `the trade of ${this.describe()} could not be made: ${scrub(error.message)}`
|
|
29322
|
+
};
|
|
29323
|
+
}
|
|
28615
29324
|
if (timedOut) {
|
|
28616
29325
|
return {
|
|
28617
29326
|
kind: "unanswered",
|
|
@@ -28626,118 +29335,1141 @@ class BrokerTokenClient {
|
|
|
28626
29335
|
};
|
|
28627
29336
|
}
|
|
28628
29337
|
async#trade(signal) {
|
|
28629
|
-
const
|
|
29338
|
+
const source = this.#subject;
|
|
29339
|
+
if (source.spend !== undefined) {
|
|
29340
|
+
return await source.spend((subject) => this.#exchange(subject, signal), signal);
|
|
29341
|
+
}
|
|
29342
|
+
return await this.#exchange(await source.read(signal), signal);
|
|
29343
|
+
}
|
|
29344
|
+
async#exchange(subject, signal) {
|
|
28630
29345
|
holdSecret(subject.token, heldUntil(subject.token));
|
|
28631
29346
|
const form = {
|
|
28632
29347
|
subject_token: subject.token,
|
|
28633
29348
|
subject_token_type: subject.tokenType
|
|
28634
29349
|
};
|
|
28635
|
-
if (this.#session !== "")
|
|
28636
|
-
form[FORM_SESSION] = this.#session;
|
|
28637
|
-
if (this.#projects.length > 0)
|
|
28638
|
-
form[FORM_PROJECTS] = this.#projects.join(" ");
|
|
28639
|
-
if (!this.#launcherCredential) {
|
|
28640
|
-
form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
|
|
29350
|
+
if (this.#session !== "")
|
|
29351
|
+
form[FORM_SESSION] = this.#session;
|
|
29352
|
+
if (this.#projects.length > 0)
|
|
29353
|
+
form[FORM_PROJECTS] = this.#projects.join(" ");
|
|
29354
|
+
if (!this.#launcherCredential) {
|
|
29355
|
+
form[FORM_LAUNCHER_CREDENTIAL] = FORM_LAUNCHER_CREDENTIAL_DECLINED;
|
|
29356
|
+
}
|
|
29357
|
+
if (this.#actor !== undefined) {
|
|
29358
|
+
let actor;
|
|
29359
|
+
try {
|
|
29360
|
+
actor = await this.#actor.read(signal);
|
|
29361
|
+
} catch (error) {
|
|
29362
|
+
throw new Error(`read the machine this person signed in on: ${messageOf(error)}`, {
|
|
29363
|
+
cause: error
|
|
29364
|
+
});
|
|
29365
|
+
}
|
|
29366
|
+
form["actor_token"] = holdSecret(actor.token, heldUntil(actor.token));
|
|
29367
|
+
form["actor_token_type"] = actor.tokenType === SUBJECT_TOKEN_TYPE_GOOGLE ? ACTOR_TOKEN_TYPE_MACHINE : actor.tokenType;
|
|
29368
|
+
}
|
|
29369
|
+
const endpoint = this.#brokerUrl + TOKEN_PATH;
|
|
29370
|
+
const raw = { body: undefined };
|
|
29371
|
+
const config = new Configuration({ issuer: this.#brokerUrl, token_endpoint: endpoint }, EXCHANGE_CLIENT_ID, {}, None2());
|
|
29372
|
+
allowInsecureRequests2(config);
|
|
29373
|
+
config[customFetch2] = (url, options) => this.#send(url, options, signal, raw);
|
|
29374
|
+
let answered;
|
|
29375
|
+
try {
|
|
29376
|
+
answered = await genericGrantRequest(config, GRANT_TYPE_TOKEN_EXCHANGE, form);
|
|
29377
|
+
} catch (error) {
|
|
29378
|
+
throw brokerRefusal("trade", this.#subject.describe(), endpoint, error, {
|
|
29379
|
+
...this.#subject.person === undefined ? {} : { person: this.#subject.person },
|
|
29380
|
+
...this.#session === "" ? {} : { session: this.#session }
|
|
29381
|
+
});
|
|
29382
|
+
}
|
|
29383
|
+
return this.#read(urlForText(endpoint, BROKER_URL_SETTING), answered, raw.body);
|
|
29384
|
+
}
|
|
29385
|
+
async#send(url, options, signal, raw) {
|
|
29386
|
+
const answer = await sendWithProof({ key: this.#key, fetch: this.#fetch, nonce: this.#nonce }, url, options, signal);
|
|
29387
|
+
raw.body = await answer.clone().json().catch(() => {
|
|
29388
|
+
return;
|
|
29389
|
+
});
|
|
29390
|
+
return answer;
|
|
29391
|
+
}
|
|
29392
|
+
#read(endpoint, answered, raw) {
|
|
29393
|
+
const written = typeof raw === "object" && raw !== null && "token_type" in raw ? raw.token_type : undefined;
|
|
29394
|
+
const tokenType = typeof written === "string" ? written : "";
|
|
29395
|
+
if (tokenType.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
|
|
29396
|
+
throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a token_type that is not DPoP, and this grant mints DPoP-bound tokens alone`);
|
|
29397
|
+
}
|
|
29398
|
+
if (answered.refresh_token !== undefined && answered.refresh_token !== "") {
|
|
29399
|
+
throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a refresh token, which this grant never issues; a renewal trades a fresh identity token instead`);
|
|
29400
|
+
}
|
|
29401
|
+
const seconds = answered.expires_in ?? 0;
|
|
29402
|
+
if (!(seconds > 0)) {
|
|
29403
|
+
throw new BrokerTradeFailedError(`the broker at ${endpoint} answered no usable expires_in (a positive number of seconds)`);
|
|
29404
|
+
}
|
|
29405
|
+
const expiresAtText = typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "";
|
|
29406
|
+
let credentialExpiresAt = null;
|
|
29407
|
+
if (expiresAtText !== "") {
|
|
29408
|
+
credentialExpiresAt = new Date(expiresAtText);
|
|
29409
|
+
if (Number.isNaN(credentialExpiresAt.getTime())) {
|
|
29410
|
+
throw new BrokerTradeFailedError(`the broker at ${endpoint} answered a credential_expires_at that is no RFC 3339 time`);
|
|
29411
|
+
}
|
|
29412
|
+
}
|
|
29413
|
+
return {
|
|
29414
|
+
accessToken: holdSecret(answered.access_token, Date.now() + seconds * 1000),
|
|
29415
|
+
tokenType,
|
|
29416
|
+
expiresAt: new Date(this.#now() + seconds * 1000),
|
|
29417
|
+
credentialId: typeof answered["credential_id"] === "string" ? answered["credential_id"] : "",
|
|
29418
|
+
credentialExpiresAt
|
|
29419
|
+
};
|
|
29420
|
+
}
|
|
29421
|
+
}
|
|
29422
|
+
function heldUntil(token) {
|
|
29423
|
+
const now = Date.now();
|
|
29424
|
+
const payload = token.split(".")[1];
|
|
29425
|
+
if (payload === undefined)
|
|
29426
|
+
return now;
|
|
29427
|
+
try {
|
|
29428
|
+
const { exp } = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
29429
|
+
return typeof exp === "number" && Number.isFinite(exp) ? Math.max(exp * 1000, now) : now;
|
|
29430
|
+
} catch {
|
|
29431
|
+
return now;
|
|
29432
|
+
}
|
|
29433
|
+
}
|
|
29434
|
+
|
|
29435
|
+
// ../cipher-client/src/device-login-lock.ts
|
|
29436
|
+
var DEVICE_LOGIN_STALE_LOCK_MS = TRADE_ATTEMPT_MS / 2;
|
|
29437
|
+
var LOCK_HEARTBEAT_MS = DEVICE_LOGIN_STALE_LOCK_MS / 3;
|
|
29438
|
+
var DEVICE_LOGIN_MOST_BYTES = 64 * 1024;
|
|
29439
|
+
var LOCK_READ = constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY | constants.O_NOFOLLOW;
|
|
29440
|
+
var LOCK_RETRY_MS = 100;
|
|
29441
|
+
var STEAL_STALE_MS = 5000;
|
|
29442
|
+
async function statOrNone(path, what) {
|
|
29443
|
+
try {
|
|
29444
|
+
return await lstat(path);
|
|
29445
|
+
} catch (error) {
|
|
29446
|
+
if (readErrorCode(error) === "ENOENT")
|
|
29447
|
+
return null;
|
|
29448
|
+
throw new Error(`read ${what}: ${readErrorCode(error)}`);
|
|
29449
|
+
}
|
|
29450
|
+
}
|
|
29451
|
+
async function createOwn(path, value, named) {
|
|
29452
|
+
let handle;
|
|
29453
|
+
try {
|
|
29454
|
+
handle = await open(path, "wx", 384);
|
|
29455
|
+
} catch (error) {
|
|
29456
|
+
if (readErrorCode(error) === "EEXIST")
|
|
29457
|
+
return false;
|
|
29458
|
+
throw new Error(`take the lock beside ${named}: ${readErrorCode(error)}`);
|
|
29459
|
+
}
|
|
29460
|
+
try {
|
|
29461
|
+
await handle.writeFile(value);
|
|
29462
|
+
} finally {
|
|
29463
|
+
await handle.close();
|
|
29464
|
+
}
|
|
29465
|
+
return true;
|
|
29466
|
+
}
|
|
29467
|
+
async function look(path, what) {
|
|
29468
|
+
let handle;
|
|
29469
|
+
try {
|
|
29470
|
+
handle = await open(path, LOCK_READ);
|
|
29471
|
+
} catch (error) {
|
|
29472
|
+
if (readErrorCode(error) === "ENOENT")
|
|
29473
|
+
return null;
|
|
29474
|
+
const stats = await statOrNone(path, what);
|
|
29475
|
+
return stats === null ? null : { stats, value: "" };
|
|
29476
|
+
}
|
|
29477
|
+
let seen;
|
|
29478
|
+
try {
|
|
29479
|
+
const stats = await handle.stat();
|
|
29480
|
+
const readable = stats.isFile() && stats.size <= DEVICE_LOGIN_MOST_BYTES;
|
|
29481
|
+
seen = { stats, value: readable ? await handle.readFile("utf8").catch(() => "") : "" };
|
|
29482
|
+
} catch (error) {
|
|
29483
|
+
await handle.close().catch(() => {});
|
|
29484
|
+
throw new Error(`read ${what}: ${readErrorCode(error)}`);
|
|
29485
|
+
}
|
|
29486
|
+
await handle.close().catch((error) => {
|
|
29487
|
+
throw new Error(`read ${what}: ${readErrorCode(error)}`);
|
|
29488
|
+
});
|
|
29489
|
+
return seen;
|
|
29490
|
+
}
|
|
29491
|
+
function sameFile(was) {
|
|
29492
|
+
return (seen) => seen.stats.dev === was.stats.dev && seen.stats.ino === was.stats.ino && seen.stats.mtimeMs === was.stats.mtimeMs && seen.value === was.value;
|
|
29493
|
+
}
|
|
29494
|
+
async function removeIfStill(path, isIt, what) {
|
|
29495
|
+
const moved = `${path}.stale-${randomUUID2()}`;
|
|
29496
|
+
try {
|
|
29497
|
+
await rename(path, moved);
|
|
29498
|
+
} catch (error) {
|
|
29499
|
+
if (readErrorCode(error) === "ENOENT")
|
|
29500
|
+
return true;
|
|
29501
|
+
throw new Error(`move ${what} aside: ${readErrorCode(error)}`);
|
|
29502
|
+
}
|
|
29503
|
+
const took = await look(moved, what);
|
|
29504
|
+
const same = took !== null && isIt(took);
|
|
29505
|
+
if (!same)
|
|
29506
|
+
await link(moved, path).catch(() => {});
|
|
29507
|
+
await rm(moved, { force: true }).catch((error) => {
|
|
29508
|
+
throw new Error(`remove ${what}, moved aside: ${readErrorCode(error)}`);
|
|
29509
|
+
});
|
|
29510
|
+
return same;
|
|
29511
|
+
}
|
|
29512
|
+
async function removeOwn(path, value, what) {
|
|
29513
|
+
const seen = await look(path, what);
|
|
29514
|
+
if (seen === null || seen.value !== value)
|
|
29515
|
+
return;
|
|
29516
|
+
await removeIfStill(path, (took) => took.value === value, what);
|
|
29517
|
+
}
|
|
29518
|
+
async function takeStale(lock, mine, named, options) {
|
|
29519
|
+
const locked = `the lock beside ${named}`;
|
|
29520
|
+
const found = await statOrNone(lock, locked);
|
|
29521
|
+
if (found === null)
|
|
29522
|
+
return true;
|
|
29523
|
+
if (Date.now() - found.mtimeMs <= DEVICE_LOGIN_STALE_LOCK_MS)
|
|
29524
|
+
return false;
|
|
29525
|
+
await options.at?.("lock-stale");
|
|
29526
|
+
const steal = `${lock}.steal`;
|
|
29527
|
+
const stealing = `the take-over lock beside ${named}`;
|
|
29528
|
+
if (!await createOwn(steal, mine, named)) {
|
|
29529
|
+
const taking = await look(steal, stealing);
|
|
29530
|
+
if (taking !== null && Date.now() - taking.stats.mtimeMs > STEAL_STALE_MS) {
|
|
29531
|
+
await options.at?.("steal-stale");
|
|
29532
|
+
await removeIfStill(steal, sameFile(taking), `the dead take-over lock beside ${named}`);
|
|
29533
|
+
}
|
|
29534
|
+
return false;
|
|
29535
|
+
}
|
|
29536
|
+
try {
|
|
29537
|
+
const again = await look(lock, locked);
|
|
29538
|
+
if (again === null)
|
|
29539
|
+
return true;
|
|
29540
|
+
if (Date.now() - again.stats.mtimeMs <= DEVICE_LOGIN_STALE_LOCK_MS)
|
|
29541
|
+
return false;
|
|
29542
|
+
await options.at?.("taking");
|
|
29543
|
+
return await removeIfStill(lock, sameFile(again), `the stale lock beside ${named}`);
|
|
29544
|
+
} finally {
|
|
29545
|
+
await removeOwn(steal, mine, stealing);
|
|
29546
|
+
}
|
|
29547
|
+
}
|
|
29548
|
+
function keepReleaseFailure(failed, released) {
|
|
29549
|
+
if (!(failed instanceof Error))
|
|
29550
|
+
return;
|
|
29551
|
+
Reflect.defineProperty(failed, failed.cause === undefined ? "cause" : "releaseFailure", {
|
|
29552
|
+
value: released,
|
|
29553
|
+
writable: true,
|
|
29554
|
+
enumerable: true,
|
|
29555
|
+
configurable: true
|
|
29556
|
+
});
|
|
29557
|
+
}
|
|
29558
|
+
async function withLoginLock(path, named, work, options = {}) {
|
|
29559
|
+
const lock = `${path}.lock`;
|
|
29560
|
+
const locked = `the lock beside ${named}`;
|
|
29561
|
+
const mine = `${process.pid} ${randomUUID2()}
|
|
29562
|
+
`;
|
|
29563
|
+
const wait = options.sleep ?? ((ms, signal) => sleep2(ms, signal, true));
|
|
29564
|
+
while (true) {
|
|
29565
|
+
if (options.signal?.aborted === true) {
|
|
29566
|
+
throw new LockHeldError(locked, { cause: options.signal.reason });
|
|
29567
|
+
}
|
|
29568
|
+
if (await createOwn(lock, mine, named))
|
|
29569
|
+
break;
|
|
29570
|
+
if (await takeStale(lock, mine, named, options))
|
|
29571
|
+
continue;
|
|
29572
|
+
await wait(LOCK_RETRY_MS, options.signal);
|
|
29573
|
+
}
|
|
29574
|
+
const beat = setInterval(async () => {
|
|
29575
|
+
const now = new Date;
|
|
29576
|
+
await utimes(lock, now, now).catch(() => {});
|
|
29577
|
+
}, LOCK_HEARTBEAT_MS);
|
|
29578
|
+
beat.unref();
|
|
29579
|
+
let answer;
|
|
29580
|
+
try {
|
|
29581
|
+
answer = await work(async () => (await look(lock, locked))?.value === mine);
|
|
29582
|
+
} catch (error) {
|
|
29583
|
+
clearInterval(beat);
|
|
29584
|
+
await removeOwn(lock, mine, locked).catch((released) => keepReleaseFailure(error, released));
|
|
29585
|
+
throw error;
|
|
29586
|
+
}
|
|
29587
|
+
clearInterval(beat);
|
|
29588
|
+
await removeOwn(lock, mine, locked);
|
|
29589
|
+
return answer;
|
|
29590
|
+
}
|
|
29591
|
+
function namedWithUuid(name, prefix) {
|
|
29592
|
+
return name.startsWith(prefix) && /^[0-9a-f-]{36}$/.test(name.slice(prefix.length));
|
|
29593
|
+
}
|
|
29594
|
+
async function removeUntouched(dir, left) {
|
|
29595
|
+
const names = await readdir2(dir).catch(() => []);
|
|
29596
|
+
for (const name of names.filter(left)) {
|
|
29597
|
+
const path = join6(dir, name);
|
|
29598
|
+
const info = await stat(path).catch(() => null);
|
|
29599
|
+
if (info !== null && Date.now() - info.mtimeMs > DEVICE_LOGIN_STALE_LOCK_MS) {
|
|
29600
|
+
await rm(path, { force: true }).catch(() => {});
|
|
29601
|
+
}
|
|
29602
|
+
}
|
|
29603
|
+
}
|
|
29604
|
+
async function removeLeftLocks(path) {
|
|
29605
|
+
const name = basename2(path);
|
|
29606
|
+
await removeUntouched(dirname2(path), (one) => namedWithUuid(one, `${name}.lock.stale-`) || namedWithUuid(one, `${name}.lock.steal.stale-`));
|
|
29607
|
+
}
|
|
29608
|
+
|
|
29609
|
+
// ../cipher-client/src/device-login-file.ts
|
|
29610
|
+
var DEVICE_LOGIN_FILE_VAR = "AGENT_SECRETS_DEVICE_LOGIN_FILE";
|
|
29611
|
+
var DEVICE_LOGIN_FILE_NAMED = `the device login ${DEVICE_LOGIN_FILE_VAR} names (default ~/.config/legion/device-login.json)`;
|
|
29612
|
+
function isTemporaryCopy(name) {
|
|
29613
|
+
return /^\.device-login-[0-9a-f-]{36}\.json\.tmp$/.test(name);
|
|
29614
|
+
}
|
|
29615
|
+
function deviceLoginFile(env) {
|
|
29616
|
+
const named = (env[DEVICE_LOGIN_FILE_VAR] ?? "").trim();
|
|
29617
|
+
if (named !== "")
|
|
29618
|
+
return named;
|
|
29619
|
+
const home = (env["HOME"] ?? "").trim();
|
|
29620
|
+
if (home === "") {
|
|
29621
|
+
throw new Error(`${DEVICE_LOGIN_FILE_VAR} names no file and HOME names no home directory, so this machine has nowhere to keep its device login`);
|
|
29622
|
+
}
|
|
29623
|
+
return join7(home, ".config", "legion", "device-login.json");
|
|
29624
|
+
}
|
|
29625
|
+
function member(json, name) {
|
|
29626
|
+
const value = json[name];
|
|
29627
|
+
return typeof value === "string" ? value : "";
|
|
29628
|
+
}
|
|
29629
|
+
function checkPrivate(info, what, forbidden, opens, notOwned) {
|
|
29630
|
+
const mode = info.mode & 511;
|
|
29631
|
+
if ((mode & forbidden) !== 0) {
|
|
29632
|
+
throw new Error(`${what} is mode ${mode.toString(8).padStart(4, "0")}, which ${opens}`);
|
|
29633
|
+
}
|
|
29634
|
+
const uid = process.getuid?.();
|
|
29635
|
+
if (uid !== undefined && info.uid !== uid) {
|
|
29636
|
+
throw new Error(`${what} is owned by uid ${info.uid}, not this user (uid ${uid}); ${notOwned}`);
|
|
29637
|
+
}
|
|
29638
|
+
}
|
|
29639
|
+
var STICKY = 512;
|
|
29640
|
+
var INITIAL_UID_MAP = "0 0 4294967295";
|
|
29641
|
+
var DEFAULT_OVERFLOW_UID = 65534;
|
|
29642
|
+
var systemFiles = new Map;
|
|
29643
|
+
async function systemFile(file) {
|
|
29644
|
+
let info;
|
|
29645
|
+
try {
|
|
29646
|
+
info = await stat2(file);
|
|
29647
|
+
} catch {
|
|
29648
|
+
return null;
|
|
29649
|
+
}
|
|
29650
|
+
const status = [info.dev, info.ino, info.size, info.mtimeMs, info.ctimeMs].join(":");
|
|
29651
|
+
const kept = systemFiles.get(file);
|
|
29652
|
+
if (kept?.status === status)
|
|
29653
|
+
return kept.text;
|
|
29654
|
+
const text = await readFile2(file, "utf8").catch(() => null);
|
|
29655
|
+
if (text === null)
|
|
29656
|
+
systemFiles.delete(file);
|
|
29657
|
+
else
|
|
29658
|
+
systemFiles.set(file, { status, text });
|
|
29659
|
+
return text;
|
|
29660
|
+
}
|
|
29661
|
+
async function safeOwner(uid, mine) {
|
|
29662
|
+
if (uid === mine || uid === 0)
|
|
29663
|
+
return true;
|
|
29664
|
+
const map = (await systemFile("/proc/self/uid_map") ?? "").trim().split(`
|
|
29665
|
+
`).map((line) => line.trim().split(/\s+/).join(" "));
|
|
29666
|
+
if (map[0] === "" || map.length === 1 && map[0] === INITIAL_UID_MAP)
|
|
29667
|
+
return false;
|
|
29668
|
+
const named = Number.parseInt(await systemFile("/proc/sys/kernel/overflowuid") ?? "", 10);
|
|
29669
|
+
return uid === (Number.isNaN(named) ? DEFAULT_OVERFLOW_UID : named);
|
|
29670
|
+
}
|
|
29671
|
+
async function records(file, fields, numbers) {
|
|
29672
|
+
const text = await systemFile(file);
|
|
29673
|
+
if (text === null)
|
|
29674
|
+
return null;
|
|
29675
|
+
const read = [];
|
|
29676
|
+
for (const line of text.split(`
|
|
29677
|
+
`)) {
|
|
29678
|
+
if (line.trim() === "" || line.startsWith("#"))
|
|
29679
|
+
continue;
|
|
29680
|
+
const record = line.split(":");
|
|
29681
|
+
if (record.length < fields || /^[+-]/.test(line))
|
|
29682
|
+
return null;
|
|
29683
|
+
if (numbers.some((at) => !/^\d+$/.test(record[at] ?? "")))
|
|
29684
|
+
return null;
|
|
29685
|
+
read.push(record);
|
|
29686
|
+
}
|
|
29687
|
+
return read;
|
|
29688
|
+
}
|
|
29689
|
+
async function privateGroup(gid, mine) {
|
|
29690
|
+
const [users, groups] = await Promise.all([
|
|
29691
|
+
records("/etc/passwd", 7, [2, 3]),
|
|
29692
|
+
records("/etc/group", 4, [2])
|
|
29693
|
+
]);
|
|
29694
|
+
if (users === null || groups === null)
|
|
29695
|
+
return false;
|
|
29696
|
+
const named = groups.filter((group) => Number(group[2]) === gid);
|
|
29697
|
+
if (named.length === 0)
|
|
29698
|
+
return false;
|
|
29699
|
+
const myNames = new Set(users.filter((user) => Number(user[2]) === mine).map((user) => user[0]));
|
|
29700
|
+
let members = 0;
|
|
29701
|
+
for (const user of users) {
|
|
29702
|
+
if (Number(user[3]) !== gid)
|
|
29703
|
+
continue;
|
|
29704
|
+
if (Number(user[2]) !== mine)
|
|
29705
|
+
return false;
|
|
29706
|
+
members += 1;
|
|
29707
|
+
}
|
|
29708
|
+
for (const group of named) {
|
|
29709
|
+
for (const name of (group[3] ?? "").split(",")) {
|
|
29710
|
+
if (name.trim() === "")
|
|
29711
|
+
continue;
|
|
29712
|
+
if (!myNames.has(name.trim()))
|
|
29713
|
+
return false;
|
|
29714
|
+
members += 1;
|
|
29715
|
+
}
|
|
29716
|
+
}
|
|
29717
|
+
return members > 0;
|
|
29718
|
+
}
|
|
29719
|
+
async function checkOnTheWay(info, what) {
|
|
29720
|
+
const onTheWay = `a directory on the way to ${what}`;
|
|
29721
|
+
const mode = info.mode & 4095;
|
|
29722
|
+
const shown = mode.toString(8).padStart(4, "0");
|
|
29723
|
+
const uid = process.getuid?.();
|
|
29724
|
+
if ((mode & STICKY) === 0 && (mode & 2) !== 0) {
|
|
29725
|
+
throw new Error(`${onTheWay} is mode ${shown}, which lets others replace what is in it; remove their write access (chmod go-w) or set its sticky bit (chmod +t), or keep the login elsewhere`);
|
|
29726
|
+
}
|
|
29727
|
+
if ((mode & STICKY) === 0 && (mode & 16) !== 0 && (uid === undefined || !await privateGroup(info.gid, uid))) {
|
|
29728
|
+
throw new Error(`${onTheWay} is mode ${shown}, and its group, gid ${info.gid}, is not one that /etc/passwd and /etc/group show this user alone is in, so another member may replace what is in it; remove the group's write access (chmod g-w) or set its sticky bit (chmod +t), or keep the login elsewhere`);
|
|
29729
|
+
}
|
|
29730
|
+
if (uid !== undefined && !await safeOwner(info.uid, uid)) {
|
|
29731
|
+
throw new Error(`${onTheWay} is owned by uid ${info.uid}, neither this user (uid ${uid}) nor root; keep the login under directories of this user's own`);
|
|
29732
|
+
}
|
|
29733
|
+
}
|
|
29734
|
+
async function checkLinkOnTheWay(info, what) {
|
|
29735
|
+
const uid = process.getuid?.();
|
|
29736
|
+
if (uid !== undefined && !await safeOwner(info.uid, uid)) {
|
|
29737
|
+
throw new Error(`a link on the way to ${what} is owned by uid ${info.uid}, neither this user (uid ${uid}) nor root; keep the login under directories and links of this user's own`);
|
|
29738
|
+
}
|
|
29739
|
+
}
|
|
29740
|
+
async function lstatOnTheWay(path, what) {
|
|
29741
|
+
try {
|
|
29742
|
+
return await lstat2(path);
|
|
29743
|
+
} catch (error) {
|
|
29744
|
+
if (readErrorCode(error) === "ENOENT")
|
|
29745
|
+
return null;
|
|
29746
|
+
throw refusedBy(error, `read a directory on the way to ${what}`);
|
|
29747
|
+
}
|
|
29748
|
+
}
|
|
29749
|
+
async function walkTheWay(path, what, meet) {
|
|
29750
|
+
const names = (isAbsolute2(path) ? path : `${process.cwd()}/${path}`).split("/");
|
|
29751
|
+
let reached = "/";
|
|
29752
|
+
let info = await lstatOnTheWay(reached, what);
|
|
29753
|
+
let followed = 0;
|
|
29754
|
+
for (let name = names.shift();name !== undefined; name = names.shift()) {
|
|
29755
|
+
if (info === null)
|
|
29756
|
+
return null;
|
|
29757
|
+
if (name === "" || name === ".")
|
|
29758
|
+
continue;
|
|
29759
|
+
if (name === "..") {
|
|
29760
|
+
reached = dirname3(reached);
|
|
29761
|
+
info = await lstatOnTheWay(reached, what);
|
|
29762
|
+
continue;
|
|
29763
|
+
}
|
|
29764
|
+
await meet?.directory(reached, info);
|
|
29765
|
+
const next = reached === "/" ? `/${name}` : `${reached}/${name}`;
|
|
29766
|
+
const here = await lstatOnTheWay(next, what);
|
|
29767
|
+
if (here === null || !here.isSymbolicLink()) {
|
|
29768
|
+
reached = next;
|
|
29769
|
+
info = here;
|
|
29770
|
+
continue;
|
|
29771
|
+
}
|
|
29772
|
+
await meet?.link(reached, here);
|
|
29773
|
+
followed += 1;
|
|
29774
|
+
if (followed > LINKS_FOLLOWED_AT_MOST)
|
|
29775
|
+
throw notARegularFile("a loop of links");
|
|
29776
|
+
let target;
|
|
29777
|
+
try {
|
|
29778
|
+
target = await readlink(next);
|
|
29779
|
+
} catch (error) {
|
|
29780
|
+
const code = readErrorCode(error);
|
|
29781
|
+
if (code !== "EINVAL" && code !== "ENOENT") {
|
|
29782
|
+
throw refusedBy(error, `read a directory on the way to ${what}`);
|
|
29783
|
+
}
|
|
29784
|
+
names.unshift(name);
|
|
29785
|
+
continue;
|
|
29786
|
+
}
|
|
29787
|
+
names.unshift(...target.split("/"));
|
|
29788
|
+
if (isAbsolute2(target)) {
|
|
29789
|
+
reached = "/";
|
|
29790
|
+
info = await lstatOnTheWay(reached, what);
|
|
29791
|
+
}
|
|
29792
|
+
}
|
|
29793
|
+
return info === null ? null : reached;
|
|
29794
|
+
}
|
|
29795
|
+
async function homeReached() {
|
|
29796
|
+
const uid = process.getuid?.();
|
|
29797
|
+
const passwd = await records("/etc/passwd", 7, [2, 3]);
|
|
29798
|
+
let home = passwd?.find((user) => Number(user[2]) === uid)?.[5];
|
|
29799
|
+
if (home === undefined) {
|
|
29800
|
+
try {
|
|
29801
|
+
home = userInfo().homedir;
|
|
29802
|
+
} catch {
|
|
29803
|
+
return null;
|
|
29804
|
+
}
|
|
29805
|
+
}
|
|
29806
|
+
if (!isAbsolute2(home))
|
|
29807
|
+
return null;
|
|
29808
|
+
return await walkTheWay(home, "the home directory").catch(() => null);
|
|
29809
|
+
}
|
|
29810
|
+
async function checkDirectoriesOnTheWay(dir, what) {
|
|
29811
|
+
const home = await homeReached();
|
|
29812
|
+
const aboveHome = (at) => home !== null && home !== at && (at === "/" || home.startsWith(`${at}/`));
|
|
29813
|
+
await walkTheWay(dir, what, {
|
|
29814
|
+
directory: async (at, info) => {
|
|
29815
|
+
if (!aboveHome(at))
|
|
29816
|
+
await checkOnTheWay(info, what);
|
|
29817
|
+
},
|
|
29818
|
+
link: async (inside, info) => {
|
|
29819
|
+
if (!aboveHome(inside))
|
|
29820
|
+
await checkLinkOnTheWay(info, what);
|
|
29821
|
+
}
|
|
29822
|
+
});
|
|
29823
|
+
}
|
|
29824
|
+
async function checkLoginDirectory(dir, absent, what = `the directory of ${DEVICE_LOGIN_FILE_NAMED}`) {
|
|
29825
|
+
let info;
|
|
29826
|
+
try {
|
|
29827
|
+
info = await stat2(dir);
|
|
29828
|
+
} catch (error) {
|
|
29829
|
+
if (absent !== undefined && readErrorCode(error) === "ENOENT")
|
|
29830
|
+
throw absent();
|
|
29831
|
+
throw refusedBy(error, `read ${what}`);
|
|
29832
|
+
}
|
|
29833
|
+
checkPrivate(info, what, 18, "lets others replace the login in it; run chmod 700 on it", "keep the login in a directory of this user's own");
|
|
29834
|
+
await checkDirectoriesOnTheWay(dir, what);
|
|
29835
|
+
}
|
|
29836
|
+
function notARegularFile(there) {
|
|
29837
|
+
const what = typeof there === "string" ? there : there.isDirectory() ? "a directory" : there.isFIFO() ? "a named pipe" : there.isSocket() ? "a socket" : there.isCharacterDevice() || there.isBlockDevice() ? "a device" : "something";
|
|
29838
|
+
return new Error(`${DEVICE_LOGIN_FILE_NAMED} is ${what}, not a regular file, so no login can be kept in its place; remove it, or set ${DEVICE_LOGIN_FILE_VAR} to a file's path`);
|
|
29839
|
+
}
|
|
29840
|
+
function refusedBy(error, doing) {
|
|
29841
|
+
const code = readErrorCode(error);
|
|
29842
|
+
if (code === "ENXIO")
|
|
29843
|
+
return notARegularFile("a socket or a device");
|
|
29844
|
+
if (code === "ELOOP")
|
|
29845
|
+
return notARegularFile("a loop of links");
|
|
29846
|
+
if (code === "ENOTDIR") {
|
|
29847
|
+
return new Error(`${DEVICE_LOGIN_FILE_NAMED} has a file, not a directory, in its path, so no login can be kept there; set ${DEVICE_LOGIN_FILE_VAR} to a path in a directory`);
|
|
29848
|
+
}
|
|
29849
|
+
return new Error(`${doing}: ${code}`);
|
|
29850
|
+
}
|
|
29851
|
+
async function deviceLoginDirectory(path) {
|
|
29852
|
+
const dir = dirname3(path);
|
|
29853
|
+
try {
|
|
29854
|
+
await mkdir(dir, { recursive: true, mode: 448 });
|
|
29855
|
+
} catch (error) {
|
|
29856
|
+
throw refusedBy(error, `make the directory of ${DEVICE_LOGIN_FILE_NAMED}`);
|
|
29857
|
+
}
|
|
29858
|
+
await checkLoginDirectory(dir);
|
|
29859
|
+
}
|
|
29860
|
+
async function deviceLoginPlace(path) {
|
|
29861
|
+
await deviceLoginDirectory(path);
|
|
29862
|
+
const dir = dirname3(path);
|
|
29863
|
+
try {
|
|
29864
|
+
await access(dir, constants2.W_OK | constants2.X_OK);
|
|
29865
|
+
} catch (error) {
|
|
29866
|
+
const code = readErrorCode(error);
|
|
29867
|
+
throw new Error(`this user cannot enter and write to the directory of ${DEVICE_LOGIN_FILE_NAMED}: ${code}${code === "EACCES" ? "; run chmod 700 on it" : ""}`);
|
|
29868
|
+
}
|
|
29869
|
+
let info;
|
|
29870
|
+
try {
|
|
29871
|
+
info = await stat2(path);
|
|
29872
|
+
} catch (error) {
|
|
29873
|
+
if (readErrorCode(error) === "ENOENT")
|
|
29874
|
+
return;
|
|
29875
|
+
throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
|
|
29876
|
+
}
|
|
29877
|
+
if (!info.isFile())
|
|
29878
|
+
throw notARegularFile(info);
|
|
29879
|
+
}
|
|
29880
|
+
var LOGIN_READ = constants2.O_RDONLY | constants2.O_NONBLOCK | constants2.O_NOCTTY;
|
|
29881
|
+
var LINKS_FOLLOWED_AT_MOST = 40;
|
|
29882
|
+
async function checkLinkDirectories(path, absent) {
|
|
29883
|
+
let checked = dirname3(path);
|
|
29884
|
+
let at = path;
|
|
29885
|
+
for (let followed = 0;; followed += 1) {
|
|
29886
|
+
if (dirname3(at) !== checked) {
|
|
29887
|
+
checked = dirname3(at);
|
|
29888
|
+
await checkLoginDirectory(checked, absent, `the directory of a file ${DEVICE_LOGIN_FILE_NAMED} links to`);
|
|
29889
|
+
}
|
|
29890
|
+
let info;
|
|
29891
|
+
try {
|
|
29892
|
+
info = await lstat2(at);
|
|
29893
|
+
} catch (error) {
|
|
29894
|
+
if (readErrorCode(error) === "ENOENT")
|
|
29895
|
+
return;
|
|
29896
|
+
throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
|
|
29897
|
+
}
|
|
29898
|
+
if (!info.isSymbolicLink())
|
|
29899
|
+
return;
|
|
29900
|
+
if (followed === LINKS_FOLLOWED_AT_MOST)
|
|
29901
|
+
throw notARegularFile("a loop of links");
|
|
29902
|
+
let target;
|
|
29903
|
+
try {
|
|
29904
|
+
target = await readlink(at);
|
|
29905
|
+
} catch (error) {
|
|
29906
|
+
const code = readErrorCode(error);
|
|
29907
|
+
if (code === "EINVAL" || code === "ENOENT")
|
|
29908
|
+
return;
|
|
29909
|
+
throw refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
|
|
29910
|
+
}
|
|
29911
|
+
at = isAbsolute2(target) ? target : `${dirname3(at)}/${target}`;
|
|
29912
|
+
}
|
|
29913
|
+
}
|
|
29914
|
+
async function readDeviceLogin(path) {
|
|
29915
|
+
const absent = () => new Error(`this machine has no device login: ${DEVICE_LOGIN_FILE_NAMED} is not there; log this machine in with: ${DEVICE_LOGIN_COMMAND}`);
|
|
29916
|
+
const failed = (error) => new Error(`read ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
|
|
29917
|
+
await checkLoginDirectory(dirname3(path), absent);
|
|
29918
|
+
await checkLinkDirectories(path, absent);
|
|
29919
|
+
let handle;
|
|
29920
|
+
try {
|
|
29921
|
+
handle = await open2(path, LOGIN_READ);
|
|
29922
|
+
} catch (error) {
|
|
29923
|
+
throw readErrorCode(error) === "ENOENT" ? absent() : refusedBy(error, `read ${DEVICE_LOGIN_FILE_NAMED}`);
|
|
29924
|
+
}
|
|
29925
|
+
let data;
|
|
29926
|
+
try {
|
|
29927
|
+
const info = await handle.stat().catch((error) => {
|
|
29928
|
+
throw failed(error);
|
|
29929
|
+
});
|
|
29930
|
+
if (!info.isFile())
|
|
29931
|
+
throw notARegularFile(info);
|
|
29932
|
+
checkPrivate(info, DEVICE_LOGIN_FILE_NAMED, 63, "lets others read the login's key; run chmod 600 on it", `remove it and log in again with: ${DEVICE_LOGIN_COMMAND}`);
|
|
29933
|
+
if (info.size > DEVICE_LOGIN_MOST_BYTES) {
|
|
29934
|
+
throw new Error(`${DEVICE_LOGIN_FILE_NAMED} is not a device login: it is over ${DEVICE_LOGIN_MOST_BYTES / 1024} KiB, many times a login's size; set ${DEVICE_LOGIN_FILE_VAR} to the login's own file, or log this machine in again with: ${DEVICE_LOGIN_COMMAND}`);
|
|
29935
|
+
}
|
|
29936
|
+
data = await handle.readFile("utf8").catch((error) => {
|
|
29937
|
+
throw failed(error);
|
|
29938
|
+
});
|
|
29939
|
+
} catch (error) {
|
|
29940
|
+
await handle.close().catch(() => {});
|
|
29941
|
+
throw error;
|
|
29942
|
+
}
|
|
29943
|
+
await handle.close().catch((error) => {
|
|
29944
|
+
throw failed(error);
|
|
29945
|
+
});
|
|
29946
|
+
let json;
|
|
29947
|
+
try {
|
|
29948
|
+
const parsed = JSON.parse(data);
|
|
29949
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
|
|
29950
|
+
throw new Error;
|
|
29951
|
+
json = parsed;
|
|
29952
|
+
} catch {
|
|
29953
|
+
throw new Error(`${DEVICE_LOGIN_FILE_NAMED} is not a device login: it does not read as one JSON object of the login's fields`);
|
|
29954
|
+
}
|
|
29955
|
+
const credentialId = member(json, "credential_id");
|
|
29956
|
+
const refreshToken = member(json, "refresh_token");
|
|
29957
|
+
const broker = member(json, "broker");
|
|
29958
|
+
const expiresAt = new Date(member(json, "expires_at"));
|
|
29959
|
+
if (credentialId === "" || refreshToken === "" || broker === "" || Number.isNaN(expiresAt.getTime())) {
|
|
29960
|
+
throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: credential_id, refresh_token, broker and an RFC 3339 expires_at are all required`);
|
|
29961
|
+
}
|
|
29962
|
+
let key;
|
|
29963
|
+
try {
|
|
29964
|
+
key = createPrivateKey({
|
|
29965
|
+
key: Buffer.from(member(json, "key"), "base64"),
|
|
29966
|
+
format: "der",
|
|
29967
|
+
type: "pkcs8"
|
|
29968
|
+
});
|
|
29969
|
+
} catch {
|
|
29970
|
+
throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a base64 PKCS#8 key`);
|
|
29971
|
+
}
|
|
29972
|
+
if (key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
|
|
29973
|
+
throw new Error(`${DEVICE_LOGIN_FILE_NAMED}: key is not a P-256 key`);
|
|
29974
|
+
}
|
|
29975
|
+
const accessToken = member(json, "access_token");
|
|
29976
|
+
const accessText = member(json, "access_expires_at");
|
|
29977
|
+
const accessExpiresAt = accessToken === "" || accessText === "" ? null : new Date(accessText);
|
|
29978
|
+
const accessUsable = accessExpiresAt !== null && !Number.isNaN(accessExpiresAt.getTime());
|
|
29979
|
+
return {
|
|
29980
|
+
key,
|
|
29981
|
+
credentialId,
|
|
29982
|
+
refreshToken: holdSecret(refreshToken, expiresAt),
|
|
29983
|
+
expiresAt,
|
|
29984
|
+
broker,
|
|
29985
|
+
accessToken: accessUsable ? holdSecret(accessToken, accessExpiresAt) : "",
|
|
29986
|
+
accessExpiresAt: accessUsable ? accessExpiresAt : null
|
|
29987
|
+
};
|
|
29988
|
+
}
|
|
29989
|
+
function lockLost(then = "this trade refreshes and keeps nothing, and the next one reads the login again") {
|
|
29990
|
+
return new Error(`the lock beside ${DEVICE_LOGIN_FILE_NAMED} is no longer this process's: it stopped for over ${DEVICE_LOGIN_STALE_LOCK_MS / 1000} s while it held it (a laptop asleep, a process stopped), and another process took it; ${then}`);
|
|
29991
|
+
}
|
|
29992
|
+
|
|
29993
|
+
class KeptCopyError extends Error {
|
|
29994
|
+
suffix;
|
|
29995
|
+
constructor(suffix, failed) {
|
|
29996
|
+
super(`${messageOf(failed)}; a copy of the new login is kept beside ${DEVICE_LOGIN_FILE_NAMED}, under that file's name with ${suffix} added: move the copy over the file to use the login`);
|
|
29997
|
+
this.suffix = suffix;
|
|
29998
|
+
}
|
|
29999
|
+
}
|
|
30000
|
+
async function keptCopy(temp, path, error) {
|
|
30001
|
+
const suffix = `.kept-${randomUUID3()}`;
|
|
30002
|
+
try {
|
|
30003
|
+
await rename2(temp, `${path}${suffix}`);
|
|
30004
|
+
} catch {
|
|
30005
|
+
return error;
|
|
30006
|
+
}
|
|
30007
|
+
return new KeptCopyError(suffix, error);
|
|
30008
|
+
}
|
|
30009
|
+
async function saveDeviceLogin(path, login, held, keep = false) {
|
|
30010
|
+
const dir = dirname3(path);
|
|
30011
|
+
const data = JSON.stringify({
|
|
30012
|
+
key: login.key.export({ format: "der", type: "pkcs8" }).toString("base64"),
|
|
30013
|
+
credential_id: login.credentialId,
|
|
30014
|
+
refresh_token: login.refreshToken,
|
|
30015
|
+
expires_at: login.expiresAt.toISOString(),
|
|
30016
|
+
broker: login.broker,
|
|
30017
|
+
...login.accessToken === "" || login.accessExpiresAt === null ? {} : {
|
|
30018
|
+
access_token: login.accessToken,
|
|
30019
|
+
access_expires_at: login.accessExpiresAt.toISOString()
|
|
30020
|
+
}
|
|
30021
|
+
});
|
|
30022
|
+
await deviceLoginPlace(path);
|
|
30023
|
+
await removeUntouched(dir, isTemporaryCopy);
|
|
30024
|
+
await removeLeftLocks(path);
|
|
30025
|
+
const temp = join7(dir, `.device-login-${randomUUID3()}.json.tmp`);
|
|
30026
|
+
const saveFailed = (error) => new Error(`save ${DEVICE_LOGIN_FILE_NAMED}: ${readErrorCode(error)}`);
|
|
30027
|
+
let whole = false;
|
|
30028
|
+
try {
|
|
30029
|
+
try {
|
|
30030
|
+
const handle = await open2(temp, "wx", 384);
|
|
30031
|
+
try {
|
|
30032
|
+
await handle.writeFile(data);
|
|
30033
|
+
await handle.sync();
|
|
30034
|
+
} finally {
|
|
30035
|
+
await handle.close();
|
|
30036
|
+
}
|
|
30037
|
+
} catch (error) {
|
|
30038
|
+
throw saveFailed(error);
|
|
30039
|
+
}
|
|
30040
|
+
whole = true;
|
|
30041
|
+
if (!await held())
|
|
30042
|
+
throw keep ? lockLost("the new login was not kept in its place") : lockLost();
|
|
30043
|
+
await rename2(temp, path).catch((error) => {
|
|
30044
|
+
throw saveFailed(error);
|
|
30045
|
+
});
|
|
30046
|
+
} catch (error) {
|
|
30047
|
+
throw keep && whole ? await keptCopy(temp, path, error) : error;
|
|
30048
|
+
} finally {
|
|
30049
|
+
await rm2(temp, { force: true }).catch(() => {});
|
|
30050
|
+
}
|
|
30051
|
+
try {
|
|
30052
|
+
const handle = await open2(dir, "r");
|
|
30053
|
+
try {
|
|
30054
|
+
await handle.sync();
|
|
30055
|
+
} finally {
|
|
30056
|
+
await handle.close();
|
|
30057
|
+
}
|
|
30058
|
+
} catch {}
|
|
30059
|
+
}
|
|
30060
|
+
|
|
30061
|
+
// ../cipher-client/src/dpop.ts
|
|
30062
|
+
import {
|
|
30063
|
+
createHash,
|
|
30064
|
+
createPrivateKey as createPrivateKey2,
|
|
30065
|
+
createPublicKey,
|
|
30066
|
+
generateKeyPairSync,
|
|
30067
|
+
randomUUID as randomUUID4,
|
|
30068
|
+
sign as sign2
|
|
30069
|
+
} from "crypto";
|
|
30070
|
+
var ALGORITHM = "ES256";
|
|
30071
|
+
var CONNECTION_PROOF_METHOD = "CONNECT";
|
|
30072
|
+
var CONNECTION_PROOF_TARGET = "nats:connect";
|
|
30073
|
+
function targetUri(url) {
|
|
30074
|
+
const parsed = new URL(url);
|
|
30075
|
+
parsed.search = "";
|
|
30076
|
+
parsed.hash = "";
|
|
30077
|
+
return parsed.toString();
|
|
30078
|
+
}
|
|
30079
|
+
function dpopKey(privateKey, publicJwk) {
|
|
30080
|
+
const header = Buffer.from(JSON.stringify({ typ: "dpop+jwt", alg: ALGORITHM, jwk: publicJwk })).toString("base64url");
|
|
30081
|
+
const signed = (htm, htu, nonce, accessToken) => {
|
|
30082
|
+
const claims = {
|
|
30083
|
+
jti: randomUUID4(),
|
|
30084
|
+
htm,
|
|
30085
|
+
htu,
|
|
30086
|
+
iat: Math.floor(Date.now() / 1000)
|
|
30087
|
+
};
|
|
30088
|
+
if (nonce !== undefined && nonce !== "")
|
|
30089
|
+
claims["nonce"] = nonce;
|
|
30090
|
+
if (accessToken !== undefined && accessToken !== "") {
|
|
30091
|
+
claims["ath"] = createHash("sha256").update(accessToken).digest("base64url");
|
|
28641
30092
|
}
|
|
28642
|
-
|
|
28643
|
-
|
|
28644
|
-
|
|
28645
|
-
|
|
28646
|
-
|
|
28647
|
-
|
|
28648
|
-
|
|
28649
|
-
|
|
28650
|
-
|
|
28651
|
-
|
|
28652
|
-
|
|
30093
|
+
const signingInput = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`;
|
|
30094
|
+
const signature = sign2("sha256", Buffer.from(signingInput), {
|
|
30095
|
+
key: privateKey,
|
|
30096
|
+
dsaEncoding: "ieee-p1363"
|
|
30097
|
+
});
|
|
30098
|
+
return `${signingInput}.${signature.toString("base64url")}`;
|
|
30099
|
+
};
|
|
30100
|
+
return {
|
|
30101
|
+
publicJwk,
|
|
30102
|
+
async proof(request) {
|
|
30103
|
+
return signed(request.method.toUpperCase(), targetUri(request.url), request.nonce, request.accessToken);
|
|
30104
|
+
},
|
|
30105
|
+
connectionProof({ accessToken, nonce }) {
|
|
30106
|
+
if (accessToken === "")
|
|
30107
|
+
throw new Error("no access token to prove a NATS connection for");
|
|
30108
|
+
if (nonce === "")
|
|
30109
|
+
throw new Error("the NATS server sent no nonce to sign");
|
|
30110
|
+
return signed(CONNECTION_PROOF_METHOD, CONNECTION_PROOF_TARGET, nonce, accessToken);
|
|
28653
30111
|
}
|
|
28654
|
-
|
|
28655
|
-
|
|
28656
|
-
|
|
30112
|
+
};
|
|
30113
|
+
}
|
|
30114
|
+
function publicJwkOf(privateKey, name) {
|
|
30115
|
+
const { kty, crv, x, y } = createPublicKey(privateKey).export({ format: "jwk" });
|
|
30116
|
+
if (kty !== "EC" || crv !== "P-256" || typeof x !== "string" || typeof y !== "string") {
|
|
30117
|
+
throw new Error(`${name} is not a P-256 key (${kty} ${crv ?? "with no curve"}), and a DPoP proof is signed ${ALGORITHM}`);
|
|
30118
|
+
}
|
|
30119
|
+
return { kty, crv, x, y };
|
|
30120
|
+
}
|
|
30121
|
+
async function newDpopKey() {
|
|
30122
|
+
const { privateKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
|
|
30123
|
+
return dpopKeyOf(privateKey, "this process's key");
|
|
30124
|
+
}
|
|
30125
|
+
function dpopKeyOf(privateKey, name) {
|
|
30126
|
+
return dpopKey(privateKey, publicJwkOf(privateKey, name));
|
|
30127
|
+
}
|
|
30128
|
+
async function importDpopKey(pkcs8Pem, name) {
|
|
30129
|
+
let privateKey;
|
|
30130
|
+
try {
|
|
30131
|
+
privateKey = createPrivateKey2(pkcs8Pem);
|
|
30132
|
+
} catch {
|
|
30133
|
+
throw new Error(`read ${name}: it does not parse as a PKCS#8 PEM private key`);
|
|
30134
|
+
}
|
|
30135
|
+
return dpopKey(privateKey, publicJwkOf(privateKey, name));
|
|
30136
|
+
}
|
|
30137
|
+
|
|
30138
|
+
// ../cipher-client/src/device-login.ts
|
|
30139
|
+
var BROKER_SETTING = "AGENT_SECRETS_URL";
|
|
30140
|
+
var ACCESS_MARGIN_MS = 2 * TRADE_ATTEMPT_MS;
|
|
30141
|
+
var BROKER_REQUEST_MS = TRADE_ATTEMPT_MS / 2;
|
|
30142
|
+
var DEFAULT_POLL_SECONDS = 5;
|
|
30143
|
+
var LEAST_POLL_SECONDS = 1;
|
|
30144
|
+
var MOST_POLL_SECONDS = 60;
|
|
30145
|
+
var MOST_LIFETIME_SECONDS = 3600;
|
|
30146
|
+
var LOOPBACK_HOST = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
|
|
30147
|
+
var UNPRINTABLE = /[\p{Cc}\p{Cf}]/u;
|
|
30148
|
+
function deviceLoginSessionName(thumbprint) {
|
|
30149
|
+
return `device-login-${thumbprint.slice(0, 12)}`;
|
|
30150
|
+
}
|
|
30151
|
+
function deviceLoginHost(name) {
|
|
30152
|
+
const labels = name.trim().toLowerCase().replace(/[^a-z0-9.-]+/g, "-").split(".").map((label) => label.replace(/^-+/, "").slice(0, 63).replace(/-+$/, "")).filter((label) => label !== "");
|
|
30153
|
+
const host = labels.join(".").slice(0, 253).replace(/[.-]+$/, "");
|
|
30154
|
+
return host === "" ? "device" : host;
|
|
30155
|
+
}
|
|
30156
|
+
function deviceLoginBroker(brokerUrl) {
|
|
30157
|
+
const trimmed = withoutTrailingSlashes(brokerUrl.trim());
|
|
30158
|
+
if (!isHttpUrl(trimmed))
|
|
30159
|
+
throw new Error(`${BROKER_SETTING} is not an http or https URL`);
|
|
30160
|
+
const { protocol, hostname } = new URL(trimmed);
|
|
30161
|
+
if (protocol === "http:" && !LOOPBACK_HOST.test(hostname)) {
|
|
30162
|
+
throw new Error(`${BROKER_SETTING} is an http URL of a host off this machine's loopback: a device login sends its refresh token and access tokens to the broker, so it takes https, or http to 127.0.0.1, ::1 or localhost`);
|
|
30163
|
+
}
|
|
30164
|
+
return holdUrlUserinfo(trimmed);
|
|
30165
|
+
}
|
|
30166
|
+
function loginDpopKey(key) {
|
|
30167
|
+
return dpopKeyOf(key, "this machine's device login key");
|
|
30168
|
+
}
|
|
30169
|
+
function printable(value, what, endpoint) {
|
|
30170
|
+
if (UNPRINTABLE.test(value)) {
|
|
30171
|
+
throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered a ${what} holding a control or format character, which this machine does not print`);
|
|
30172
|
+
}
|
|
30173
|
+
return value;
|
|
30174
|
+
}
|
|
30175
|
+
function page(uri, endpoint) {
|
|
30176
|
+
if (!isHttpUrl(uri)) {
|
|
30177
|
+
throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered a page to type the code in that is no http or https URL`);
|
|
30178
|
+
}
|
|
30179
|
+
return printable(uri, "page to type the code in", endpoint);
|
|
30180
|
+
}
|
|
30181
|
+
async function withDeviceLoginLock(path, work, options = {}) {
|
|
30182
|
+
await deviceLoginDirectory(path);
|
|
30183
|
+
return await withLoginLock(path, DEVICE_LOGIN_FILE_NAMED, work, options);
|
|
30184
|
+
}
|
|
30185
|
+
function brokerConfiguration(brokerUrl, fetchImpl, proved) {
|
|
30186
|
+
const config = new Configuration({
|
|
30187
|
+
issuer: brokerUrl,
|
|
30188
|
+
token_endpoint: brokerUrl + TOKEN_PATH,
|
|
30189
|
+
device_authorization_endpoint: brokerUrl + DEVICE_AUTHORIZATION_PATH
|
|
30190
|
+
}, MACHINE_LOGIN_CLIENT_ID, {}, None2());
|
|
30191
|
+
if (new URL(brokerUrl).protocol === "http:")
|
|
28657
30192
|
allowInsecureRequests2(config);
|
|
28658
|
-
|
|
30193
|
+
config[customFetch2] = (url, options) => {
|
|
30194
|
+
const deadline = AbortSignal.timeout(BROKER_REQUEST_MS);
|
|
30195
|
+
return proved === undefined ? fetchImpl(url, requestInit(options, deadline, options.headers)) : sendWithProof({ key: proved.key, fetch: fetchImpl, nonce: proved.nonce }, url, options, deadline);
|
|
30196
|
+
};
|
|
30197
|
+
return config;
|
|
30198
|
+
}
|
|
30199
|
+
function loginOf(key, broker, answered, now) {
|
|
30200
|
+
const endpoint = broker + TOKEN_PATH;
|
|
30201
|
+
const credentialId = typeof answered["credential_id"] === "string" ? answered["credential_id"] : "";
|
|
30202
|
+
const expiresAt = new Date(typeof answered["credential_expires_at"] === "string" ? answered["credential_expires_at"] : "");
|
|
30203
|
+
const refreshToken = answered.refresh_token ?? "";
|
|
30204
|
+
const seconds = Math.min(answered.expires_in ?? 0, MOST_LIFETIME_SECONDS);
|
|
30205
|
+
if (credentialId === "" || Number.isNaN(expiresAt.getTime()) || refreshToken === "" || !(seconds > 0) || answered.token_type.toLowerCase() !== TOKEN_TYPE_DPOP.toLowerCase()) {
|
|
30206
|
+
throw new BrokerTradeFailedError(`the secrets broker at ${urlForText(endpoint, BROKER_URL_SETTING)} answered the device login without a credential_id, an RFC 3339 credential_expires_at, a refresh_token, a positive expires_in or a DPoP-bound token`);
|
|
30207
|
+
}
|
|
30208
|
+
const accessExpiresAt = new Date(now + seconds * 1000);
|
|
30209
|
+
return {
|
|
30210
|
+
key,
|
|
30211
|
+
credentialId: printable(credentialId, "credential_id", endpoint),
|
|
30212
|
+
refreshToken: holdSecret(refreshToken, expiresAt),
|
|
30213
|
+
expiresAt,
|
|
30214
|
+
broker,
|
|
30215
|
+
accessToken: holdSecret(answered.access_token, accessExpiresAt),
|
|
30216
|
+
accessExpiresAt
|
|
30217
|
+
};
|
|
30218
|
+
}
|
|
30219
|
+
async function startDeviceLogin(options) {
|
|
30220
|
+
const brokerUrl = deviceLoginBroker(options.brokerUrl);
|
|
30221
|
+
const endpoint = brokerUrl + DEVICE_AUTHORIZATION_PATH;
|
|
30222
|
+
const person = options.person.trim();
|
|
30223
|
+
const { privateKey } = generateKeyPairSync2("ec", { namedCurve: "P-256" });
|
|
30224
|
+
const jwk = loginDpopKey(privateKey).publicJwk;
|
|
30225
|
+
const thumbprint = await calculateJwkThumbprint(jwk);
|
|
30226
|
+
const iat = Math.floor(Date.now() / 1000);
|
|
30227
|
+
const claims = {
|
|
30228
|
+
iss: thumbprint,
|
|
30229
|
+
aud: brokerUrl,
|
|
30230
|
+
jti: randomUUID5(),
|
|
30231
|
+
iat,
|
|
30232
|
+
exp: iat + REQUEST_OBJECT_LIFETIME_SECONDS,
|
|
30233
|
+
authorization_details: [{ type: LAUNCHER_CREDENTIAL_DETAIL, identifier: options.host }],
|
|
30234
|
+
login_hint: person
|
|
30235
|
+
};
|
|
30236
|
+
const request = await new CompactSign(new TextEncoder().encode(JSON.stringify(claims))).setProtectedHeader({ alg: "ES256", typ: REQUEST_OBJECT_TYPE, jwk }).sign(privateKey);
|
|
30237
|
+
const config = brokerConfiguration(brokerUrl, options.fetch ?? fetch);
|
|
30238
|
+
let answered;
|
|
30239
|
+
try {
|
|
30240
|
+
answered = await initiateDeviceAuthorization(config, {
|
|
30241
|
+
scope: MACHINE_LOGIN_SCOPE,
|
|
30242
|
+
dpop_jkt: thumbprint,
|
|
30243
|
+
request
|
|
30244
|
+
});
|
|
30245
|
+
} catch (error) {
|
|
30246
|
+
throw brokerRefusal("ask for a code for", "this machine's device login", endpoint, error);
|
|
30247
|
+
}
|
|
30248
|
+
const expiresAt = new Date(Date.now() + Math.min(answered.expires_in, MOST_LIFETIME_SECONDS) * 1000);
|
|
30249
|
+
return {
|
|
30250
|
+
brokerUrl,
|
|
30251
|
+
person,
|
|
30252
|
+
userCode: printable(answered.user_code, "user code", endpoint),
|
|
30253
|
+
verificationUri: page(answered.verification_uri, endpoint),
|
|
30254
|
+
verificationUriComplete: answered.verification_uri_complete === undefined ? undefined : page(answered.verification_uri_complete, endpoint),
|
|
30255
|
+
expiresAt,
|
|
30256
|
+
intervalSeconds: Math.min(Math.max(answered.interval ?? DEFAULT_POLL_SECONDS, LEAST_POLL_SECONDS), MOST_POLL_SECONDS),
|
|
30257
|
+
deviceCode: holdSecret(answered.device_code, expiresAt),
|
|
30258
|
+
key: privateKey
|
|
30259
|
+
};
|
|
30260
|
+
}
|
|
30261
|
+
async function finishDeviceLogin(started, options) {
|
|
30262
|
+
const wait = options.sleep ?? ((ms) => sleep2(ms, undefined, true));
|
|
30263
|
+
const config = brokerConfiguration(started.brokerUrl, options.fetch ?? fetch, {
|
|
30264
|
+
key: loginDpopKey(started.key),
|
|
30265
|
+
nonce: { value: "" }
|
|
30266
|
+
});
|
|
30267
|
+
const endpoint = started.brokerUrl + TOKEN_PATH;
|
|
30268
|
+
const expired = new Error(`the code ${started.userCode} expired before ${started.person} approved this machine; ask again with: ${DEVICE_LOGIN_COMMAND}`);
|
|
30269
|
+
let interval = started.intervalSeconds;
|
|
30270
|
+
while (true) {
|
|
30271
|
+
if (Date.now() >= started.expiresAt.getTime())
|
|
30272
|
+
throw expired;
|
|
30273
|
+
await wait(interval * 1000);
|
|
28659
30274
|
let answered;
|
|
28660
30275
|
try {
|
|
28661
|
-
answered = await genericGrantRequest(config,
|
|
30276
|
+
answered = await genericGrantRequest(config, GRANT_TYPE_DEVICE_CODE, {
|
|
30277
|
+
device_code: started.deviceCode
|
|
30278
|
+
});
|
|
28662
30279
|
} catch (error) {
|
|
28663
|
-
|
|
30280
|
+
const code = error instanceof ResponseBodyError ? error.error : "";
|
|
30281
|
+
if (code === "access_denied") {
|
|
30282
|
+
throw new Error(`this machine's device login was denied, not approved as ${started.person}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
|
|
30283
|
+
}
|
|
30284
|
+
if (code === "expired_token" || code === "invalid_grant")
|
|
30285
|
+
throw expired;
|
|
30286
|
+
if (code === "slow_down")
|
|
30287
|
+
interval += 5;
|
|
30288
|
+
const status = statusOf(error);
|
|
30289
|
+
const pollAgain = code === "authorization_pending" || code === "slow_down" || status === 0 || status === 429 || status >= 500;
|
|
30290
|
+
if (!pollAgain) {
|
|
30291
|
+
const refusal = brokerRefusal("poll the code of", "this machine's device login", endpoint, error);
|
|
30292
|
+
throw new Error(`${refusal.message}; ask again with: ${DEVICE_LOGIN_COMMAND}`);
|
|
30293
|
+
}
|
|
30294
|
+
continue;
|
|
28664
30295
|
}
|
|
28665
|
-
|
|
28666
|
-
|
|
28667
|
-
|
|
28668
|
-
|
|
28669
|
-
|
|
28670
|
-
|
|
28671
|
-
|
|
28672
|
-
|
|
30296
|
+
const login = loginOf(started.key, started.brokerUrl, answered, Date.now());
|
|
30297
|
+
let replaced = "";
|
|
30298
|
+
let saved = false;
|
|
30299
|
+
try {
|
|
30300
|
+
await withDeviceLoginLock(options.path, async (held) => {
|
|
30301
|
+
replaced = await readDeviceLogin(options.path).then((kept) => kept.credentialId, () => "");
|
|
30302
|
+
await saveDeviceLogin(options.path, login, held, true);
|
|
30303
|
+
saved = true;
|
|
28673
30304
|
});
|
|
30305
|
+
} catch (error) {
|
|
30306
|
+
if (saved) {
|
|
30307
|
+
const lockLeft = `this process could not let go of the lock beside ${DEVICE_LOGIN_FILE_NAMED} (${messageOf(error)}); another process takes it over once it is ${DEVICE_LOGIN_STALE_LOCK_MS / 1000} s old`;
|
|
30308
|
+
return { ...login, replaced, lockLeft };
|
|
30309
|
+
}
|
|
30310
|
+
const revoke = `Machine logins on ${started.verificationUri}`;
|
|
30311
|
+
throw new Error(error instanceof KeptCopyError ? `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it in its place: ${messageOf(error)}, which then needs no revoke. Where the copy is not used, delete it, since it holds the login's key and refresh token, and revoke the credential in ${revoke}: it stays live until it lapses or is revoked` : `${started.person} approved this machine's launcher credential ${login.credentialId}, but this machine could not keep it: ${messageOf(error)}. The credential stays live until it lapses or is revoked: revoke it in ${revoke}, and log in again with: ${DEVICE_LOGIN_COMMAND}`, { cause: error });
|
|
28674
30312
|
}
|
|
28675
|
-
|
|
28676
|
-
const said = status === 0 ? errorClass(error) : `HTTP ${status}: ${errorClass(error)}`;
|
|
28677
|
-
return new BrokerTradeFailedError(`trade ${this.#subject.describe()} at ${urlForText(endpoint, BROKER_URL_SETTING)}: ${said}`);
|
|
30313
|
+
return { ...login, replaced, lockLeft: "" };
|
|
28678
30314
|
}
|
|
28679
|
-
|
|
28680
|
-
|
|
28681
|
-
|
|
28682
|
-
|
|
28683
|
-
|
|
28684
|
-
|
|
28685
|
-
|
|
28686
|
-
|
|
28687
|
-
|
|
28688
|
-
this.#nonce = given;
|
|
28689
|
-
if (answer.status === 400 && given !== "") {
|
|
28690
|
-
const body = await answer.clone().json().catch(() => null);
|
|
28691
|
-
const asked = typeof body === "object" && body !== null && "error" in body && body.error === "use_dpop_nonce";
|
|
28692
|
-
if (asked)
|
|
28693
|
-
answer = await send();
|
|
28694
|
-
}
|
|
28695
|
-
raw.body = await answer.clone().json().catch(() => {
|
|
28696
|
-
return;
|
|
28697
|
-
});
|
|
28698
|
-
return answer;
|
|
30315
|
+
}
|
|
30316
|
+
|
|
30317
|
+
class DeviceLoginIdentity {
|
|
30318
|
+
#path;
|
|
30319
|
+
#brokerUrl;
|
|
30320
|
+
#key;
|
|
30321
|
+
constructor(options) {
|
|
30322
|
+
this.#path = options.path;
|
|
30323
|
+
this.#brokerUrl = deviceLoginBroker(options.brokerUrl);
|
|
28699
30324
|
}
|
|
28700
|
-
|
|
28701
|
-
|
|
28702
|
-
|
|
28703
|
-
|
|
28704
|
-
|
|
28705
|
-
|
|
28706
|
-
|
|
28707
|
-
|
|
28708
|
-
|
|
28709
|
-
|
|
28710
|
-
if (
|
|
28711
|
-
|
|
30325
|
+
describe() {
|
|
30326
|
+
return `this machine's device login (${DEVICE_LOGIN_FILE_NAMED})`;
|
|
30327
|
+
}
|
|
30328
|
+
async key() {
|
|
30329
|
+
return (await this.#loaded()).key;
|
|
30330
|
+
}
|
|
30331
|
+
async thumbprint() {
|
|
30332
|
+
return (await this.#loaded()).thumbprint;
|
|
30333
|
+
}
|
|
30334
|
+
#loaded() {
|
|
30335
|
+
if (this.#key === undefined) {
|
|
30336
|
+
const loading = readDeviceLogin(this.#path).then(async ({ key }) => {
|
|
30337
|
+
const dpop = loginDpopKey(key);
|
|
30338
|
+
return { key: dpop, thumbprint: await calculateJwkThumbprint(dpop.publicJwk) };
|
|
30339
|
+
});
|
|
30340
|
+
this.#key = loading;
|
|
30341
|
+
loading.catch(() => {
|
|
30342
|
+
if (this.#key === loading)
|
|
30343
|
+
this.#key = undefined;
|
|
30344
|
+
});
|
|
28712
30345
|
}
|
|
28713
|
-
|
|
28714
|
-
|
|
28715
|
-
|
|
28716
|
-
|
|
28717
|
-
|
|
28718
|
-
|
|
30346
|
+
return this.#key;
|
|
30347
|
+
}
|
|
30348
|
+
async spend(trade, signal) {
|
|
30349
|
+
const { thumbprint } = await this.#loaded();
|
|
30350
|
+
return await withDeviceLoginLock(this.#path, async (held) => {
|
|
30351
|
+
let login = await readDeviceLogin(this.#path);
|
|
30352
|
+
if (withoutTrailingSlashes(login.broker) !== this.#brokerUrl) {
|
|
30353
|
+
throw new Error(`${DEVICE_LOGIN_FILE_NAMED} was made at another secrets broker than ${BROKER_SETTING} names; log this machine in at this one with: ${DEVICE_LOGIN_COMMAND}`);
|
|
30354
|
+
}
|
|
30355
|
+
if (await calculateJwkThumbprint(loginDpopKey(login.key).publicJwk) !== thumbprint) {
|
|
30356
|
+
throw new Error(`${DEVICE_LOGIN_FILE_NAMED} holds another login than the one this process started with, since ${DEVICE_LOGIN_COMMAND} ran again; start this session again to trade the new one`);
|
|
30357
|
+
}
|
|
30358
|
+
const refresh = () => refreshDeviceLogin(this.#path, login, { describe: this.describe(), held });
|
|
30359
|
+
const expires = login.accessExpiresAt?.getTime() ?? 0;
|
|
30360
|
+
let refreshed = login.accessToken === "" || expires - Date.now() < ACCESS_MARGIN_MS;
|
|
30361
|
+
if (refreshed)
|
|
30362
|
+
login = await refresh();
|
|
30363
|
+
while (true) {
|
|
30364
|
+
try {
|
|
30365
|
+
return await trade({ token: login.accessToken, tokenType: SUBJECT_TYPE_ACCESS });
|
|
30366
|
+
} catch (error) {
|
|
30367
|
+
if (!(error instanceof BrokerRefusedError) || !error.subjectNotHonoured)
|
|
30368
|
+
throw error;
|
|
30369
|
+
if (!await held())
|
|
30370
|
+
throw lockLost();
|
|
30371
|
+
if (refreshed)
|
|
30372
|
+
throw error;
|
|
30373
|
+
login = await refresh();
|
|
30374
|
+
refreshed = true;
|
|
30375
|
+
}
|
|
28719
30376
|
}
|
|
28720
|
-
}
|
|
28721
|
-
|
|
28722
|
-
|
|
28723
|
-
|
|
28724
|
-
expiresAt: new Date(this.#now() + seconds * 1000),
|
|
28725
|
-
credentialId: typeof answered["credential_id"] === "string" ? answered["credential_id"] : "",
|
|
28726
|
-
credentialExpiresAt
|
|
28727
|
-
};
|
|
30377
|
+
}, { signal });
|
|
30378
|
+
}
|
|
30379
|
+
async read(signal) {
|
|
30380
|
+
return await this.spend(async (subject) => subject, signal);
|
|
28728
30381
|
}
|
|
28729
30382
|
}
|
|
28730
|
-
function
|
|
28731
|
-
const
|
|
28732
|
-
|
|
28733
|
-
|
|
28734
|
-
|
|
28735
|
-
|
|
28736
|
-
|
|
28737
|
-
|
|
28738
|
-
|
|
28739
|
-
|
|
30383
|
+
async function refreshDeviceLogin(path, login, options) {
|
|
30384
|
+
const config = brokerConfiguration(login.broker, fetch, {
|
|
30385
|
+
key: loginDpopKey(login.key),
|
|
30386
|
+
nonce: { value: "" }
|
|
30387
|
+
});
|
|
30388
|
+
const endpoint = login.broker + TOKEN_PATH;
|
|
30389
|
+
let answered;
|
|
30390
|
+
for (let sent = 0;answered === undefined; sent += 1) {
|
|
30391
|
+
if (!await options.held())
|
|
30392
|
+
throw lockLost();
|
|
30393
|
+
try {
|
|
30394
|
+
answered = await genericGrantRequest(config, GRANT_TYPE_REFRESH, {
|
|
30395
|
+
refresh_token: login.refreshToken
|
|
30396
|
+
});
|
|
30397
|
+
} catch (error) {
|
|
30398
|
+
if (error instanceof ResponseBodyError && error.error === "invalid_grant") {
|
|
30399
|
+
throw new DeviceLoginEndedError(options.describe);
|
|
30400
|
+
}
|
|
30401
|
+
if (sent === 0 && statusOf(error) === 0)
|
|
30402
|
+
continue;
|
|
30403
|
+
throw brokerRefusal("refresh", options.describe, endpoint, error);
|
|
30404
|
+
}
|
|
28740
30405
|
}
|
|
30406
|
+
const next = loginOf(login.key, login.broker, answered, Date.now());
|
|
30407
|
+
await saveDeviceLogin(path, next, options.held);
|
|
30408
|
+
return next;
|
|
30409
|
+
}
|
|
30410
|
+
|
|
30411
|
+
// ../cipher-client/src/metadata-identity.ts
|
|
30412
|
+
import { Agent, request } from "http";
|
|
30413
|
+
var METADATA_HOST_VAR = "GCE_METADATA_HOST";
|
|
30414
|
+
var DEFAULT_METADATA_HOST = "metadata.google.internal";
|
|
30415
|
+
var IDENTITY_PATH = "/computeMetadata/v1/instance/service-accounts/default/identity";
|
|
30416
|
+
var TIMEOUT_MS = 1e4;
|
|
30417
|
+
var MAX_ANSWER_BYTES = 1 << 20;
|
|
30418
|
+
var agent = new Agent({ keepAlive: false });
|
|
30419
|
+
function tokenUrl(audience, env) {
|
|
30420
|
+
const host = (env[METADATA_HOST_VAR] ?? "").trim() || DEFAULT_METADATA_HOST;
|
|
30421
|
+
return `http://${host}${IDENTITY_PATH}?audience=${encodeURIComponent(audience)}&format=full`;
|
|
30422
|
+
}
|
|
30423
|
+
function serverNamed(env) {
|
|
30424
|
+
return (env[METADATA_HOST_VAR] ?? "").trim() === "" ? `at ${DEFAULT_METADATA_HOST}` : `${METADATA_HOST_VAR} names`;
|
|
30425
|
+
}
|
|
30426
|
+
function get(url, signal, lookup) {
|
|
30427
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
30428
|
+
const call = request(url, {
|
|
30429
|
+
agent,
|
|
30430
|
+
method: "GET",
|
|
30431
|
+
headers: { "Metadata-Flavor": "Google" },
|
|
30432
|
+
timeout: TIMEOUT_MS,
|
|
30433
|
+
...signal === undefined ? {} : { signal },
|
|
30434
|
+
...lookup === undefined ? {} : { lookup }
|
|
30435
|
+
}, (answer) => {
|
|
30436
|
+
const chunks = [];
|
|
30437
|
+
let read = 0;
|
|
30438
|
+
answer.on("data", (chunk) => {
|
|
30439
|
+
read += chunk.length;
|
|
30440
|
+
if (read <= MAX_ANSWER_BYTES)
|
|
30441
|
+
chunks.push(chunk);
|
|
30442
|
+
});
|
|
30443
|
+
answer.on("end", () => resolve({ status: answer.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8") }));
|
|
30444
|
+
answer.on("error", reject);
|
|
30445
|
+
});
|
|
30446
|
+
call.on("timeout", () => call.destroy(Object.assign(new Error(`no answer within ${TIMEOUT_MS} ms`), { code: "ETIMEDOUT" })));
|
|
30447
|
+
call.on("error", reject);
|
|
30448
|
+
call.end();
|
|
30449
|
+
return promise;
|
|
30450
|
+
}
|
|
30451
|
+
function metadataIdentity(audience, env = process.env, options = {}) {
|
|
30452
|
+
return {
|
|
30453
|
+
async read(signal) {
|
|
30454
|
+
const url = tokenUrl(audience, env);
|
|
30455
|
+
const named = `the metadata server ${serverNamed(env)}`;
|
|
30456
|
+
let answer;
|
|
30457
|
+
try {
|
|
30458
|
+
answer = await get(url, signal, options.lookup);
|
|
30459
|
+
} catch (error) {
|
|
30460
|
+
throw new Error(`${named} could not be reached: ${errorClass(error)}`);
|
|
30461
|
+
}
|
|
30462
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
30463
|
+
throw new Error(`${named} answered HTTP ${answer.status}`);
|
|
30464
|
+
}
|
|
30465
|
+
const token = answer.body.trim();
|
|
30466
|
+
if (token === "") {
|
|
30467
|
+
throw new Error(`${named} answered an empty identity token`);
|
|
30468
|
+
}
|
|
30469
|
+
return { token, tokenType: SUBJECT_TOKEN_TYPE_GOOGLE };
|
|
30470
|
+
},
|
|
30471
|
+
describe: () => `this machine's Google identity token for ${audience} (${METADATA_HOST_VAR} names the metadata server)`
|
|
30472
|
+
};
|
|
28741
30473
|
}
|
|
28742
30474
|
|
|
28743
30475
|
// ../cipher-client/src/person-identity.ts
|
|
@@ -28954,14 +30686,14 @@ function poolIdentity(options) {
|
|
|
28954
30686
|
}
|
|
28955
30687
|
|
|
28956
30688
|
// ../cipher-client/src/projected-token.ts
|
|
28957
|
-
import { readFile as
|
|
30689
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
28958
30690
|
function projectedToken(path, variable) {
|
|
28959
30691
|
const named = `the projected service-account token ${variable} names`;
|
|
28960
30692
|
return {
|
|
28961
30693
|
async read(signal) {
|
|
28962
30694
|
let contents;
|
|
28963
30695
|
try {
|
|
28964
|
-
contents = await
|
|
30696
|
+
contents = await readFile3(path, {
|
|
28965
30697
|
encoding: "utf8",
|
|
28966
30698
|
...signal === undefined ? {} : { signal }
|
|
28967
30699
|
});
|
|
@@ -28990,6 +30722,7 @@ var POOL_ACCOUNT_VAR = "AGENT_SECRETS_POOL_ACCOUNT";
|
|
|
28990
30722
|
var IDENTITY_KUBERNETES = "kubernetes";
|
|
28991
30723
|
var IDENTITY_METADATA = "metadata";
|
|
28992
30724
|
var IDENTITY_POOL = "pool";
|
|
30725
|
+
var IDENTITY_DEVICE_LOGIN = "device-login";
|
|
28993
30726
|
var BROKER_VARIABLES = [
|
|
28994
30727
|
BROKER_URL_VAR,
|
|
28995
30728
|
IDENTITY_VAR,
|
|
@@ -28999,6 +30732,7 @@ var BROKER_VARIABLES = [
|
|
|
28999
30732
|
PROJECTS_VAR,
|
|
29000
30733
|
POOL_AUDIENCE_VAR,
|
|
29001
30734
|
POOL_ACCOUNT_VAR,
|
|
30735
|
+
DEVICE_LOGIN_FILE_VAR,
|
|
29002
30736
|
SIGNIN_DIR_VAR,
|
|
29003
30737
|
"XDG_STATE_HOME",
|
|
29004
30738
|
"HOME",
|
|
@@ -29038,8 +30772,12 @@ function machineIdentity(env) {
|
|
|
29038
30772
|
tokenAudience
|
|
29039
30773
|
});
|
|
29040
30774
|
}
|
|
30775
|
+
case IDENTITY_DEVICE_LOGIN: {
|
|
30776
|
+
const brokerUrl = required2(env, BROKER_URL_VAR, kind);
|
|
30777
|
+
return new DeviceLoginIdentity({ path: deviceLoginFile(env), brokerUrl });
|
|
30778
|
+
}
|
|
29041
30779
|
default:
|
|
29042
|
-
throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA} or ${
|
|
30780
|
+
throw new Error(`${IDENTITY_VAR} names no identity this machine can prove; it takes ${IDENTITY_KUBERNETES}, ${IDENTITY_METADATA}, ${IDENTITY_POOL} or ${IDENTITY_DEVICE_LOGIN}`);
|
|
29043
30781
|
}
|
|
29044
30782
|
}
|
|
29045
30783
|
function tradeSession(env, own = "") {
|
|
@@ -29071,6 +30809,19 @@ async function brokerTokenClient(env, own = "") {
|
|
|
29071
30809
|
return;
|
|
29072
30810
|
if (!isHttpUrl(brokerUrl))
|
|
29073
30811
|
throw new Error(`${BROKER_URL_VAR} is not an http or https URL`);
|
|
30812
|
+
if (machine instanceof DeviceLoginIdentity) {
|
|
30813
|
+
if (personTradeOff(env)) {
|
|
30814
|
+
throw new Error(`${PERSON_TRADE_VAR}=off turns off every trade made as a person, and ${IDENTITY_VAR}=${IDENTITY_DEVICE_LOGIN} trades this machine's device login as the person who approved it; unset one of them`);
|
|
30815
|
+
}
|
|
30816
|
+
const client = new BrokerTokenClient({
|
|
30817
|
+
brokerUrl,
|
|
30818
|
+
key: await machine.key(),
|
|
30819
|
+
subject: machine,
|
|
30820
|
+
session: tradeSession(env, own) || deviceLoginSessionName(await machine.thumbprint()),
|
|
30821
|
+
projects: tradeProjects(env)
|
|
30822
|
+
});
|
|
30823
|
+
return { client, signIn: undefined };
|
|
30824
|
+
}
|
|
29074
30825
|
const record = await chooseSignIn(env);
|
|
29075
30826
|
if (record === undefined) {
|
|
29076
30827
|
const client = new BrokerTokenClient({
|
|
@@ -29875,7 +31626,7 @@ function natsCredential(env, section, namedNatsUrls, filePath, session) {
|
|
|
29875
31626
|
throw new NoSessionNamedError(auth.source);
|
|
29876
31627
|
return { kind: "broker", broker: brokerNatsCredential(env, session, auth.source) };
|
|
29877
31628
|
}
|
|
29878
|
-
var
|
|
31629
|
+
var LOOPBACK_HOST2 = /^(localhost|127(\.\d{1,3}){3}|\[::1\])$/i;
|
|
29879
31630
|
function natsConflictText(source, natsSetting) {
|
|
29880
31631
|
return `${source} is listener, and ${natsSetting} names NATS servers: set one of the two`;
|
|
29881
31632
|
}
|
|
@@ -29900,7 +31651,7 @@ function listenerInbound(source, natsSetting, credential, session) {
|
|
|
29900
31651
|
}
|
|
29901
31652
|
function plainHttpOffMachine(url) {
|
|
29902
31653
|
const host = URL.canParse(url) ? new URL(url) : undefined;
|
|
29903
|
-
return host?.protocol === "http:" && !
|
|
31654
|
+
return host?.protocol === "http:" && !LOOPBACK_HOST2.test(host.hostname) ? host.hostname : undefined;
|
|
29904
31655
|
}
|
|
29905
31656
|
function envoySettings(env, config, options = {}) {
|
|
29906
31657
|
if (config.kind === "failed")
|
|
@@ -30093,7 +31844,7 @@ function sessionEnvoySettings(file, env, options) {
|
|
|
30093
31844
|
|
|
30094
31845
|
// ../pi-shared/src/jj-attribution.ts
|
|
30095
31846
|
import { realpathSync } from "fs";
|
|
30096
|
-
import { mkdir, rename, writeFile } from "fs/promises";
|
|
31847
|
+
import { mkdir as mkdir2, rename as rename3, writeFile } from "fs/promises";
|
|
30097
31848
|
import path2 from "path";
|
|
30098
31849
|
var UUID = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
|
|
30099
31850
|
var JJ_CONFIG_PATH_TIMEOUT_MS = 1e4;
|
|
@@ -30232,10 +31983,10 @@ async function exportJjSessionAttribution(sessionId, stateDir, options = {}) {
|
|
|
30232
31983
|
pair.push(["Legion-Role", role]);
|
|
30233
31984
|
const contents = templatesTable(pair) + scopeTable(pair, issueKey, workspace);
|
|
30234
31985
|
try {
|
|
30235
|
-
await
|
|
31986
|
+
await mkdir2(stateDir, { recursive: true });
|
|
30236
31987
|
const tmp = `${overlay}.${process.pid}.tmp`;
|
|
30237
31988
|
await writeFile(tmp, contents);
|
|
30238
|
-
await
|
|
31989
|
+
await rename3(tmp, overlay);
|
|
30239
31990
|
const chain = `${base}:${overlay}`;
|
|
30240
31991
|
env["JJ_CONFIG"] = chain;
|
|
30241
31992
|
return chain;
|
|
@@ -30273,53 +32024,53 @@ function claudeProjectDirectory(environment, fallback) {
|
|
|
30273
32024
|
}
|
|
30274
32025
|
|
|
30275
32026
|
// src/session-identity.ts
|
|
30276
|
-
import { readFile as
|
|
30277
|
-
import { basename as
|
|
32027
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
32028
|
+
import { basename as basename3, join as join9 } from "path";
|
|
30278
32029
|
|
|
30279
32030
|
// src/session-state.ts
|
|
30280
32031
|
import { readFileSync as readFileSync5 } from "fs";
|
|
30281
|
-
import { mkdir as
|
|
30282
|
-
import { dirname as
|
|
32032
|
+
import { mkdir as mkdir3, readdir as readdir3, rename as rename4, rm as rm3, stat as stat3, utimes as utimes2, writeFile as writeFile2 } from "fs/promises";
|
|
32033
|
+
import { dirname as dirname4, join as join8 } from "path";
|
|
30283
32034
|
async function writeAtomicStateFile(file, contents) {
|
|
30284
|
-
await
|
|
32035
|
+
await mkdir3(dirname4(file), { recursive: true, mode: 448 });
|
|
30285
32036
|
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
30286
32037
|
await writeFile2(temporary, contents, { mode: 384 });
|
|
30287
|
-
await
|
|
32038
|
+
await rename4(temporary, file);
|
|
30288
32039
|
}
|
|
30289
32040
|
async function touchStateFile(file) {
|
|
30290
32041
|
const now = new Date;
|
|
30291
|
-
await
|
|
32042
|
+
await utimes2(file, now, now);
|
|
30292
32043
|
}
|
|
30293
32044
|
async function pruneStateDirectory(directory, isStale) {
|
|
30294
|
-
const entries = await
|
|
32045
|
+
const entries = await readdir3(directory).catch((error) => {
|
|
30295
32046
|
if (hasErrnoCode(error, "ENOENT"))
|
|
30296
32047
|
return [];
|
|
30297
32048
|
throw error;
|
|
30298
32049
|
});
|
|
30299
32050
|
for (const entry of entries) {
|
|
30300
|
-
const file =
|
|
32051
|
+
const file = join8(directory, entry);
|
|
30301
32052
|
if (!await isStale(file))
|
|
30302
32053
|
continue;
|
|
30303
|
-
await
|
|
32054
|
+
await rm3(file, { recursive: true, force: true });
|
|
30304
32055
|
}
|
|
30305
32056
|
}
|
|
30306
32057
|
var STATE_FILE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
|
30307
32058
|
async function writtenLongAgo(file) {
|
|
30308
|
-
const modified = await
|
|
32059
|
+
const modified = await stat3(file).then((stats) => stats.mtimeMs, () => {
|
|
30309
32060
|
return;
|
|
30310
32061
|
});
|
|
30311
32062
|
return modified !== undefined && Date.now() - modified > STATE_FILE_MAX_AGE_MS;
|
|
30312
32063
|
}
|
|
30313
32064
|
var TITLES_DIRECTORY = "titles";
|
|
30314
32065
|
function sessionTitleFile(stateDirectory, sessionId) {
|
|
30315
|
-
return
|
|
32066
|
+
return join8(stateDirectory, TITLES_DIRECTORY, `${encodeURIComponent(sessionId)}.txt`);
|
|
30316
32067
|
}
|
|
30317
32068
|
async function writeChosenTitle(file, title) {
|
|
30318
32069
|
await writeAtomicStateFile(file, `${title}
|
|
30319
32070
|
`);
|
|
30320
32071
|
}
|
|
30321
32072
|
async function removeChosenTitle(file) {
|
|
30322
|
-
await
|
|
32073
|
+
await rm3(file, { force: true });
|
|
30323
32074
|
}
|
|
30324
32075
|
function readChosenTitleSync(file) {
|
|
30325
32076
|
try {
|
|
@@ -30340,7 +32091,7 @@ async function recordChosenTitle(sessionId, title) {
|
|
|
30340
32091
|
await writeChosenTitle(file, chosen);
|
|
30341
32092
|
}
|
|
30342
32093
|
async function pruneStaleSessionTitles(stateDirectory) {
|
|
30343
|
-
await pruneStateDirectory(
|
|
32094
|
+
await pruneStateDirectory(join8(stateDirectory, TITLES_DIRECTORY), writtenLongAgo);
|
|
30344
32095
|
}
|
|
30345
32096
|
|
|
30346
32097
|
// src/session-identity.ts
|
|
@@ -30365,14 +32116,14 @@ class SessionIdentity {
|
|
|
30365
32116
|
}
|
|
30366
32117
|
}
|
|
30367
32118
|
function sessionHandoffDirectory(stateDirectory, claudePid) {
|
|
30368
|
-
return
|
|
32119
|
+
return join9(stateDirectory, "sessions", String(claudePid));
|
|
30369
32120
|
}
|
|
30370
32121
|
function sessionHandoffFile(stateDirectory, claudePid) {
|
|
30371
|
-
return
|
|
32122
|
+
return join9(sessionHandoffDirectory(stateDirectory, claudePid), "session-id");
|
|
30372
32123
|
}
|
|
30373
32124
|
var ROLES_DIRECTORY = "roles";
|
|
30374
32125
|
function roleStateFile(stateDirectory, sessionId) {
|
|
30375
|
-
return
|
|
32126
|
+
return join9(stateDirectory, ROLES_DIRECTORY, `${encodeURIComponent(sessionId)}.json`);
|
|
30376
32127
|
}
|
|
30377
32128
|
|
|
30378
32129
|
class UnparseableRoleRecordError extends Error {
|
|
@@ -30384,7 +32135,7 @@ class UnparseableRoleRecordError extends Error {
|
|
|
30384
32135
|
async function readPersistedRole(roleFile) {
|
|
30385
32136
|
let bytes;
|
|
30386
32137
|
try {
|
|
30387
|
-
bytes = await
|
|
32138
|
+
bytes = await readFile4(roleFile, "utf8");
|
|
30388
32139
|
} catch (error) {
|
|
30389
32140
|
if (hasErrnoCode(error, "ENOENT"))
|
|
30390
32141
|
return;
|
|
@@ -30406,7 +32157,7 @@ async function writeSessionHandoff(file, sessionId) {
|
|
|
30406
32157
|
}
|
|
30407
32158
|
async function readSessionHandoff(file) {
|
|
30408
32159
|
try {
|
|
30409
|
-
const id = (await
|
|
32160
|
+
const id = (await readFile4(file, "utf8")).trim();
|
|
30410
32161
|
return id.length === 0 ? undefined : id;
|
|
30411
32162
|
} catch (error) {
|
|
30412
32163
|
if (hasErrnoCode(error, "ENOENT"))
|
|
@@ -30423,14 +32174,14 @@ function processExists(pid) {
|
|
|
30423
32174
|
}
|
|
30424
32175
|
}
|
|
30425
32176
|
async function pruneStaleSessionHandoffs(stateDirectory) {
|
|
30426
|
-
await pruneStateDirectory(
|
|
30427
|
-
const pid =
|
|
32177
|
+
await pruneStateDirectory(join9(stateDirectory, "sessions"), (file) => {
|
|
32178
|
+
const pid = basename3(file);
|
|
30428
32179
|
return /^\d+$/.test(pid) && !processExists(Number(pid));
|
|
30429
32180
|
});
|
|
30430
32181
|
}
|
|
30431
32182
|
async function pruneStaleSessionRoles(stateDirectory, currentSessionId) {
|
|
30432
32183
|
const own = roleStateFile(stateDirectory, currentSessionId);
|
|
30433
|
-
await pruneStateDirectory(
|
|
32184
|
+
await pruneStateDirectory(join9(stateDirectory, ROLES_DIRECTORY), async (file) => file !== own && await writtenLongAgo(file));
|
|
30434
32185
|
}
|
|
30435
32186
|
|
|
30436
32187
|
// hooks/hook-arguments.ts
|
|
@@ -30604,7 +32355,7 @@ function dispatchFirst(raw) {
|
|
|
30604
32355
|
process.stdout.write(JSON.stringify({
|
|
30605
32356
|
hookSpecificOutput: {
|
|
30606
32357
|
hookEventName: input.hook_event_name,
|
|
30607
|
-
additionalContext: readDispatchFirstContext(dispatchFirstSkillFile(
|
|
32358
|
+
additionalContext: readDispatchFirstContext(dispatchFirstSkillFile(join10(pluginRoot, "skills")))
|
|
30608
32359
|
}
|
|
30609
32360
|
}));
|
|
30610
32361
|
}
|
|
@@ -30666,7 +32417,7 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
|
|
|
30666
32417
|
} catch (error) {
|
|
30667
32418
|
return { reason: messageFor(error) };
|
|
30668
32419
|
}
|
|
30669
|
-
const lock =
|
|
32420
|
+
const lock = join10(directory, REFRESH_LOCK);
|
|
30670
32421
|
if (!refreshLockHeld(lock)) {
|
|
30671
32422
|
Bun.spawn([process.execPath, Bun.main, "answers-refresh", session, cwd, "--host", HOST], {
|
|
30672
32423
|
stdin: "ignore",
|
|
@@ -30675,7 +32426,7 @@ async function refreshedAnswers(session, cwd, dispatchUrl, startedAt, by) {
|
|
|
30675
32426
|
detached: true
|
|
30676
32427
|
}).unref();
|
|
30677
32428
|
}
|
|
30678
|
-
const file =
|
|
32429
|
+
const file = join10(directory, REFRESH_OUTCOME);
|
|
30679
32430
|
for (;; ) {
|
|
30680
32431
|
const outcome = refreshOutcome(file, startedAt);
|
|
30681
32432
|
if (outcome !== undefined) {
|
|
@@ -30761,7 +32512,7 @@ async function answers(text) {
|
|
|
30761
32512
|
async function answersRefresh(session, cwd) {
|
|
30762
32513
|
const directory = sessionDirectory(process.env, session);
|
|
30763
32514
|
mkdirSync2(directory, { recursive: true, mode: 448 });
|
|
30764
|
-
const lock =
|
|
32515
|
+
const lock = join10(directory, REFRESH_LOCK);
|
|
30765
32516
|
if (takeRefreshLock(lock)) {
|
|
30766
32517
|
try {
|
|
30767
32518
|
const file = sessionConfigFile(HOST, process.env);
|
|
@@ -30779,7 +32530,7 @@ async function answersRefresh(session, cwd) {
|
|
|
30779
32530
|
text: read.text ?? null,
|
|
30780
32531
|
notice: read.notice ?? null
|
|
30781
32532
|
};
|
|
30782
|
-
writeAtomically(
|
|
32533
|
+
writeAtomically(join10(directory, REFRESH_OUTCOME), JSON.stringify(outcome));
|
|
30783
32534
|
} finally {
|
|
30784
32535
|
rmSync3(lock, { force: true });
|
|
30785
32536
|
}
|