@capybara-hq/kernel 0.1.0-rc.62 → 0.1.0-rc.63

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.
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { CATALOG_ITEM_NAME_RE, marketplaceEntryDeprecation, marketplaceEntryVersion, PLUGIN_MANIFEST_FILE, parseMarketplaceManifest, parsePluginManifest, pluginDescription, SDK_VERSION, SEMVER_VERSION_RE, } from "@capybara-hq/plugin-sdk";
11
+ import { CATALOG_ITEM_NAME_RE, GIT_USERNAME_RE, marketplaceEntryDeprecation, marketplaceEntryVersion, PLUGIN_MANIFEST_FILE, parseMarketplaceManifest, parsePluginManifest, pluginDescription, SDK_VERSION, SEMVER_VERSION_RE, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import semver from "semver";
@@ -39,6 +39,8 @@ const OFFICIAL_MARKETPLACE_NAME = "Capybara official marketplace";
39
39
  /** 企业清单的可选令牌:secrets 的 namespace `kernel`、org `_deployment`、键 `catalog-token:<id>`(preflight #65)。 */
40
40
  const SECRETS_NAMESPACE = "kernel";
41
41
  const tokenKey = (id) => `catalog-token:${id}`;
42
+ /** The id prefix of a marketplace the deployment config owns (`config:<name>`). */
43
+ export const CONFIG_MARKETPLACE_PREFIX = "config:";
42
44
  /** 拉取一份清单的超时。 */
43
45
  export const MARKETPLACE_FETCH_TIMEOUT_MS = 30_000;
44
46
  /**
@@ -72,6 +74,7 @@ export function pluginNameFrom(segment) {
72
74
  return name === "" ? "plugin" : name;
73
75
  }
74
76
  const builtinErr = (what) => new ApiError("marketplace.builtin", `The official marketplace is configured in marketplaces.official.*; it cannot be ${what} here (only enabled or disabled)`);
77
+ const configManagedErr = (what) => new ApiError("marketplace.config_managed", `This marketplace is configured by the deployment (bootstrap.extraManifest); it cannot be ${what} here (only enabled or disabled)`);
75
78
  /** Entry versions newest first; `''` (no version) last. */
76
79
  const bySemverDescOrNone = (a, b) => a === b ? 0 : a === "" ? 1 : b === "" ? -1 : compareVersions(b, a);
77
80
  const gitDetailOf = (v) => {
@@ -461,6 +464,115 @@ let MarketplacesService = class MarketplacesService {
461
464
  }))
462
465
  .execute();
463
466
  }
