ppio-sandbox 2.1.1-a4 → 2.1.1-a5

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.
@@ -60,7 +60,7 @@ import createClient from "openapi-fetch";
60
60
  import platform2 from "platform";
61
61
 
62
62
  // package.json
63
- var version = "2.1.1-a4";
63
+ var version = "2.1.1-a5";
64
64
 
65
65
  // src/core/utils.ts
66
66
  import platform from "platform";
@@ -256,6 +256,8 @@ var FileUploadError = class extends BuildError {
256
256
  this.name = "FileUploadError";
257
257
  }
258
258
  };
259
+ var ImageConfigError = class extends BuildError {
260
+ };
259
261
  var VolumeError = class extends Error {
260
262
  constructor(message) {
261
263
  super(message);
@@ -5640,6 +5642,7 @@ var SKIP_ENV = /* @__PURE__ */ new Set([
5640
5642
  ]);
5641
5643
  var RETRY_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
5642
5644
  var READ_ATTEMPTS = 3;
5645
+ var TOKEN_CLIENT_ID = "ppio-sandbox";
5643
5646
  var backoffBaseMs = 1e3;
5644
5647
  function unsupportedBase(blob) {
5645
5648
  var _a3, _b, _c, _d, _e;
@@ -5716,13 +5719,87 @@ function parseImageRef(image) {
5716
5719
  return { host, repository, reference };
5717
5720
  }
5718
5721
  var RegistryHttpError = class extends Error {
5719
- constructor(status, retryAfter, message) {
5722
+ constructor(status, retryAfter, message, challenge = null) {
5720
5723
  super(message);
5721
5724
  this.status = status;
5722
5725
  this.retryAfter = retryAfter;
5726
+ this.challenge = challenge;
5723
5727
  this.name = "RegistryHttpError";
5724
5728
  }
5725
5729
  };
5730
+ function parseChallenges(header) {
5731
+ const text = header != null ? header : "";
5732
+ const challenges = [];
5733
+ let index = 0;
5734
+ const skipSeparators = () => {
5735
+ while (index < text.length && " ,".includes(text[index])) {
5736
+ index++;
5737
+ }
5738
+ };
5739
+ const readToken = () => {
5740
+ const start = index;
5741
+ while (index < text.length && /[A-Za-z0-9\-_.:]/.test(text[index])) {
5742
+ index++;
5743
+ }
5744
+ return text.slice(start, index);
5745
+ };
5746
+ for (; ; ) {
5747
+ skipSeparators();
5748
+ const scheme = readToken();
5749
+ if (!scheme) {
5750
+ break;
5751
+ }
5752
+ const params = {};
5753
+ for (; ; ) {
5754
+ skipSeparators();
5755
+ if (index >= text.length) {
5756
+ break;
5757
+ }
5758
+ const keyStart = index;
5759
+ const key = readToken();
5760
+ if (!key) {
5761
+ break;
5762
+ }
5763
+ while (index < text.length && " ".includes(text[index])) {
5764
+ index++;
5765
+ }
5766
+ if (index >= text.length || text[index] !== "=") {
5767
+ index = keyStart;
5768
+ break;
5769
+ }
5770
+ index++;
5771
+ while (index < text.length && " ".includes(text[index])) {
5772
+ index++;
5773
+ }
5774
+ if (index < text.length && text[index] === '"') {
5775
+ index++;
5776
+ const chars = [];
5777
+ while (index < text.length) {
5778
+ if (text[index] === "\\" && index + 1 < text.length) {
5779
+ chars.push(text[index + 1]);
5780
+ index += 2;
5781
+ continue;
5782
+ }
5783
+ if (text[index] === '"') {
5784
+ index++;
5785
+ break;
5786
+ }
5787
+ chars.push(text[index]);
5788
+ index++;
5789
+ }
5790
+ params[key.toLowerCase()] = chars.join("");
5791
+ } else {
5792
+ const valueStart = index;
5793
+ while (index < text.length && text[index] !== ",") {
5794
+ index++;
5795
+ }
5796
+ params[key.toLowerCase()] = text.slice(valueStart, index).trim();
5797
+ }
5798
+ }
5799
+ challenges.push({ scheme, params });
5800
+ }
5801
+ return challenges;
5802
+ }
5726
5803
  var UnusableImageError = class extends Error {
5727
5804
  constructor(message) {
5728
5805
  super(message);
@@ -5749,15 +5826,20 @@ async function registryGet(url, headers, options) {
5749
5826
  );
5750
5827
  }
5751
5828
  try {
5752
- const response = await fetch(url, {
5829
+ const init = {
5753
5830
  headers,
5754
5831
  signal: AbortSignal.timeout(timeoutMs)
5755
- });
5832
+ };
5833
+ if ((options == null ? void 0 : options.dispatcher) !== void 0) {
5834
+ init.dispatcher = options.dispatcher;
5835
+ }
5836
+ const response = await fetch(url, init);
5756
5837
  if (!response.ok) {
5757
5838
  const error = new RegistryHttpError(
5758
5839
  response.status,
5759
5840
  response.headers.get("retry-after"),
5760
- `HTTP ${response.status} ${response.statusText}`
5841
+ `HTTP ${response.status} ${response.statusText}`,
5842
+ response.headers.get("www-authenticate")
5761
5843
  );
5762
5844
  if (!RETRY_STATUS.has(response.status)) {
5763
5845
  throw error;
@@ -5775,14 +5857,10 @@ async function registryGet(url, headers, options) {
5775
5857
  }
5776
5858
  throw last;
5777
5859
  }
5778
- async function authHeaders(host, repository, credentials) {
5860
+ async function authHeaders(host, repository, credentials, dispatcher) {
5779
5861
  const headers = { Accept: MANIFEST_TYPES };
5780
- if (credentials) {
5781
- const basic = Buffer.from(
5782
- `${credentials.username}:${credentials.password}`,
5783
- "utf8"
5784
- ).toString("base64");
5785
- headers.Authorization = `Basic ${basic}`;
5862
+ if ((credentials == null ? void 0 : credentials.username) && credentials.password) {
5863
+ headers.Authorization = basicHeader(credentials);
5786
5864
  }
5787
5865
  const services = {
5788
5866
  "registry-1.docker.io": ["auth.docker.io", "registry.docker.io"],
@@ -5796,9 +5874,9 @@ async function authHeaders(host, repository, credentials) {
5796
5874
  const url = `https://${authHost}/token?service=${serviceName}&scope=repository:${repository}:pull`;
5797
5875
  try {
5798
5876
  const tokenHeaders = headers.Authorization ? { Authorization: headers.Authorization } : {};
5799
- const body = await registryGet(url, tokenHeaders, {
5877
+ const body = await registryGet(url, tokenHeaders, __spreadValues({
5800
5878
  attempts: 1
5801
- });
5879
+ }, dispatcher === void 0 ? {} : { dispatcher }));
5802
5880
  if (body.token) {
5803
5881
  headers.Authorization = `Bearer ${body.token}`;
5804
5882
  }
@@ -5806,6 +5884,79 @@ async function authHeaders(host, repository, credentials) {
5806
5884
  }
5807
5885
  return headers;
5808
5886
  }
5887
+ var RegistrySession = class {
5888
+ constructor(repository, credentials, headers, dispatcher) {
5889
+ this.repository = repository;
5890
+ this.credentials = credentials;
5891
+ this.headers = headers;
5892
+ this.dispatcher = dispatcher;
5893
+ this.token = null;
5894
+ }
5895
+ /** GET `url`, resolving one Bearer challenge if the registry asks for it. */
5896
+ async get(url) {
5897
+ const headers = __spreadValues({}, this.headers);
5898
+ if (this.token) {
5899
+ headers.Authorization = `Bearer ${this.token}`;
5900
+ }
5901
+ try {
5902
+ return await registryGet(url, headers, __spreadValues({
5903
+ attempts: READ_ATTEMPTS
5904
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
5905
+ } catch (error) {
5906
+ if (!(error instanceof RegistryHttpError) || error.status !== 401) {
5907
+ throw error;
5908
+ }
5909
+ const token = await this.tokenFrom(error.challenge);
5910
+ if (token === null) {
5911
+ throw error;
5912
+ }
5913
+ this.token = token;
5914
+ headers.Authorization = `Bearer ${token}`;
5915
+ return registryGet(url, headers, __spreadValues({
5916
+ attempts: READ_ATTEMPTS
5917
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
5918
+ }
5919
+ }
5920
+ async tokenFrom(challenge) {
5921
+ for (const { scheme, params } of parseChallenges(challenge)) {
5922
+ if (scheme.toLowerCase() === "bearer") {
5923
+ return this.bearer(params);
5924
+ }
5925
+ }
5926
+ return null;
5927
+ }
5928
+ async bearer(params) {
5929
+ var _a3;
5930
+ const realm = params.realm;
5931
+ if (!realm || !/^https?:\/\//.test(realm)) {
5932
+ return null;
5933
+ }
5934
+ const url = new URL(realm);
5935
+ url.searchParams.set("client_id", TOKEN_CLIENT_ID);
5936
+ if (params.service) {
5937
+ url.searchParams.set("service", params.service);
5938
+ }
5939
+ url.searchParams.set("scope", params.scope || `repository:${this.repository}:pull`);
5940
+ const headers = {};
5941
+ if (((_a3 = this.credentials) == null ? void 0 : _a3.username) && this.credentials.password) {
5942
+ headers.Authorization = basicHeader(this.credentials);
5943
+ }
5944
+ const body = await registryGet(url.toString(), headers, __spreadValues({
5945
+ attempts: 1
5946
+ }, this.dispatcher === void 0 ? {} : { dispatcher: this.dispatcher }));
5947
+ if (body === null || typeof body !== "object") {
5948
+ return null;
5949
+ }
5950
+ return body.token || body.access_token || null;
5951
+ }
5952
+ };
5953
+ function basicHeader(credentials) {
5954
+ const encoded = Buffer.from(
5955
+ `${credentials.username}:${credentials.password}`,
5956
+ "utf8"
5957
+ ).toString("base64");
5958
+ return `Basic ${encoded}`;
5959
+ }
5809
5960
  function platformName(entry) {
5810
5961
  var _a3, _b, _c;
5811
5962
  const p = (_a3 = entry.platform) != null ? _a3 : {};
@@ -5850,41 +6001,53 @@ function describeFailure(error, image, host, repository, authenticated) {
5850
6001
  const reason = `no such image: Docker Hub has no official image '${image}' (HTTP 401). The \`library/\` namespace has no private repositories, so this is a typo rather than a permissions problem`;
5851
6002
  return __spreadProps(__spreadValues({}, empty), { error: reason, unusable: reason });
5852
6003
  }
6004
+ if (error.status === 401) {
6005
+ const reason = authenticated ? `cannot read '${image}' (HTTP 401): the registry rejected the credentials. Check the username, the password, and the read permission on the repository` : `cannot read '${image}' (HTTP 401): the registry wants pull credentials for it. Pass the registry username and password, or check that the reference names an existing public image`;
6006
+ return __spreadProps(__spreadValues({}, empty), { error: reason });
6007
+ }
5853
6008
  return __spreadProps(__spreadValues({}, empty), { error: `${error.name}: ${error.message}` });
5854
6009
  }
5855
6010
  const message = error instanceof Error ? error.message : String(error);
5856
6011
  return __spreadProps(__spreadValues({}, empty), { error: message });
5857
6012
  }
5858
- async function fetchImageConfig(image, credentials) {
6013
+ async function fetchImageConfig(image, credentials, options) {
5859
6014
  var _a3, _b, _c, _d, _e, _f, _g;
6015
+ const dispatcher = options == null ? void 0 : options.dispatcher;
6016
+ const cacheable = dispatcher === void 0;
5860
6017
  const key = JSON.stringify([
5861
6018
  image,
5862
6019
  (_a3 = credentials == null ? void 0 : credentials.username) != null ? _a3 : null,
5863
6020
  (_b = credentials == null ? void 0 : credentials.password) != null ? _b : null
5864
6021
  ]);
5865
- const cached = CACHE.get(key);
5866
- if (cached) {
5867
- return copyConfig(cached);
6022
+ if (cacheable) {
6023
+ const cached = CACHE.get(key);
6024
+ if (cached) {
6025
+ return copyConfig(cached);
6026
+ }
5868
6027
  }
5869
6028
  const { host, repository, reference } = parseImageRef(image);
5870
6029
  let result;
5871
6030
  try {
5872
- const auth = await authHeaders(host, repository, credentials);
6031
+ const auth = await authHeaders(host, repository, credentials, dispatcher);
6032
+ const session = new RegistrySession(
6033
+ repository,
6034
+ credentials,
6035
+ auth,
6036
+ dispatcher
6037
+ );
5873
6038
  const base = `https://${host}/v2/${repository}`;
5874
- let manifest = await registryGet(
5875
- `${base}/manifests/${reference}`,
5876
- auth
6039
+ let manifest = await session.get(
6040
+ `${base}/manifests/${reference}`
5877
6041
  );
5878
6042
  if (manifest.manifests) {
5879
6043
  const digest = pickAmd64(manifest, image);
5880
- manifest = await registryGet(`${base}/manifests/${digest}`, auth);
6044
+ manifest = await session.get(`${base}/manifests/${digest}`);
5881
6045
  }
5882
6046
  if (!((_c = manifest.config) == null ? void 0 : _c.digest)) {
5883
6047
  throw new Error(`${image}: manifest names no config blob`);
5884
6048
  }
5885
- const blob = await registryGet(
5886
- `${base}/blobs/${manifest.config.digest}`,
5887
- auth
6049
+ const blob = await session.get(
6050
+ `${base}/blobs/${manifest.config.digest}`
5888
6051
  );
5889
6052
  const declared = (_d = blob.config) != null ? _d : {};
5890
6053
  const env = {};
@@ -5911,10 +6074,14 @@ async function fetchImageConfig(image, credentials) {
5911
6074
  image,
5912
6075
  host,
5913
6076
  repository,
5914
- credentials !== void 0
6077
+ // Both, because that is what the request actually carried: a lone username
6078
+ // is not a credential the registry could have rejected.
6079
+ Boolean((credentials == null ? void 0 : credentials.username) && (credentials == null ? void 0 : credentials.password))
5915
6080
  );
5916
6081
  }
5917
- CACHE.set(key, result);
6082
+ if (cacheable) {
6083
+ CACHE.set(key, result);
6084
+ }
5918
6085
  return copyConfig(result);
5919
6086
  }
5920
6087
  function effectiveStartCmd(entrypoint, cmd) {
@@ -6097,6 +6264,13 @@ var TemplateBase = class _TemplateBase {
6097
6264
  // image's PATH -- the exact failure this reading exists to prevent.
6098
6265
  this.imageConfigError = void 0;
6099
6266
  this.imageUnusable = void 0;
6267
+ // What a failed read does. "warn" by default: one unreachable registry must not
6268
+ // abort a batch conversion, but a template silently missing the image's PATH is
6269
+ // the failure this reading exists to prevent, so it cannot pass unmentioned.
6270
+ this.imageOnConfigFailure = "warn";
6271
+ // Carries the TLS trust and proxy settings for a self-hosted registry, which
6272
+ // Node's fetch cannot be told about in any other per-request way.
6273
+ this.imageDispatcher = void 0;
6100
6274
  this.fileContextPath = runtime === "browser" ? "." : (_a2 = getCallerDirectory(STACK_TRACE_DEPTH)) != null ? _a2 : ".";
6101
6275
  this.fileIgnorePatterns = [];
6102
6276
  this.logsRefreshFrequency = 200;
@@ -6323,12 +6497,40 @@ var TemplateBase = class _TemplateBase {
6323
6497
  fromBaseImage() {
6324
6498
  return this.fromImage(this.defaultBaseImage);
6325
6499
  }
6500
+ /**
6501
+ * Build from a Docker image, restoring what the image declares.
6502
+ *
6503
+ * The image's ENV, WORKDIR and start command are read from its registry config
6504
+ * because the platform's own pull does not apply them. Reading is best-effort
6505
+ * and asynchronous, so it happens at build/serialize time.
6506
+ *
6507
+ * @param credentials registry username and password, for a private image.
6508
+ * @param options.inheritConfig restore the image's config (default true).
6509
+ * @param options.onConfigFailure what a failed read does — see
6510
+ * {@link ImageConfigFailureMode}. Defaults to `warn`.
6511
+ * @param options.dispatcher Node fetch `dispatcher` (an undici `Agent`), for a
6512
+ * self-hosted registry behind a private CA, a client certificate or a proxy.
6513
+ * For example, with a private CA:
6514
+ *
6515
+ * ```ts
6516
+ * import { Agent } from 'undici'
6517
+ * const dispatcher = new Agent({ connect: { ca: readFileSync('/ca.pem') } })
6518
+ * Template().fromImage('harbor.internal/app:1', undefined, { dispatcher })
6519
+ * ```
6520
+ */
6326
6521
  fromImage(baseImage, credentials, options) {
6327
- var _a3;
6522
+ var _a3, _b;
6523
+ if ((options == null ? void 0 : options.onConfigFailure) !== void 0 && !["warn", "raise", "ignore"].includes(options.onConfigFailure)) {
6524
+ throw new InvalidArgumentError(
6525
+ 'onConfigFailure must be "warn", "raise" or "ignore", got ' + String(options.onConfigFailure)
6526
+ );
6527
+ }
6328
6528
  this.baseImage = baseImage;
6329
6529
  this.baseTemplate = void 0;
6330
6530
  this.inheritImageConfig = (_a3 = options == null ? void 0 : options.inheritConfig) != null ? _a3 : true;
6331
6531
  this.imageCredentials = credentials;
6532
+ this.imageOnConfigFailure = (_b = options == null ? void 0 : options.onConfigFailure) != null ? _b : "warn";
6533
+ this.imageDispatcher = options == null ? void 0 : options.dispatcher;
6332
6534
  if (credentials) {
6333
6535
  this.registryConfig = {
6334
6536
  type: "registry",
@@ -6743,23 +6945,35 @@ var TemplateBase = class _TemplateBase {
6743
6945
  * restored config — but it is reported, since an image whose toolchain lives
6744
6946
  * behind its ENV will otherwise look installed and behave as though it is not.
6745
6947
  */
6948
+ /** The one wording a failed read is reported with, on every channel. */
6949
+ configFailureMessage() {
6950
+ return `Could not read ${this.baseImage}: ${this.imageConfigError}. The template will build without the environment, working directory and start command the image declares.`;
6951
+ }
6746
6952
  async resolveInheritedConfig(onBuildLogs) {
6747
6953
  var _a3;
6954
+ if (this.imageOnConfigFailure === "raise" && this.imageConfigError !== void 0) {
6955
+ throw new ImageConfigError(this.configFailureMessage());
6956
+ }
6748
6957
  if (!this.inheritImageConfig || this.baseImage === void 0) {
6749
6958
  return;
6750
6959
  }
6751
6960
  this.inheritImageConfig = false;
6752
- const config = await fetchImageConfig(this.baseImage, this.imageCredentials);
6961
+ const config = await fetchImageConfig(
6962
+ this.baseImage,
6963
+ this.imageCredentials,
6964
+ this.imageDispatcher === void 0 ? void 0 : { dispatcher: this.imageDispatcher }
6965
+ );
6753
6966
  if (config.error) {
6754
6967
  this.imageConfigError = config.error;
6755
6968
  this.imageUnusable = config.unusable;
6756
- onBuildLogs == null ? void 0 : onBuildLogs(
6757
- new LogEntry(
6758
- /* @__PURE__ */ new Date(),
6759
- "warn",
6760
- `Could not read ${this.baseImage}: ${config.error}. The template will build without the environment, working directory and start command the image declares.`
6761
- )
6762
- );
6969
+ const message = this.configFailureMessage();
6970
+ if (this.imageOnConfigFailure === "raise") {
6971
+ throw new ImageConfigError(message);
6972
+ }
6973
+ if (this.imageOnConfigFailure !== "ignore") {
6974
+ console.warn(message);
6975
+ onBuildLogs == null ? void 0 : onBuildLogs(new LogEntry(/* @__PURE__ */ new Date(), "warn", message));
6976
+ }
6763
6977
  return;
6764
6978
  }
6765
6979
  this.envs = __spreadValues(__spreadValues({}, config.env), this.envs);
@@ -7146,6 +7360,7 @@ Template.list = TemplateBase.list;
7146
7360
  Template.delete = TemplateBase.delete;
7147
7361
  Template.toJSON = TemplateBase.toJSON;
7148
7362
  Template.toDockerfile = TemplateBase.toDockerfile;
7363
+ Template.imageConfigFailure = TemplateBase.imageConfigFailure;
7149
7364
 
7150
7365
  // src/core/volume/index.ts
7151
7366
  function quotaInodesForSize(quotaSizeGiB) {
@@ -7708,12 +7923,12 @@ var PPIO = class {
7708
7923
  this.secret = new SecretNamespace(opts);
7709
7924
  this.codeInterpreter = new RuntimeSandboxNamespace(
7710
7925
  opts,
7711
- () => import("./sandbox-OAPKYDCZ.mjs")
7926
+ () => import("./sandbox-GD3E5T3C.mjs")
7712
7927
  );
7713
7928
  this.code_interpreter = this.codeInterpreter;
7714
7929
  this.desktop = new RuntimeSandboxNamespace(
7715
7930
  opts,
7716
- () => import("./sandbox-IFBOTC7A.mjs")
7931
+ () => import("./sandbox-U6WT7JIS.mjs")
7717
7932
  );
7718
7933
  }
7719
7934
  async create(templateOrOpts, opts) {
@@ -7756,6 +7971,7 @@ export {
7756
7971
  RateLimitError,
7757
7972
  BuildError,
7758
7973
  FileUploadError,
7974
+ ImageConfigError,
7759
7975
  VolumeError,
7760
7976
  SecretError,
7761
7977
  ApiClient,
@@ -7791,4 +8007,4 @@ export {
7791
8007
  ALL_TRAFFIC,
7792
8008
  core_default
7793
8009
  };
7794
- //# sourceMappingURL=chunk-6PRE7JOS.mjs.map
8010
+ //# sourceMappingURL=chunk-473VNTF7.mjs.map