467
+ /**
468
+ * Upserts the marketplaces of the extra bootstrap manifest (spec 2026-11-20 §5): one row
469
+ * `config:<name>` each with `managed = 'config'`; name, URL (its form per
470
+ * {@link marketplaceForm}), ref and username follow the file, the admin's enable switch is left
471
+ * alone, and a changed URL, form or ref drops the ETag and the last commit. The token stays in
472
+ * `marketplaces.tokens[name]`, never in the secrets table (a token an admin set while the row
473
+ * was demoted is deleted when it becomes managed again). A managed row whose name left the
474
+ * file is kept as an ordinary custom marketplace (`managed = NULL`, so no token). Called by
475
+ * every replica at start; idempotent. An invalid entry -> {@link ConfigError}, nothing written.
476
+ * `undefined` (this process has no extra manifest) writes nothing and demotes nothing: such a
477
+ * process may have read no managed row before another replica's sync committed (ruling R16), so
478
+ * only a configured extra manifest (an empty one included) removes a marketplace. Returns the
479
+ * names of the rows it demoted.
480
+ */
481
+ async syncExtraFromConfig(marketplaces) {
482
+ if (marketplaces === undefined)
483
+ return [];
484
+ const rows = marketplaces
485
+ .map((m) => this.extraMarketplaceRow(m))
486
+ // one lock order for every replica
487
+ .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
488
+ const ids = rows.map((r) => r.id);
489
+ if (new Set(ids).size !== ids.length) {
490
+ throw new ConfigError("invalid configuration:\n - bootstrap.extraManifest: marketplace names must be unique");
491
+ }
492
+ const t = this.db;
493
+ const same = sql `marketplaces.url = excluded.url AND marketplaces.form = excluded.form AND marketplaces.ref IS NOT DISTINCT FROM excluded.ref`;
494
+ for (const r of rows) {
495
+ await t
496
+ .insertInto("marketplaces")
497
+ .values({ ...r, mirrors: "[]", builtin: false, enabled: true, managed: "config" })
498
+ .onConflict((oc) => oc.column("id").doUpdateSet({
499
+ name: r.name,
500
+ url: r.url,
501
+ form: r.form,
502
+ ref: r.ref,
503
+ username: r.username,
504
+ mirrors: "[]",
505
+ builtin: false,
506
+ managed: "config",
507
+ etag: sql `CASE WHEN ${same} THEN marketplaces.etag ELSE NULL END`,
508
+ last_commit: sql `CASE WHEN ${same} THEN marketplaces.last_commit ELSE NULL END`,
509
+ }))
510
+ .execute();
511
+ // A managed row's token lives only in the config: drop one an admin set while the row was
512
+ // demoted, so it never follows the file's URL to another origin
513
+ await this.secrets().delete(DEPLOYMENT_SECRETS_ORG, tokenKey(r.id));
514
+ }
515
+ let gone = t.updateTable("marketplaces").set({ managed: null }).where("managed", "=", "config");
516
+ if (ids.length > 0)
517
+ gone = gone.where("id", "not in", ids);
518
+ const demoted = await gone.returning("name").execute();
519
+ for (const r of rows)
520
+ await this.backfillBootstrapItems(r.id);
521
+ return demoted.map((d) => d.name).sort();
522
+ }
523
+ /**
524
+ * Names the managed marketplace on the platform items the bootstrap step imported from it before
525
+ * its row existed (`capybara bootstrap` runs before the first start, and `marketplace_id` is a
526
+ * foreign key): a live item without a marketplace whose latest version came from the bootstrap
527
+ * with a `source_ref` of `<id>:…` (a git entry of that marketplace). Then the catalog tracks its
528
+ * updates like an import from the marketplace. Idempotent.
529
+ */
530
+ async backfillBootstrapItems(id) {
531
+ const prefix = `${id.replace(/[\\%_]/g, (c) => `\\${c}`)}:%`;
532
+ await this.db
533
+ .updateTable("catalog_items as i")
534
+ .set({ marketplace_id: id })
535
+ .where("i.owner_org_id", "is", null)
536
+ .where("i.marketplace_id", "is", null)
537
+ .where("i.deleted_at", "is", null)
538
+ .where((eb) => eb.exists(eb
539
+ .selectFrom("catalog_item_versions as v")
540
+ .select("v.item_id")
541
+ .whereRef("v.item_id", "=", "i.id")
542
+ .whereRef("v.version", "=", "i.latest_version")
543
+ .where("v.source", "=", "bootstrap")
544
+ .where("v.source_ref", "like", prefix)))
545
+ .execute();
546
+ }
547
+ /** The row of one extra-manifest marketplace, checked as an admin add is (else ConfigError). */
548
+ extraMarketplaceRow(m) {
549
+ const bad = (what) => new ConfigError(`invalid configuration:\n - bootstrap.extraManifest marketplaces: ${what}`);
550
+ if (!CATALOG_ITEM_NAME_RE.test(m.name)) {
551
+ throw bad(`name ${JSON.stringify(m.name)} must match ^[a-z0-9][a-z0-9-]{0,63}$`);
552
+ }
553
+ if (m.username !== undefined && m.username !== "" && !GIT_USERNAME_RE.test(m.username)) {
554
+ throw bad(`${m.name}: username must match ^[A-Za-z0-9._-]{1,64}$`);
555
+ }
556
+ const { form, url } = marketplaceForm(m.url);
557
+ const ref = m.ref ?? null;
558
+ try {
559
+ this.checkUrls(url, []);
560
+ this.checkGitFields(form, ref, []);
561
+ }
562
+ catch (e) {
563
+ if (e instanceof ApiError)
564
+ throw bad(`${m.name}: ${e.message}`);
565
+ throw e;
566
+ }
567
+ return {
568
+ id: `${CONFIG_MARKETPLACE_PREFIX}${m.name}`,
569
+ name: m.name,
570
+ url,
571
+ form,
572
+ ref,
573
+ username: m.username === undefined || m.username === "" ? null : m.username,
574
+ };
575
+ }
464
576
  /** 全部来源(official 在前,其余按创建时间)。 */
465
577
  async list() {
466
578
  const rows = (await this.db
@@ -494,8 +606,9 @@ let MarketplacesService = class MarketplacesService {
494
606
  this.checkGitFields(form, input.ref ?? null, input.mirrors ?? []);
495
607
  if (input.token !== undefined)
496
608
  this.checkToken(input.token);
609
+ const username = this.checkUsername(input.username);
497
610
  const id = randomUUID();
498
- await this.writeAdd(actor, id, { ...input, name, form, url }, opts);
611
+ await this.writeAdd(actor, id, { ...input, name, form, url, username }, opts);
499
612
  return this.get(id);
500
613
  }
501
614
  /**
@@ -532,6 +645,7 @@ let MarketplacesService = class MarketplacesService {
532
645
  mirrors: JSON.stringify(input.mirrors ?? []),
533
646
  builtin: false,
534
647
  enabled: true,
648
+ username: input.username,
535
649
  created_by: actor,
536
650
  })
537
651
  .execute();
@@ -549,6 +663,7 @@ let MarketplacesService = class MarketplacesService {
549
663
  form,
550
664
  ...(input.ref !== undefined && { ref: input.ref }),
551
665
  mirrors: input.mirrors ?? [],
666
+ ...(input.username !== null && { username: input.username }),
552
667
  hasToken: input.token !== undefined,
553
668
  ...opts.auditDetail,
554
669
  },
@@ -556,12 +671,13 @@ let MarketplacesService = class MarketplacesService {
556
671
  }
557
672
  /**
558
673
  * Updates a custom marketplace (audit `marketplace.updated`, listing the changed fields, the
559
- * token's value never recorded; not written when unchanged). `token: null` clears the token.
560
- * Official only takes `enabled`, any other field -> `marketplace.builtin`. Changing the URL, form
561
- * or ref clears the ETag and the last commit (the next refresh reads everything again); a new URL
562
- * gets its form from {@link marketplaceForm} unless `form` is given. `ref: null` follows the
563
- * remote HEAD. Switching the form clears the other form's field (the ref when becoming http,
564
- * the mirrors when becoming git) unless the patch sets it.
674
+ * token's value never recorded; not written when unchanged). `token: null` clears the token,
675
+ * `username: null` or `""` the username. Official only takes `enabled`, any other field ->
676
+ * `marketplace.builtin`; a config-managed marketplace likewise -> `marketplace.config_managed`.
677
+ * Changing the URL, form or ref clears the ETag and the last commit (the next refresh reads
678
+ * everything again); a new URL gets its form from {@link marketplaceForm} unless `form` is
679
+ * given. `ref: null` follows the remote HEAD. Switching the form clears the other form's field
680
+ * (the ref when becoming http, the mirrors when becoming git) unless the patch sets it.
565
681
  */
566
682
  async update(actor, id, patch, opts = {}) {
567
683
  const name = patch.name !== undefined ? this.checkName(patch.name) : undefined;
@@ -579,15 +695,17 @@ let MarketplacesService = class MarketplacesService {
579
695
  .executeTakeFirst());
580
696
  if (!row)
581
697
  throw notFound();
582
- if (row.builtin &&
583
- (name !== undefined ||
584
- patch.url !== undefined ||
585
- patch.form !== undefined ||
586
- patch.ref !== undefined ||
587
- patch.mirrors !== undefined ||
588
- patch.token !== undefined)) {
698
+ const editsMore = name !== undefined ||
699
+ patch.url !== undefined ||
700
+ patch.form !== undefined ||
701
+ patch.ref !== undefined ||
702
+ patch.mirrors !== undefined ||
703
+ patch.token !== undefined ||
704
+ patch.username !== undefined;
705
+ if (row.builtin && editsMore)
589
706
  throw builtinErr("changed");
590
- }
707
+ if (row.managed === "config" && editsMore)
708
+ throw configManagedErr("changed");
591
709
  const target = patch.url !== undefined || patch.form !== undefined
592
710
  ? marketplaceForm(patch.url ?? row.url, patch.form)
593
711
  : { form: row.form, url: row.url };
@@ -600,6 +718,7 @@ let MarketplacesService = class MarketplacesService {
600
718
  this.checkGitFields(target.form, ref, mirrors);
601
719
  if (typeof patch.token === "string")
602
720
  this.checkToken(patch.token);
721
+ const username = patch.username === undefined ? row.username : this.checkUsername(patch.username ?? undefined);
603
722
  const changed = [];
604
723
  const set = {};
605
724
  if (name !== undefined && name !== row.name) {
@@ -626,6 +745,10 @@ let MarketplacesService = class MarketplacesService {
626
745
  set.mirrors = JSON.stringify(mirrors);
627
746
  changed.push("mirrors");
628
747
  }
748
+ if (username !== row.username) {
749
+ set.username = username;
750
+ changed.push("username");
751
+ }
629
752
  if (patch.enabled !== undefined && patch.enabled !== row.enabled) {
630
753
  set.enabled = patch.enabled;
631
754
  changed.push("enabled");
@@ -660,6 +783,7 @@ let MarketplacesService = class MarketplacesService {
660
783
  ...(set.url !== undefined && { url: set.url }),
661
784
  ...(set.form !== undefined && { form: set.form }),
662
785
  ...(set.ref !== undefined && { ref: set.ref }),
786
+ ...(set.username !== undefined && { username: set.username }),
663
787
  ...opts.auditDetail,
664
788
  },
665
789
  });
@@ -667,14 +791,15 @@ let MarketplacesService = class MarketplacesService {
667
791
  /**
668
792
  * Deletes a custom marketplace (audit `marketplace.removed`): its cached entries and token
669
793
  * are deleted; imported catalog items are kept (their marketplace becomes null). Official can
670
- * only be disabled -> `marketplace.builtin`.
794
+ * only be disabled -> `marketplace.builtin`; a config-managed one ->
795
+ * `marketplace.config_managed`.
671
796
  */
672
797
  async remove(actor, id, opts = {}) {
673
798
  const t = this.db;
674
799
  await this.adminLock.lockAndAuthorize(actor);
675
800
  const row = await t
676
801
  .selectFrom("marketplaces")
677
- .select(["builtin", "name", "url"])
802
+ .select(["builtin", "managed", "name", "url"])
678
803
  .where("id", "=", id)
679
804
  .forUpdate()
680
805
  .executeTakeFirst();
@@ -682,6 +807,8 @@ let MarketplacesService = class MarketplacesService {
682
807
  throw notFound();
683
808
  if (row.builtin)
684
809
  throw builtinErr("deleted");
810
+ if (row.managed === "config")
811
+ throw configManagedErr("deleted");
685
812
  await t.deleteFrom("marketplaces").where("id", "=", id).execute();
686
813
  await this.secrets().delete(DEPLOYMENT_SECRETS_ORG, tokenKey(id));
687
814
  await audit(t, {
@@ -717,9 +844,8 @@ let MarketplacesService = class MarketplacesService {
717
844
  ? "The official marketplace is disabled by marketplaces.official.enabled (offline mode)"
718
845
  : "This marketplace is disabled; enable it before refreshing");
719
846
  }
720
- const token = row.builtin
721
- ? undefined
722
- : ((await this.secrets().get(DEPLOYMENT_SECRETS_ORG, tokenKey(id))) ?? undefined);
847
+ const creds = await this.credentialsOf(row);
848
+ const token = creds.token;
723
849
  const tokenOrigin = new URL(row.url).origin;
724
850
  const errors = [];
725
851
  // the API code of each failed URL (undefined: an ordinary fetch failure)
@@ -730,7 +856,7 @@ let MarketplacesService = class MarketplacesService {
730
856
  let outcome;
731
857
  if (row.form === "git") {
732
858
  try {
733
- outcome = await this.fetchGit(row, token, signal);
859
+ outcome = await this.fetchGit(row, creds, signal);
734
860
  }
735
861
  catch (e) {
736
862
  if (!(e instanceof GitSourceError || e instanceof MarketplaceInvalidError))
@@ -781,7 +907,7 @@ let MarketplacesService = class MarketplacesService {
781
907
  // the branch heads of imported branch-following git entries (outside the transaction)
782
908
  const heads = outcome === undefined
783
909
  ? new Map()
784
- : await this.resolveHeads(id, outcome === "not_modified" ? undefined : outcome.manifest.plugins, { url: row.url, token }, signal);
910
+ : await this.resolveHeads(id, outcome === "not_modified" ? undefined : outcome.manifest.plugins, { url: row.url, ...creds }, signal);
785
911
  const lastError = status === "error" ? errors.join("\n").slice(0, MAX_ERROR_CHARS) : null;
786
912
  const from = await this.recordRefresh(row, { outcome, heads, status, lastError }, actor, opts);
787
913
  if (from === "stale") {
@@ -835,13 +961,17 @@ let MarketplacesService = class MarketplacesService {
835
961
  * with source path `.`, named by plugin.json or, for a skills-only repo, by the repo name
836
962
  * (Decision 3). Throws {@link GitSourceError} or {@link MarketplaceInvalidError}.
837
963
  */
838
- async fetchGit(row, token, signal) {
964
+ async fetchGit(row, creds, signal) {
839
965
  const config = this.config.get();
840
966
  const options = {
841
967
  net: marketplaceNetPolicy(config),
842
968
  maxBytes: config.packages.maxBytes,
843
969
  signal,
844
- ...(token !== undefined && { token, tokenOrigin: new URL(row.url).origin }),
970
+ ...(creds.token !== undefined && {
971
+ token: creds.token,
972
+ tokenOrigin: new URL(row.url).origin,
973
+ ...(creds.username !== undefined && { username: creds.username }),
974
+ }),
845
975
  };
846
976
  const loc = { url: row.url, ...(row.ref !== null && { ref: row.ref }) };
847
977
  const commit = await resolveGitCommit(loc, options);
@@ -1000,7 +1130,11 @@ let MarketplacesService = class MarketplacesService {
1000
1130
  net: marketplaceNetPolicy(config),
1001
1131
  maxBytes: config.packages.maxBytes,
1002
1132
  signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
1003
- ...(m.token !== undefined && { token: m.token, tokenOrigin: new URL(m.url).origin }),
1133
+ ...(m.token !== undefined && {
1134
+ token: m.token,
1135
+ tokenOrigin: new URL(m.url).origin,
1136
+ ...(m.username !== undefined && { username: m.username }),
1137
+ }),
1004
1138
  };
1005
1139
  try {
1006
1140
  const commit = await resolveGitCommit({ url: git.url, ...(git.ref !== undefined && { ref: git.ref }) }, options);
@@ -1218,9 +1352,37 @@ let MarketplacesService = class MarketplacesService {
1218
1352
  }
1219
1353
  return { contentType: checked.contentType, data };
1220
1354
  }
1221
- /** The token of a custom marketplace (undefined without one; official never has one). */
1222
- async token(id) {
1223
- return (await this.secrets().get(DEPLOYMENT_SECRETS_ORG, tokenKey(id))) ?? undefined;
1355
+ /**
1356
+ * The git / http credential of a marketplace: none for official; a config-managed one's token
1357
+ * from `marketplaces.tokens[name]` (never the secrets table); a custom one's from secrets. The
1358
+ * username is the stored one (absent: the default `x-access-token`). Missing -> `{}`.
1359
+ */
1360
+ async credentials(id) {
1361
+ const row = await this.db
1362
+ .selectFrom("marketplaces")
1363
+ .select(["id", "builtin", "managed", "username"])
1364
+ .where("id", "=", id)
1365
+ .executeTakeFirst();
1366
+ return row === undefined ? {} : this.credentialsOf(row);
1367
+ }
1368
+ async credentialsOf(row) {
1369
+ if (row.builtin)
1370
+ return {};
1371
+ const token = row.managed === "config"
1372
+ ? this.configToken(row.id)
1373
+ : ((await this.secrets().get(DEPLOYMENT_SECRETS_ORG, tokenKey(row.id))) ?? undefined);
1374
+ return {
1375
+ ...(token !== undefined && { token }),
1376
+ ...(row.username !== null && { username: row.username }),
1377
+ };
1378
+ }
1379
+ /** The `marketplaces.tokens` entry of a config-managed marketplace (`config:<name>`). */
1380
+ configToken(id) {
1381
+ if (!id.startsWith(CONFIG_MARKETPLACE_PREFIX))
1382
+ return undefined;
1383
+ const tokens = this.config.get().marketplaces.tokens;
1384
+ const name = id.slice(CONFIG_MARKETPLACE_PREFIX.length);
1385
+ return Object.hasOwn(tokens, name) ? tokens[name] : undefined;
1224
1386
  }
1225
1387
  /** Refreshes every effective marketplace (maintenance job `catalogs-refresh`), one failing not stopping the rest. */
1226
1388
  async refreshAll(signal) {
@@ -1519,7 +1681,11 @@ let MarketplacesService = class MarketplacesService {
1519
1681
  builtin: r.builtin,
1520
1682
  enabled: sourceEffective(r, config),
1521
1683
  disabledByConfig: r.builtin && !config.marketplaces.official.enabled,
1522
- hasToken: hasToken.has(tokenKey(r.id)),
1684
+ managed: r.managed,
1685
+ username: r.username,
1686
+ hasToken: r.managed === "config"
1687
+ ? this.configToken(r.id) !== undefined
1688
+ : hasToken.has(tokenKey(r.id)),
1523
1689
  etag: r.etag,
1524
1690
  lastRefreshedAt: r.last_refreshed_at?.toISOString() ?? null,
1525
1691
  lastStatus: r.last_status,
@@ -1563,12 +1729,24 @@ let MarketplacesService = class MarketplacesService {
1563
1729
  throw new ApiError("validation_failed", "ref must be 1–256 characters without spaces");
1564
1730
  }
1565
1731
  }
1732
+ /** A username outside `GIT_USERNAME_RE` -> `validation_failed`; empty or absent -> null. */
1733
+ checkUsername(username) {
1734
+ if (username === undefined || username === "")
1735
+ return null;
1736
+ if (!GIT_USERNAME_RE.test(username)) {
1737
+ throw new ApiError("validation_failed", "username must match ^[A-Za-z0-9._-]{1,64}$");
1738
+ }
1739
+ return username;
1740
+ }
1566
1741
  checkToken(token) {
1567
1742
  if (token.length < 1 || token.length > MAX_TOKEN_CHARS || /[\r\n]/.test(token)) {
1568
1743
  throw new ApiError("validation_failed", `token must be 1–${MAX_TOKEN_CHARS} characters without line breaks`);
1569
1744
  }
1570
1745
  }
1571
1746
  };
1747
+ __decorate([
1748
+ Transactional()
1749
+ ], MarketplacesService.prototype, "syncExtraFromConfig", null);
1572
1750
  __decorate([
1573
1751
  Transactional()
1574
1752
  ], MarketplacesService.prototype, "writeAdd", null);
@@ -93,11 +93,13 @@ export declare const KernelConfigSchema: z.ZodObject<{
93
93
  }, z.core.$strict>>;
94
94
  bootstrap: z.ZodPrefault<z.ZodObject<{
95
95
  dir: z.ZodDefault<z.ZodString>;
96
+ extraManifest: z.ZodOptional<z.ZodString>;
96
97
  }, z.core.$strict>>;
97
98
  catalog: z.ZodPrefault<z.ZodObject<{
98
99
  staleInstallMinutes: z.ZodDefault<z.ZodNumber>;
99
100
  }, z.core.$strict>>;
100
101
  marketplaces: z.ZodPrefault<z.ZodObject<{
102
+ tokens: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
101
103
  official: z.ZodPrefault<z.ZodObject<{
102
104
  enabled: z.ZodDefault<z.ZodBoolean>;
103
105
  url: z.ZodDefault<z.ZodURL>;
@@ -1,5 +1,5 @@
1
1
  import { isIP } from "node:net";
2
- import { DOCUMENT_MEDIA_TYPES, IMAGE_MEDIA_TYPES, validateAllowHost, } from "@capybara-hq/plugin-sdk";
2
+ import { CATALOG_ITEM_NAME_RE, DOCUMENT_MEDIA_TYPES, IMAGE_MEDIA_TYPES, validateAllowHost, } from "@capybara-hq/plugin-sdk";
3
3
  import { z } from "zod";
4
4
  import { LOG_FORMATS, LOG_LEVELS } from "../log.js";
5
5
  import { noProxyEntryProblem, proxyUrlProblem } from "../net/proxy.js";
@@ -452,6 +452,13 @@ export const KernelConfigSchema = z.strictObject({
452
452
  .meta(meta({
453
453
  description: "Offline directory for the bootstrap plugins, resolved against the working directory (/app/bootstrap in the image): a .tgz file here whose sha512 matches a pinned plugin is installed instead of downloading it from packages.npmRegistry",
454
454
  })),
455
+ extraManifest: z
456
+ .string()
457
+ .min(1)
458
+ .optional()
459
+ .meta(meta({
460
+ description: "Path of a bootstrap-extra.v1 manifest, resolved against the working directory like bootstrap.dir, that is merged with the built-in bootstrap manifest (extra plugins and marketplaces for a distribution). Absent by default",
461
+ })),
455
462
  })
456
463
  .prefault({}),
457
464
  catalog: z
@@ -468,6 +475,19 @@ export const KernelConfigSchema = z.strictObject({
468
475
  .prefault({}),
469
476
  marketplaces: z
470
477
  .strictObject({
478
+ tokens: z
479
+ .record(z.string().regex(CATALOG_ITEM_NAME_RE, {
480
+ message: "marketplace name must match ^[a-z0-9][a-z0-9-]{0,63}$",
481
+ }), z
482
+ .string()
483
+ .min(1)
484
+ .max(4096)
485
+ .refine((t) => !/[\r\n]/.test(t), { message: "a token must not contain a newline" }))
486
+ .default({})
487
+ .meta(meta({
488
+ description: "Access tokens by marketplace name for the marketplaces the extra bootstrap manifest declares (bootstrap.extraManifest); never put a token in the manifest file",
489
+ secret: true,
490
+ })),
471
491
  official: z
472
492
  .strictObject({
473
493
  enabled: z
@@ -2181,6 +2181,10 @@ export interface MarketplacesTable {
2181
2181
  }[], string | undefined, string>;
2182
2182
  /** 0101: the git commit whose repository-path icons were last stored completely. */
2183
2183
  icons_commit: ColumnType<string | null, string | null | undefined, string | null>;
2184
+ /** 0169: `config` when the deployment config (bootstrap.extraManifest) owns the row. */
2185
+ managed: ColumnType<"config" | null, "config" | null | undefined, "config" | null>;
2186
+ /** 0169: the Basic auth username sent with the git token (null: x-access-token). */
2187
+ username: ColumnType<string | null, string | null | undefined, string | null>;
2184
2188
  }
2185
2189
  /**
2186
2190
  * 0035, renamed in 0042, reshaped in 0044: cached marketplace entries (replaced as a whole on each
package/dist/errors.d.ts CHANGED
@@ -147,6 +147,12 @@ export declare const ERROR_CODES: {
147
147
  readonly "bootstrap.integrity_mismatch": 500;
148
148
  readonly "bootstrap.download_failed": 502;
149
149
  readonly "bootstrap.missing_file": 500;
150
+ /** The extra bootstrap manifest cannot be read, is invalid, or a git entry's marketplace is not git form. */
151
+ readonly "bootstrap.extra_invalid": 500;
152
+ /** The extra bootstrap manifest names a plugin the built-in manifest already pins. */
153
+ readonly "bootstrap.extra_conflict": 500;
154
+ /** A git entry's tree cannot be read from its marketplace (the git error, never the token). */
155
+ readonly "bootstrap.git_read_failed": 502;
150
156
  readonly "catalog.invalid_manifest": 422;
151
157
  readonly "catalog.no_extension": 409;
152
158
  readonly "catalog.dependency_unresolved": 409;
@@ -280,6 +286,7 @@ export declare const ERROR_CODES: {
280
286
  readonly "marketplace.entry_deprecated": 409;
281
287
  readonly "marketplace.package_mismatch": 409;
282
288
  readonly "marketplace.builtin": 409;
289
+ readonly "marketplace.config_managed": 409;
283
290
  readonly "marketplace.git_failed": 502;
284
291
  readonly "marketplace.git_too_large": 422;
285
292
  readonly "marketplace.git_unsupported_entry": 422;
package/dist/errors.js CHANGED
@@ -147,6 +147,12 @@ export const ERROR_CODES = {
147
147
  "bootstrap.integrity_mismatch": 500,
148
148
  "bootstrap.download_failed": 502,
149
149
  "bootstrap.missing_file": 500,
150
+ /** The extra bootstrap manifest cannot be read, is invalid, or a git entry's marketplace is not git form. */
151
+ "bootstrap.extra_invalid": 500,
152
+ /** The extra bootstrap manifest names a plugin the built-in manifest already pins. */
153
+ "bootstrap.extra_conflict": 500,
154
+ /** A git entry's tree cannot be read from its marketplace (the git error, never the token). */
155
+ "bootstrap.git_read_failed": 502,
150
156
  "catalog.invalid_manifest": 422,
151
157
  "catalog.no_extension": 409,
152
158
  "catalog.dependency_unresolved": 409,
@@ -280,6 +286,7 @@ export const ERROR_CODES = {
280
286
  "marketplace.entry_deprecated": 409,
281
287
  "marketplace.package_mismatch": 409,
282
288
  "marketplace.builtin": 409,
289
+ "marketplace.config_managed": 409,
283
290
  "marketplace.git_failed": 502,
284
291
  "marketplace.git_too_large": 422,
285
292
  "marketplace.git_unsupported_entry": 422,
@@ -0,0 +1,24 @@
1
+ import { SettingsService } from "../identity/settings.js";
2
+ import { KernelDb } from "../infra/database/kernel-db.js";
3
+ import type { KernelLogger } from "../log.js";
4
+ /**
5
+ * The deployment defaults of the extra bootstrap manifest (bootstrap extra manifest spec §7),
6
+ * applied at every kernel start after the extensions loaded (and the bootstrap step's second pass),
7
+ * whether or not the step ran in that start: cheap, and a no-op once applied or once a super admin
8
+ * chose, so a default that could not be applied yet (its theme not imported, not eligible) is
9
+ * retried at the next start. Never fails the start.
10
+ */
11
+ export declare class BootstrapDefaultsService {
12
+ private readonly db;
13
+ private readonly settings;
14
+ private readonly log;
15
+ constructor(db: KernelDb, settings: SettingsService, log: Pick<KernelLogger, "info" | "warn" | "error">);
16
+ /**
17
+ * `defaultTheme`: the platform default theme, `(plugin, theme)` resolved to the live
18
+ * platform-owned `platform_themes` row and handed to {@link SettingsService.applyBootstrapUiTheme}.
19
+ */
20
+ apply(defaultTheme?: {
21
+ plugin: string;
22
+ theme: string;
23
+ }): Promise<void>;
24
+ }
@@ -0,0 +1,78 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { ApiError } from "../errors.js";
12
+ import { SettingsService } from "../identity/settings.js";
13
+ import { KernelDb } from "../infra/database/kernel-db.js";
14
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
15
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
16
+ /**
17
+ * The deployment defaults of the extra bootstrap manifest (bootstrap extra manifest spec §7),
18
+ * applied at every kernel start after the extensions loaded (and the bootstrap step's second pass),
19
+ * whether or not the step ran in that start: cheap, and a no-op once applied or once a super admin
20
+ * chose, so a default that could not be applied yet (its theme not imported, not eligible) is
21
+ * retried at the next start. Never fails the start.
22
+ */
23
+ let BootstrapDefaultsService = class BootstrapDefaultsService {
24
+ db;
25
+ settings;
26
+ log;
27
+ constructor(db, settings, log) {
28
+ this.db = db;
29
+ this.settings = settings;
30
+ this.log = log;
31
+ }
32
+ /**
33
+ * `defaultTheme`: the platform default theme, `(plugin, theme)` resolved to the live
34
+ * platform-owned `platform_themes` row and handed to {@link SettingsService.applyBootstrapUiTheme}.
35
+ */
36
+ async apply(defaultTheme) {
37
+ if (defaultTheme === undefined)
38
+ return;
39
+ const fields = { plugin: defaultTheme.plugin, theme: defaultTheme.theme };
40
+ try {
41
+ // Resolved outside the transaction; applyBootstrapUiTheme re-validates it under the locks
42
+ // (assertPlatformDefaultEligible)
43
+ const row = await this.db
44
+ .selectFrom("platform_themes")
45
+ .select("id")
46
+ .where("plugin_name", "=", defaultTheme.plugin)
47
+ .where("name", "=", defaultTheme.theme)
48
+ .where("deleted_at", "is", null)
49
+ .where("owner_org_id", "is", null)
50
+ .executeTakeFirst();
51
+ if (row === undefined) {
52
+ this.log.warn("bootstrap: the default theme is not installed; retried on the next start", fields);
53
+ return;
54
+ }
55
+ const outcome = await this.settings.applyBootstrapUiTheme(row.id);
56
+ if (outcome === "applied") {
57
+ this.log.info("bootstrap: the default theme is the platform default", fields);
58
+ }
59
+ }
60
+ catch (e) {
61
+ if (e instanceof ApiError && e.code === "theme.not_available") {
62
+ this.log.warn("bootstrap: the default theme cannot be the platform default; retried on the next start", { ...fields, error: e.message });
63
+ return;
64
+ }
65
+ this.log.error("bootstrap: the default theme could not be applied; retried on the next start", {
66
+ ...fields,
67
+ error: errMsg(e),
68
+ });
69
+ }
70
+ }
71
+ };
72
+ BootstrapDefaultsService = __decorate([
73
+ Injectable(),
74
+ __param(0, Inject(KernelDb)),
75
+ __param(1, Inject(SettingsService)),
76
+ __param(2, Inject(KERNEL_LOGGER))
77
+ ], BootstrapDefaultsService);
78
+ export { BootstrapDefaultsService };