@jini-ai/devops 0.7.3-next.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/backup/site/backup-service.credentials.js +2 -5
  3. package/dist/backup/site/backup-service.d.ts +5 -0
  4. package/dist/backup/site/backup-service.js +4 -2
  5. package/dist/backup/site/backup-service.push.d.ts +2 -2
  6. package/dist/backup/site/backup-service.push.js +15 -3
  7. package/dist/backup/site/bundled-export-file-policy.js +5 -6
  8. package/dist/backup/site/share-database/projection.d.ts +2 -0
  9. package/dist/backup/site/share-database/projection.tables.js +18 -1
  10. package/dist/backup/site/share-preparation-steps.js +2 -4
  11. package/dist/backup/site/static-export-selection.js +1 -2
  12. package/dist/backup/site/tool-registrations.js +5 -2
  13. package/dist/checks/coverage/lcov.js +1 -1
  14. package/dist/checks/env-access.js +1 -1
  15. package/dist/deploy/react/StaticCredentialSteps.js +3 -6
  16. package/dist/deploy/site/deploy-targets/registry.js +1 -3
  17. package/dist/deploy/site/publish-credentials/store.d.ts +14 -15
  18. package/dist/deploy/site/publish-credentials/store.js +10 -15
  19. package/dist/deploy/site/static-publish/admin-publish-read.js +4 -2
  20. package/dist/deploy/site/static-publish/credentials.d.ts +5 -1
  21. package/dist/deploy/site/static-publish/credentials.js +12 -4
  22. package/dist/deploy/site/static-publish/types.d.ts +3 -0
  23. package/dist/deploy/site/static-publish/verify.d.ts +20 -0
  24. package/dist/deploy/site/static-publish/verify.js +41 -5
  25. package/dist/packaging/electron/update-manifest-merge.js +0 -2
  26. package/dist/static-export/asset-crawl.d.ts +30 -0
  27. package/dist/static-export/asset-crawl.js +71 -0
  28. package/dist/static-export/dynamic-asset-locations.d.ts +23 -0
  29. package/dist/static-export/dynamic-asset-locations.js +34 -0
  30. package/dist/static-export/html-url-locations.d.ts +3 -1
  31. package/dist/static-export/html-url-locations.js +43 -9
  32. package/dist/static-export/runner.js +26 -27
  33. package/dist/static-export/transforms.d.ts +1 -1
  34. package/dist/static-export/transforms.js +3 -3
  35. package/package.json +8 -8
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # @jini-ai/devops
2
2
 
3
+ ## 0.7.4
4
+
5
+ ### Changes
6
+
7
+ - Add reusable deployment, static export, DNS, and approved site-update workflows with host-supplied ports.
8
+ - Forward publish cancellation, honor the selected credential, and correct missing srcset assets and bounded retention sweeps.
9
+
3
10
  ## 0.7.2
4
11
 
5
12
  ### Patch Changes
@@ -41,12 +41,9 @@ async function pickCredentialLabel({ deps, providers, requested }, _optional = {
41
41
  const apiOrigins = providers.map((provider) => provider.apiOrigin);
42
42
  const where = apiOrigins.join(" or ");
43
43
  const matching = saved.filter((credential) => apiOrigins.includes(originOf({ url: credential.baseUrl }) ?? "")).map((credential) => credential.label);
44
- if (matching.length === 1) {
45
- const label = matching[0];
46
- if (label === undefined)
47
- throw new Error("Backup credential match has no label");
44
+ const [label] = matching;
45
+ if (matching.length === 1 && label !== undefined)
48
46
  return { ok: true, label };
49
- }
50
47
  if (matching.length === 0) {
51
48
  return {
52
49
  ok: false,
@@ -272,6 +272,11 @@ export declare function planSiteBackup<TSource extends SiteBackupSources, TConte
272
272
  deps: SiteBackupToolDeps<TSource, TContent, TRequest>;
273
273
  call: SiteBackupCall;
274
274
  }, _optional?: Record<string, never>): Promise<unknown>;
275
+ export interface SiteBackupPushInput {
276
+ readonly planId: string;
277
+ /** Confirms the reviewed warnings for this private-repository push; preserves the original bytes. */
278
+ readonly acknowledgeCredentialWarnings?: boolean;
279
+ }
275
280
  export type PushResult = {
276
281
  pushed: true;
277
282
  commitSha: string;
@@ -95,7 +95,9 @@ export async function planSiteBackup(required, _optional = {}) {
95
95
  */
96
96
  export async function pushSiteBackup(required, optional = {}) {
97
97
  const { deps, call: ctx } = required;
98
- const planId = requireString({ input: requireInputRecord({ input: ctx.input }), key: "planId" });
98
+ const input = requireInputRecord({ input: ctx.input });
99
+ const planId = requireString({ input, key: "planId" });
100
+ const acknowledgeCredentialWarnings = input["acknowledgeCredentialWarnings"] === true;
99
101
  await requireBackupPermissions(deps, ctx);
100
102
  if (ctx.signal.aborted)
101
103
  return { pushed: false, cancelled: false, reason: "abandoned" };
@@ -106,7 +108,7 @@ export async function pushSiteBackup(required, optional = {}) {
106
108
  const taken = (deps.request.siteBackupPlanStore ?? deps.siteBackupPlanStore).take(key);
107
109
  if (!taken.ok)
108
110
  return { pushed: false, cancelled: false, code: taken.code, message: PLAN_TAKE_MESSAGES[taken.code] };
109
- job = jobs.start({ key, progress: deps.initialPushProgress({ plan: taken.plan }), run: ({ signal, progress }) => runObservedBackupPush({ deps, plan: taken.plan, run: { signal, progress } }) });
111
+ job = jobs.start({ key, progress: deps.initialPushProgress({ plan: taken.plan }), run: ({ signal, progress }) => runObservedBackupPush({ deps, plan: taken.plan, acknowledgeCredentialWarnings, run: { signal, progress } }) });
110
112
  }
111
113
  const waited = await jobs.wait({ job, signal: ctx.signal, budgetMs: pushWaitBudget({ deps, waitMs: optional.waitMs }) });
112
114
  if (waited.state === "done")
@@ -1,6 +1,6 @@
1
1
  import type { SiteBackupSources } from "./sources.js";
2
2
  import type { SiteBackupPushProgress } from "../push-jobs.js";
3
- import type { SiteBackupRequestDeps, SiteBackupRepositoryPlanContent, SiteBackupToolDeps, SiteBackupPlan, PushResult } from "./backup-service.js";
3
+ import type { SiteBackupRequestDeps, SiteBackupRepositoryPlanContent, SiteBackupToolDeps, SiteBackupPlan, SiteBackupPushInput, PushResult } from "./backup-service.js";
4
4
  export declare function runObservedBackupPush<TSource extends SiteBackupSources, TContent extends SiteBackupRepositoryPlanContent, TRequest extends SiteBackupRequestDeps<TSource, TContent>>(required: {
5
5
  deps: SiteBackupToolDeps<TSource, TContent, TRequest>;
6
6
  plan: SiteBackupPlan<TContent>;
@@ -8,7 +8,7 @@ export declare function runObservedBackupPush<TSource extends SiteBackupSources,
8
8
  signal: AbortSignal;
9
9
  progress: SiteBackupPushProgress;
10
10
  };
11
- }): Promise<PushResult>;
11
+ } & Pick<SiteBackupPushInput, "acknowledgeCredentialWarnings">): Promise<PushResult>;
12
12
  export declare const PLAN_TAKE_MESSAGES: {
13
13
  readonly PLAN_NOT_FOUND: "no backup plan with that planId is waiting (a planId works once, for this principal, and a server restart drops plans). Call site_backup_plan again.";
14
14
  readonly PLAN_EXPIRED: "that backup plan expired (plans last 10 minutes). Call site_backup_plan again.";
@@ -6,6 +6,17 @@ function pushRefusal(refusal, cancelledCode) {
6
6
  function backupBlobUploadOptions(provider) {
7
7
  return provider.backupInlineTextMaxBytes === undefined ? {} : { inlineTextMaxBytes: provider.backupInlineTextMaxBytes };
8
8
  }
9
+ function unacknowledgedCredentialWarnings({ plan, acknowledgeCredentialWarnings }) {
10
+ if (!plan.credentialWarnings?.length || acknowledgeCredentialWarnings === true)
11
+ return undefined;
12
+ // The scanner stores redacted locations and fixed kind labels, never matched secret values.
13
+ const files = plan.credentialWarnings.map(({ path, kind }) => `${path} (${kind})`).join("; ");
14
+ return {
15
+ ok: false, code: "UNSAFE_FILE",
16
+ message: `The backup contains files with possible credentials: ${files}. Nothing was written. ` +
17
+ "Call site_backup_plan again, review every warning, then call site_backup_push with the new planId and acknowledgeCredentialWarnings: true to back up the original bytes to this private repository.",
18
+ };
19
+ }
9
20
  /**
10
21
  * The authorized push: re-resolve the credential, re-check the repository (still
11
22
  * private, branch not moved), upload, commit on the PLAN's parent. Stopping (`signal`) takes effect
@@ -14,7 +25,7 @@ function backupBlobUploadOptions(provider) {
14
25
  * @complexity O(total bytes); see Jini's `backup/site/push-content` for the uploads, plus a few fixed tree writes,
15
26
  * one commit and one ref update.
16
27
  */
17
- async function pushPlannedBackup({ deps, plan, run }, _optional = {}) {
28
+ async function pushPlannedBackup({ deps, plan, run, acknowledgeCredentialWarnings = false }, _optional = {}) {
18
29
  const credential = await resolveBackupCredential({ deps, requested: plan.credentialLabel });
19
30
  if (!credential.ok)
20
31
  return pushRefusal(credential, deps.cancelled.code);
@@ -29,8 +40,9 @@ async function pushPlannedBackup({ deps, plan, run }, _optional = {}) {
29
40
  message: `branch '${plan.repository.branch}' moved since the backup was planned (someone pushed to it). Nothing was written. Call site_backup_plan again.`,
30
41
  }, deps.cancelled.code);
31
42
  }
32
- if (plan.credentialWarnings?.length)
33
- return pushRefusal({ ok: false, code: "UNSAFE_FILE", message: "The export contains files with possible credentials. Remove the credentials and export again." }, deps.cancelled.code);
43
+ const warningRefusal = unacknowledgedCredentialWarnings({ plan, acknowledgeCredentialWarnings });
44
+ if (warningRefusal)
45
+ return pushRefusal(warningRefusal, deps.cancelled.code);
34
46
  const uploaded = await deps.uploadBackupPlan({
35
47
  plan, signal: run.signal, progress: run.progress, ...deps.backupPushUploadPolicy({ plan }),
36
48
  uploadBlob: async (file, _optional = {}) => {
@@ -15,17 +15,16 @@ export function createBundledExportFilePolicy(required, optional = {}) {
15
15
  const specifier = selection.get(pluginId);
16
16
  if (!specifier)
17
17
  return null;
18
- if (!roots.has(pluginId)) {
18
+ let root = roots.get(pluginId);
19
+ if (root === undefined) {
19
20
  try {
20
- roots.set(pluginId, path.dirname(resolve(`${specifier}/plugin.json`)));
21
+ root = path.dirname(resolve(`${specifier}/plugin.json`));
21
22
  }
22
23
  catch {
23
- roots.set(pluginId, null);
24
+ root = null;
24
25
  }
26
+ roots.set(pluginId, root);
25
27
  }
26
- const root = roots.get(pluginId);
27
- if (root === undefined)
28
- throw new Error(`Bundled plugin ${pluginId} has no resolved root`);
29
28
  if (root === null)
30
29
  return null;
31
30
  return read(path.join(root, relativePath));
@@ -84,6 +84,8 @@ export interface ShareProjectionHost {
84
84
  db: Kernel;
85
85
  dbPath: string;
86
86
  decl: DataModuleDecl;
87
+ }, optional?: {
88
+ report?: Pick<import('@jini-ai/core/primitives').Logger, 'warn' | 'error'>;
87
89
  }): Promise<{
88
90
  ok: boolean;
89
91
  error?: {
@@ -51,7 +51,8 @@ function portableColumnsOnly(required, _options = {}) {
51
51
  * Logs the redacted declaration diagnostic; only the fixed refusal crosses the worker boundary.
52
52
  * @throws SiteShareRefusal when the owner refuses. O(declaration + diagnostic bytes). */
53
53
  async function declarePortableTables(required, { logger = createConsoleLogger({ prefix: "[site-share]" }) } = {}) {
54
- const result = await required.host.deps.declareDataModule({ db: required.target, dbPath: ":memory:", decl: { ...required.decl, tables: required.tables } });
54
+ const report = redactingSchemaReport({ host: required.host, logger });
55
+ const result = await required.host.deps.declareDataModule({ db: required.target, dbPath: ":memory:", decl: { ...required.decl, tables: required.tables } }, { report });
55
56
  if (result.ok)
56
57
  return;
57
58
  // A typed refusal is written verbatim to refusal.txt, so native error text belongs only in logs.
@@ -60,6 +61,22 @@ async function declarePortableTables(required, { logger = createConsoleLogger({
60
61
  });
61
62
  throw new SiteShareRefusal({ code: "UNSUPPORTED_SCHEMA", message: `Cannot build portable plugin schema for '${required.decl.pluginId}': the bundled portable-data declaration could not be installed.` });
62
63
  }
64
+ /** Native errors are intentionally private diagnostics, but must be redacted before any sink. */
65
+ function redactingSchemaReport({ host, logger }, _optional = {}) {
66
+ const write = (required, optional = {}) => {
67
+ let diagnostic;
68
+ try {
69
+ diagnostic = JSON.stringify({ ...required, ...optional }, (_key, value) => value instanceof Error ? { ...value, name: value.name, message: value.message, stack: value.stack, cause: value.cause } : value) ?? 'Schema diagnostic could not be read';
70
+ }
71
+ catch {
72
+ diagnostic = 'Schema diagnostic could not be read';
73
+ }
74
+ logger.error({ message: 'Portable plugin schema diagnostic' }, {
75
+ meta: { diagnostic: host.redactSecretShapes({ text: diagnostic }).text },
76
+ });
77
+ };
78
+ return { warn: write, error: write };
79
+ }
63
80
  /** Refuse populated undeclared tables by name before any portable-row projection.
64
81
  * Never executes source DDL; `listTables` omits SQLite's own `sqlite_*` tables.
65
82
  * @throws SiteShareRefusal UNSUPPORTED_DATA with the table and required policy.
@@ -31,10 +31,8 @@ export function createShareSteps(deps) {
31
31
  /** Collects the share profile's files (never the media folder); any skipped file refuses by name. */
32
32
  async function collectShareFiles(required) {
33
33
  const collected = await deps.collectFiles({ sources: required.sources, include: { ...required.include, media: false } }, { profile: "share" });
34
- if (collected.skipped.length) {
35
- const skipped = collected.skipped[0];
36
- if (skipped === undefined)
37
- throw new Error("Share export has no skipped-file details");
34
+ const [skipped] = collected.skipped;
35
+ if (skipped) {
38
36
  throw new SiteShareRefusal({ code: "UNSAFE_FILE", message: `Cannot share '${skipped.path}': ${skipped.reason}. Remove it or replace it with a regular file.` });
39
37
  }
40
38
  return collected;
@@ -67,9 +67,8 @@ export function allocateStaticExportThemes({ themeIds, siteSlug, policy }, _opti
67
67
  claimed.add(policy.sharePathAlias({ path: name }));
68
68
  }
69
69
  return themeIds.map(themeId => {
70
+ // The complete roster was allocated above; retain the caller's selection order.
70
71
  const name = names.get(themeId);
71
- if (name === undefined)
72
- throw new Error(`Static export has no allocated folder for theme ${themeId}`);
73
72
  return { themeId, name };
74
73
  });
75
74
  }
@@ -45,7 +45,10 @@ const PUSH_SCHEMA = {
45
45
  type: "object",
46
46
  additionalProperties: false,
47
47
  required: ["planId"],
48
- properties: { planId: { type: "string", description: "The planId site_backup_plan returned. Single-use; valid for 10 minutes." } },
48
+ properties: {
49
+ planId: { type: "string", description: "The planId site_backup_plan returned. Single-use; valid for 10 minutes." },
50
+ acknowledgeCredentialWarnings: { type: "boolean", description: "Set true only after the human reviews and confirms every credential warning in the plan. Allows backing up the original bytes to the private repository. Omit or set false to refuse warned files." },
51
+ },
49
52
  };
50
53
  export function createSiteBackupCatalog(required, _optional = {}) {
51
54
  return [
@@ -64,7 +67,7 @@ export function createSiteBackupCatalog(required, _optional = {}) {
64
67
  inputSchema: { ...PLAN_SCHEMA, properties: { ...PLAN_SCHEMA.properties, commitMessage: { ...PLAN_SCHEMA.properties.commitMessage, description: required.commitDescription } } },
65
68
  },
66
69
  { name: SITE_BACKUP_PUSH_TOOL_ID,
67
- description: "Pushes the single-use plan from site_backup_plan immediately in one non-force Git commit. Requires the original permissions and principal binding, and re-checks that the repository is private, the branch is unchanged and the planned files are fresh. Replaces only the backup folder; previous contents remain recoverable in Git history. Returns {pushed:true, commitSha, commitUrl, repository, branch, folder, filesWritten, totalBytes}. A large backup can take longer than one call: then it returns {pushed:false, cancelled:false, inProgress:true, planId, progress:{filesDone, filesTotal, bytesDone, bytesTotal}, message} while the upload keeps running; tell the human how far it is and call site_backup_push again with the SAME planId to keep waiting (it never starts a second upload). Failures return {pushed:false, cancelled:false, code, message}, including expired/missing plans, changed branches or files, public repositories and credential/provider/network errors; a failed upload names the file. Transient network errors, host errors and rate limits are already retried with backoff, so do not retry NETWORK_UNREACHABLE in a loop. Plan again after PLAN_STALE, DIVERGED_BRANCH or plan expiry.",
70
+ description: "Pushes the single-use plan from site_backup_plan immediately in one non-force Git commit. When the plan has credentialWarnings, show every warned path and kind to the human and pass acknowledgeCredentialWarnings: true only after their explicit confirmation; otherwise the push refuses with UNSAFE_FILE. Acknowledgement preserves the original bytes and applies only to private repository backups. Requires the original permissions and principal binding, and re-checks that the repository is private, the branch is unchanged and the planned files are fresh. Replaces only the backup folder; previous contents remain recoverable in Git history. Returns {pushed:true, commitSha, commitUrl, repository, branch, folder, filesWritten, totalBytes}. A large backup can take longer than one call: then it returns {pushed:false, cancelled:false, inProgress:true, planId, progress:{filesDone, filesTotal, bytesDone, bytesTotal}, message} while the upload keeps running; tell the human how far it is and call site_backup_push again with the SAME planId to keep waiting (it never starts a second upload). Failures return {pushed:false, cancelled:false, code, message}, including expired/missing plans, changed branches or files, public repositories and credential/provider/network errors; a failed upload names the file. Transient network errors, host errors and rate limits are already retried with backoff, so do not retry NETWORK_UNREACHABLE in a loop. Plan again after PLAN_STALE, DIVERGED_BRANCH or plan expiry.",
68
71
  sideEffects: MUTATES_DURABLE_STATE,
69
72
  authorization: { permission: PUSH_PERMISSION },
70
73
  inputSchema: PUSH_SCHEMA,
@@ -38,7 +38,7 @@ export function isMeasurableSourceFile({ file, rules }, _optional = {}) {
38
38
  const parts = normalized.split('/');
39
39
  if (parts.some((part) => rules.excludedDirectories.includes(part)))
40
40
  return false;
41
- if (rules.excludedBasenames.includes(parts.at(-1) ?? ''))
41
+ if (rules.excludedBasenames.includes(normalized.slice(normalized.lastIndexOf('/') + 1)))
42
42
  return false;
43
43
  // Do not mutate a host's global/sticky regex or inherit its lastIndex.
44
44
  return !new RegExp(rules.testPattern.source, rules.testPattern.flags.replace(/[gy]/g, '')).test(normalized);
@@ -58,7 +58,7 @@ function createEnvBindingReads({ compiler: c, staticKey, propertyNameKey }) {
58
58
  function bindingElementKey({ element }) {
59
59
  if (element.propertyName)
60
60
  return propertyNameKey({ name: element.propertyName });
61
- return c.isIdentifier(element.name) ? element.name.text : undefined;
61
+ return element.name.text;
62
62
  }
63
63
  /** `const { A, B: b, ...rest } = process.env`, also as a parameter or binding default: one read per source key. */
64
64
  function bindingReads({ node }) {
@@ -87,7 +87,7 @@ export function CredentialStepDone({ row, controller, t: translate, kit, deps },
87
87
  return (_jsxs("details", { className: "deployment-step deployment-step-done", ...agentHandle({ handle: `deployment-static-site-credentials-row-${row.providerId}` }, {
88
88
  role: "region",
89
89
  label: `${row.label}'s saved publish credential — connected`,
90
- }), children: [_jsxs("summary", { className: "deployment-step-summary", children: [_jsx("span", { className: "deployment-step-marker deployment-step-marker-done", "aria-hidden": "true", children: _jsx(StepDoneIcon, { lineIcon: LINE_ICON, Icon: Icon }) }), _jsx(SavedCredentialSummary, { kit: kit, deps: deps, row: row, saved: saved, t: translate }), _jsx(CredentialVerifyAction, { row: row, controller: controller, t: translate }), _jsxs("span", { className: "deployment-step-summary-action", children: [translate("Replace token"), _jsx(DisclosureChevron, { lineIcon: LINE_ICON, Icon: Icon })] })] }), _jsx(CredentialTokenPicker, { deps: deps, row: row, controller: controller, t: translate }), _jsx(PublishCredentialFields, { kit: kit, deps: deps, row: row, controller: controller, t: translate })] }));
90
+ }), children: [_jsxs("summary", { className: "deployment-step-summary", children: [_jsx("span", { className: "deployment-step-marker deployment-step-marker-done", "aria-hidden": "true", children: _jsx(StepDoneIcon, { lineIcon: LINE_ICON, Icon: Icon }) }), _jsx(SavedCredentialSummary, { kit: kit, deps: deps, row: row, saved: saved, t: translate }), _jsx(CredentialVerifyAction, { row: row, controller: controller, t: translate }), _jsxs("span", { className: "deployment-step-summary-action", children: [translate("Replace token"), _jsx(DisclosureChevron, { lineIcon: LINE_ICON, Icon: Icon })] })] }), _jsx(CredentialTokenPicker, { deps: deps, row: row, saved: saved, controller: controller, t: translate }), _jsx(PublishCredentialFields, { kit: kit, deps: deps, row: row, controller: controller, t: translate })] }));
91
91
  }
92
92
  /**
93
93
  * The "Verify" control on an already-connected row — re-checks the saved token against its real
@@ -128,16 +128,13 @@ function CredentialVerifyAction({ row, controller, t: translate, }, _optional =
128
128
  * @complexity O(n) in this provider's own (small) saved-credential count, same bound
129
129
  * {@link credentialsForProvider} documents.
130
130
  */
131
- function CredentialTokenPicker({ row, controller, t: translate, deps }, _optional = {}) {
131
+ function CredentialTokenPicker({ row, saved, controller, t: translate, deps }, _optional = {}) {
132
132
  const { copy, VIEWER_TIME_ZONE } = deps;
133
- // Rendered only inside the connected row (`row.saved` set — that row checks it too), so
133
+ // The connected row checks and passes its saved credential, so
134
134
  // the selected value falls back to the saved default's id with no further "nothing saved" arm.
135
135
  const options = controller.credentialsForProvider(row.providerId);
136
136
  if (options.length < 2)
137
137
  return null;
138
- const saved = row.saved;
139
- if (!saved)
140
- throw new Error(`publish credential picker ${row.providerId} has no saved credential`);
141
138
  const fieldId = `deployment-static-site-credentials-picker-${row.providerId}`;
142
139
  return (_jsxs("div", { className: "field", children: [_jsx("label", { className: "field-label", htmlFor: fieldId, children: translate("Which saved token publishes") }), _jsx("select", { id: fieldId, value: row.selectingCredentialId ?? saved.id, disabled: row.selectingCredentialId !== null, onChange: (e) => void controller.selectCredential({ providerId: row.providerId, credentialId: e.target.value }), ...agentHandle({ handle: fieldId }, {
143
140
  role: "field",
@@ -113,9 +113,7 @@ function buildRegistry({ loaded, refusals }, _optional = {}) {
113
113
  const allRefusals = [...refusals];
114
114
  for (const [id, claimants] of byId) {
115
115
  if (claimants.length === 1) {
116
- const claimant = claimants[0];
117
- if (claimant === undefined)
118
- throw new Error(`Deploy target ${id} has no claimant`);
116
+ const [claimant] = claimants;
119
117
  unique.set(id, claimant);
120
118
  }
121
119
  else {
@@ -289,20 +289,12 @@ export declare function deletePublishCredential(deps: {
289
289
  id: UUID;
290
290
  }): Promise<void>;
291
291
  /**
292
- * Persists a freshly-verified account label onto an existing row — see this file's own header for
293
- * why {@link createPublishCredential}/{@link updatePublishCredential} never do this themselves. The
294
- * ONE intended caller is the admin credential-CRUD route (`server/routes/admin/system/publish-
295
- * credentials.ts`), immediately after its own `verifyPublishCredentialById` call returns a `"valid"`
296
- * result carrying an `accountLabel`. Never call this with an EMPTY/absent label to "clear" one: a
297
- * failed or inconclusive re-verify carries no `accountLabel` at all and must leave a previously-healed
298
- * value alone — the caller's own `result.accountLabel !== undefined` check enforces that.
299
- *
300
- * A targeted single-column write ({@link VendorCredentialSetRepoPort.updateAccountLabel}), not a
301
- * full-row replace — never touches `sealed`, `isDefault`, or `updatedAt`.
302
- *
303
- * Written where the row lives: this site's vault, else the project's.
304
- *
305
- * @complexity O(1) — one lookup and one repo write (a no-op, not an error, if the row vanished meanwhile).
292
+ * Persist the public account only against the exact basis opened before the provider probe.
293
+ * The verifier owns this step so its cache can use the resulting revision. Older hosts may still
294
+ * call without a basis after verification; those calls safely do nothing because reading a fresh
295
+ * basis here would silently attach an old probe's account to a replacement credential.
296
+ * Written in the owning site/project store, with no envelope/default/timestamp changes.
297
+ * @returns The committed basis, or null when no conditional heal was possible.
306
298
  */
307
299
  export declare function healAccountLabel(deps: {
308
300
  repo: VendorCredentialSetRepoPort;
@@ -310,7 +302,14 @@ export declare function healAccountLabel(deps: {
310
302
  workspaceId: UUID;
311
303
  id: UUID;
312
304
  accountLabel: string;
313
- }): Promise<void>;
305
+ expectedBasis?: {
306
+ id: UUID;
307
+ revision: number;
308
+ };
309
+ }): Promise<{
310
+ id: UUID;
311
+ revision: number;
312
+ } | null>;
314
313
  /** Jini checks exact ownership before opening. Keep the typed error used by HTTP and daemon
315
314
  * boundaries: a missing key must not become an unhandled rejection in a publishing process. */
316
315
  export declare function decryptRecord({ deps, record, providerId }: {
@@ -336,24 +336,19 @@ export async function deletePublishCredential(deps, input) {
336
336
  await owner.repo.delete({ workspaceId: owner.workspaceId, id: input.id });
337
337
  }
338
338
  /**
339
- * Persists a freshly-verified account label onto an existing row — see this file's own header for
340
- * why {@link createPublishCredential}/{@link updatePublishCredential} never do this themselves. The
341
- * ONE intended caller is the admin credential-CRUD route (`server/routes/admin/system/publish-
342
- * credentials.ts`), immediately after its own `verifyPublishCredentialById` call returns a `"valid"`
343
- * result carrying an `accountLabel`. Never call this with an EMPTY/absent label to "clear" one: a
344
- * failed or inconclusive re-verify carries no `accountLabel` at all and must leave a previously-healed
345
- * value alone — the caller's own `result.accountLabel !== undefined` check enforces that.
346
- *
347
- * A targeted single-column write ({@link VendorCredentialSetRepoPort.updateAccountLabel}), not a
348
- * full-row replace — never touches `sealed`, `isDefault`, or `updatedAt`.
349
- *
350
- * Written where the row lives: this site's vault, else the project's.
351
- *
352
- * @complexity O(1) — one lookup and one repo write (a no-op, not an error, if the row vanished meanwhile).
339
+ * Persist the public account only against the exact basis opened before the provider probe.
340
+ * The verifier owns this step so its cache can use the resulting revision. Older hosts may still
341
+ * call without a basis after verification; those calls safely do nothing because reading a fresh
342
+ * basis here would silently attach an old probe's account to a replacement credential.
343
+ * Written in the owning site/project store, with no envelope/default/timestamp changes.
344
+ * @returns The committed basis, or null when no conditional heal was possible.
353
345
  */
354
346
  export async function healAccountLabel(deps, input) {
347
+ if (!input.expectedBasis || input.expectedBasis.id !== input.id)
348
+ return null;
355
349
  const owner = await ownerOf(deps.repo, input);
356
- await owner.repo.updateAccountLabel({ ...input, workspaceId: owner.workspaceId });
350
+ return owner.repo.updateAccountLabelIfRevision({ workspaceId: owner.workspaceId, id: input.id,
351
+ accountLabel: input.accountLabel, expectedRevision: input.expectedBasis.revision });
357
352
  }
358
353
  /** Jini checks exact ownership before opening. Keep the typed error used by HTTP and daemon
359
354
  * boundaries: a missing key must not become an unhandled rejection in a publishing process. */
@@ -41,8 +41,10 @@ export function credentialChoice({ value }, _options = {}) {
41
41
  export async function httpPublishPreview(required, _options = {}) {
42
42
  const { deps, credentialSource, registry, config, query } = required;
43
43
  const plan = deps.planStaticPublish({ registry, config });
44
- // A chosen connection wins over the default one for readiness too (decision J-O25).
45
- const choice = credentialChoice({ value: query.credentialId });
44
+ // J-O25: an invalid plan wins over a blank selection; use default readiness in that case.
45
+ // A valid chosen connection still wins over the default one for readiness too.
46
+ const choice = !plan.ok && typeof query.credentialId === "string" && !query.credentialId.trim()
47
+ ? {} : credentialChoice({ value: query.credentialId });
46
48
  const credential = await credentialSource.isConfigured({ workspaceId: deps.workspaceId, target: config.target, ...choice });
47
49
  const inspected = plan.ok && credential.configured ? await deps.inspectStaticPublish({
48
50
  input: { workspaceId: deps.workspaceId, config, projectName: typeof query.projectName === "string" ? query.projectName : "", ...choice },
@@ -1,3 +1,4 @@
1
+ import { type DigestCryptoPort } from "@jini-ai/core/records";
1
2
  import type { UUID } from "@jini-ai/core/primitives";
2
3
  import type { SecretSealerPort } from "@jini-ai/core/contracts/vault";
3
4
  import type { describeCredential, PublishCredentialReadDeps } from '../publish-credentials/store.js';
@@ -33,8 +34,9 @@ export declare function redactDeployTargetMessage({ message, credential, target
33
34
  * process env vars (which would leak across parallel test files in the same process).
34
35
  * @complexity One registry load per call, then O(v) env reads for the target's declared vars.
35
36
  */
36
- export declare function createEnvPublishCredentialSource({ workspaceId, loadDeployTargets, env }: {
37
+ export declare function createEnvPublishCredentialSource({ workspaceId, loadDeployTargets, env, crypto }: {
37
38
  env: NodeJS.ProcessEnv;
39
+ crypto?: DigestCryptoPort;
38
40
  workspaceId: UUID;
39
41
  loadDeployTargets: ({ workspaceId }: {
40
42
  workspaceId: string;
@@ -91,6 +93,8 @@ export interface ComposePublishCredentialSourceInput {
91
93
  * `createEnvPublishCredentialSource`'s own `env` parameter documents. Only read when
92
94
  * `executionMode` is `"self-hosted-cli"` — see this function's own doc for why. */
93
95
  env: NodeJS.ProcessEnv;
96
+ /** Optional WebCrypto hook for environments without a global implementation. */
97
+ crypto?: DigestCryptoPort;
94
98
  }
95
99
  /**
96
100
  * The ONE place this feature decides which `PublishCredentialSource`(s) a real publish attempt may
@@ -1,4 +1,5 @@
1
1
  import { redactSecrets } from "@jini-ai/core";
2
+ import { canonicalArgumentDigest } from "@jini-ai/core/records";
2
3
  /** Keep provider explanations useful without exposing any declared credential secret.
3
4
  * Uses Jini's redactor for both publish and preview responses; does not mutate the credential.
4
5
  * @complexity O(fields + message bytes × secrets), delegated to the shared redactor. */
@@ -79,6 +80,12 @@ function chosenCredentialWrongProviderReason(providerId, target) {
79
80
  function chosenConnectionUnavailableFromEnvReason(target) {
80
81
  return `a saved connection was chosen for this publish, but this install resolves '${target}' credentials from server environment variables, which have no saved connections to choose from`;
81
82
  }
83
+ /** Hash the actual trimmed credential, including secondary fields, so rotation cannot reuse a
84
+ * previous account's verification. Canonical ordering also works across source instances. */
85
+ async function environmentBasis({ token, fields, crypto }, _optional = {}) {
86
+ const entries = Object.keys(fields).sort().map(name => [name, fields[name]]);
87
+ return { kind: "env", fingerprint: await canonicalArgumentDigest({ args: [token, entries], crypto }) };
88
+ }
82
89
  /** The first set, non-blank var of `tokenVars` (blank counts as unset). The failure reason names
83
90
  * every var the operator could have set, not just the first. */
84
91
  function readToken(env, target, tokenVars) {
@@ -116,7 +123,7 @@ function readFields(env, target, fallback) {
116
123
  * process env vars (which would leak across parallel test files in the same process).
117
124
  * @complexity One registry load per call, then O(v) env reads for the target's declared vars.
118
125
  */
119
- export function createEnvPublishCredentialSource({ workspaceId, loadDeployTargets, env }, _optional = {}) {
126
+ export function createEnvPublishCredentialSource({ workspaceId, loadDeployTargets, env, crypto = globalThis.crypto }, _optional = {}) {
120
127
  async function readCredential({ target, requestedWorkspaceId }, { credentialId } = {}) {
121
128
  // An env var is never "the saved connection the operator chose" — a chosen id must resolve to
122
129
  // THAT row or refuse (see `PublishCredentialSource.resolve`'s `credentialId` doc).
@@ -144,11 +151,11 @@ export function createEnvPublishCredentialSource({ workspaceId, loadDeployTarget
144
151
  return {
145
152
  async resolve(input) {
146
153
  const result = await readCredential({ target: input.target, requestedWorkspaceId: input.workspaceId }, input.credentialId === undefined ? {} : { credentialId: input.credentialId });
147
- return "token" in result ? { ok: true, token: result.token, ...result.fields, basis: { kind: "env" } } : { ok: false, reason: result.reason };
154
+ return "token" in result ? { ok: true, token: result.token, ...result.fields, basis: await environmentBasis({ ...result, crypto }) } : { ok: false, reason: result.reason };
148
155
  },
149
156
  async isConfigured(input, _options = {}) {
150
157
  const result = await readCredential({ target: input.target, requestedWorkspaceId: input.workspaceId }, input.credentialId === undefined ? {} : { credentialId: input.credentialId });
151
- return "token" in result ? { configured: true, basis: { kind: "env" } } : { configured: false, reason: result.reason };
158
+ return "token" in result ? { configured: true, basis: await environmentBasis({ ...result, crypto }) } : { configured: false, reason: result.reason };
152
159
  },
153
160
  };
154
161
  }
@@ -262,7 +269,8 @@ export function composePublishCredentialSource(input) {
262
269
  if (input.executionMode === "hosted-api-only") {
263
270
  return dbSource;
264
271
  }
265
- const envSource = createEnvPublishCredentialSource({ workspaceId: input.workspaceId, loadDeployTargets: input.dbDeps.loadDeployTargets, env: input.env });
272
+ const envSource = createEnvPublishCredentialSource({ workspaceId: input.workspaceId, loadDeployTargets: input.dbDeps.loadDeployTargets, env: input.env,
273
+ ...(input.crypto === undefined ? {} : { crypto: input.crypto }) });
266
274
  return {
267
275
  async resolve(req) {
268
276
  const fromDb = await dbSource.resolve(req);
@@ -114,6 +114,9 @@ export type PublishVerificationBasis = {
114
114
  readonly revision: number;
115
115
  } | {
116
116
  readonly kind: "env";
117
+ /** Digest of the effective credential, kept internal to readiness bookkeeping. Optional for
118
+ * historical injected sources; an unbound basis never matches a fingerprinted one. */
119
+ readonly fingerprint?: string;
117
120
  };
118
121
  /** {@link PublishCredentialSource.resolve}'s success: `token` plus the host's other declared credential
119
122
  * fields. `true` is in the index type only so `ok` itself fits it; every field is a string. */
@@ -61,6 +61,16 @@ export interface PublishCredentialVerificationCache {
61
61
  workspaceId: UUID;
62
62
  target: StaticPublishTargetId;
63
63
  }): void;
64
+ /** Capture before resolving/opening a credential; invalidation during any await fences the write. */
65
+ checkpoint(required: Record<string, never>): number;
66
+ /** Commit only if this target has not been invalidated or replaced since the checkpoint. */
67
+ setIfCurrent(input: {
68
+ workspaceId: UUID;
69
+ target: StaticPublishTargetId;
70
+ basis: PublishVerificationBasis;
71
+ checkpoint: number;
72
+ result: PublishCredentialVerificationResult;
73
+ }): void;
64
74
  }
65
75
  /**
66
76
  * The real, in-process implementation — a plain `Map`, no TTL/expiry (see this feature's design doc
@@ -73,6 +83,8 @@ export interface PublishCredentialVerificationCache {
73
83
  */
74
84
  export declare class InMemoryPublishCredentialVerificationCache implements PublishCredentialVerificationCache {
75
85
  private readonly entries;
86
+ private readonly changedAt;
87
+ private version;
76
88
  private static key;
77
89
  get(input: {
78
90
  workspaceId: UUID;
@@ -88,6 +100,14 @@ export declare class InMemoryPublishCredentialVerificationCache implements Publi
88
100
  workspaceId: UUID;
89
101
  target: StaticPublishTargetId;
90
102
  }): void;
103
+ checkpoint(_required: Record<string, never>, _optional?: {}): number;
104
+ setIfCurrent(input: {
105
+ workspaceId: UUID;
106
+ target: StaticPublishTargetId;
107
+ basis: PublishVerificationBasis;
108
+ checkpoint: number;
109
+ result: PublishCredentialVerificationResult;
110
+ }, _optional?: {}): void;
91
111
  }
92
112
  export interface VerifyPublishCredentialDeps {
93
113
  readonly assertCredentialToken: (required: {
@@ -1,4 +1,5 @@
1
1
  import { DEPLOY_FETCH_TIMEOUTS } from "@jini-ai/devops/deploy/site/deploy-targets/host-kit";
2
+ import { healAccountLabel } from "../publish-credentials/store.js";
2
3
  import { projectConnectionForPublish, toDeployTargetCredential } from "./credentials.js";
3
4
  /**
4
5
  * @file Verifies a static-publish credential against its REAL host — the fix for "ready means a
@@ -81,6 +82,8 @@ function buildVerificationMessage({ label, check, credentialText }, _options = {
81
82
  */
82
83
  export class InMemoryPublishCredentialVerificationCache {
83
84
  entries = new Map();
85
+ changedAt = new Map();
86
+ version = 0;
84
87
  static key(input) {
85
88
  return `${input.workspaceId}::${input.target}`;
86
89
  }
@@ -89,15 +92,28 @@ export class InMemoryPublishCredentialVerificationCache {
89
92
  if (!entry)
90
93
  return undefined;
91
94
  const matches = "kind" in input.basis
92
- ? "kind" in entry.basis
95
+ ? "kind" in entry.basis && entry.basis.fingerprint === input.basis.fingerprint
93
96
  : !("kind" in entry.basis) && entry.basis.id === input.basis.id && entry.basis.revision === input.basis.revision;
94
97
  return matches ? entry.result : undefined;
95
98
  }
96
99
  set(input, result) {
97
- this.entries.set(InMemoryPublishCredentialVerificationCache.key(input), { basis: input.basis, result });
100
+ const key = InMemoryPublishCredentialVerificationCache.key(input);
101
+ this.changedAt.set(key, ++this.version);
102
+ this.entries.set(key, { basis: { ...input.basis }, result });
98
103
  }
99
104
  delete(input) {
100
- this.entries.delete(InMemoryPublishCredentialVerificationCache.key(input));
105
+ const key = InMemoryPublishCredentialVerificationCache.key(input);
106
+ // Keep a tombstone even for an empty slot: an in-flight first check can still be invalidated.
107
+ this.changedAt.set(key, ++this.version);
108
+ this.entries.delete(key);
109
+ }
110
+ checkpoint(_required, _optional = {}) {
111
+ return this.version;
112
+ }
113
+ setIfCurrent(input, _optional = {}) {
114
+ const changed = this.changedAt.get(InMemoryPublishCredentialVerificationCache.key(input)) ?? 0;
115
+ if (changed <= input.checkpoint)
116
+ this.set(input, input.result);
101
117
  }
102
118
  }
103
119
  /** The kit a check runs with: `fetchFn` (tests), the observability port, and a `QUICK` timeout sized for a waiting human. */
@@ -185,6 +201,7 @@ function checkedVerificationResult({ context, loaded, check }) {
185
201
  * decrypt), one registry load, plus one bounded outbound HTTP request.
186
202
  */
187
203
  export async function verifyPublishCredential(deps, input) {
204
+ const checkpoint = deps.cache.checkpoint({});
188
205
  const resolved = await deps.credentialSource.resolve(input);
189
206
  if (!resolved.ok) {
190
207
  deps.cache.delete(input);
@@ -192,7 +209,7 @@ export async function verifyPublishCredential(deps, input) {
192
209
  }
193
210
  const context = { assertCredentialToken: deps.assertCredentialToken, CredentialInputError: deps.CredentialInputError, credentialText: deps.credentialText, registry: await deps.loadDeployTargets({ workspaceId: input.workspaceId }), kit: verificationKit(deps), clock: deps.clock };
194
211
  const result = await computeVerificationResult({ context, target: input.target, credential: toDeployTargetCredential(resolved) });
195
- deps.cache.set({ ...input, basis: resolved.basis }, result);
212
+ deps.cache.setIfCurrent({ ...input, basis: resolved.basis, checkpoint, result });
196
213
  return result;
197
214
  }
198
215
  /**
@@ -219,6 +236,7 @@ export async function verifyPublishCredential(deps, input) {
219
236
  * outbound HTTP request.
220
237
  */
221
238
  export async function verifyPublishCredentialById(deps, input) {
239
+ const checkpoint = deps.cache.checkpoint({});
222
240
  const resolved = await deps.resolveForPublish(deps, input);
223
241
  if (!resolved)
224
242
  return null;
@@ -228,11 +246,29 @@ export async function verifyPublishCredentialById(deps, input) {
228
246
  const result = projected?.ok
229
247
  ? await computeVerificationResult({ context, target: resolved.providerId, credential: toDeployTargetCredential(projected) })
230
248
  : cannotVerify({ reason: projected?.reason ?? noCheckReason(resolved.providerId), clock: deps.clock });
249
+ const basis = await verifiedAccountBasis({ deps, input, resolved, result });
231
250
  if (resolved.isDefault) {
232
- deps.cache.set({ workspaceId: input.workspaceId, target: resolved.providerId, basis: { id: input.id, revision: resolved.revision } }, result);
251
+ deps.cache.setIfCurrent({ workspaceId: input.workspaceId, target: resolved.providerId, basis, checkpoint, result });
233
252
  }
234
253
  return result;
235
254
  }
255
+ /** Healing belongs inside verification: only this function still knows which revision was probed. */
256
+ async function verifiedAccountBasis({ deps, input, resolved, result }, _optional = {}) {
257
+ const basis = { id: input.id, revision: resolved.revision };
258
+ if (result.status !== "valid" || result.accountLabel === undefined)
259
+ return basis;
260
+ try {
261
+ const healed = await healAccountLabel({ repo: deps.repo }, { ...input, accountLabel: result.accountLabel, expectedBasis: basis });
262
+ // Legacy custom rows cannot store account labels; their original basis remains usable.
263
+ // A stale basis also remains safe: it cannot match a replacement row's revision.
264
+ return healed ?? basis;
265
+ }
266
+ catch {
267
+ // A metadata failure must not turn an accepted key or a committed save into a failed response.
268
+ // Retain only the original basis; never re-read and bless a potentially replaced credential.
269
+ return basis;
270
+ }
271
+ }
236
272
  /** Check a human-submitted replacement through the existing host verifier before overwriting.
237
273
  * @returns The normal safe verification result; does not write credentials or cache results.
238
274
  * @complexity One registry load and one bounded host check.
@@ -41,8 +41,6 @@ function assertManifest({ value, label }) {
41
41
  * @complexity O(n) in files.
42
42
  */
43
43
  function mergeMacManifests({ inputs }, _options = {}) {
44
- if (inputs.length === 0)
45
- throw new Error("no manifests to merge");
46
44
  const manifests = inputs.map(({ label, manifest }) => assertManifest({ value: manifest, label }));
47
45
  const [first] = manifests;
48
46
  if (first === undefined)
@@ -0,0 +1,30 @@
1
+ import type { FailedAsset } from './contracts.js';
2
+ export interface AssetQueueItem {
3
+ url: string;
4
+ depth: number;
5
+ crawlCss: boolean;
6
+ }
7
+ export interface AssetCrawl {
8
+ queue: AssetQueueItem[];
9
+ queued: Set<string>;
10
+ failed: FailedAsset[];
11
+ countRefused: boolean;
12
+ depthRefused: boolean;
13
+ jsonBytes: number;
14
+ }
15
+ export declare function createAssetCrawl(_required: Record<string, never>, _optional?: {}): AssetCrawl;
16
+ /** Bound queue memory as well as requests. Report a limit once instead of silently making an
17
+ * incomplete artifact look successful, or retaining an unbounded list of refused references. */
18
+ export declare function enqueueAssets({ state, urls, depth, crawlCss }: {
19
+ state: AssetCrawl;
20
+ urls: readonly string[];
21
+ depth: number;
22
+ crawlCss: boolean;
23
+ }, _optional?: {}): void;
24
+ /** Bound JSON before allocating/parsing it. Other asset types retain their existing byte policy,
25
+ * so introducing recursive manifests does not impose a new size limit on public videos. */
26
+ export declare function readAssetData({ response, state }: {
27
+ response: Response;
28
+ state: AssetCrawl;
29
+ }, _optional?: {}): Promise<Buffer>;
30
+ //# sourceMappingURL=asset-crawl.d.ts.map
@@ -0,0 +1,71 @@
1
+ const MAX_ASSETS = 2000;
2
+ const MAX_DEPENDENCY_DEPTH = 8;
3
+ const MAX_JSON_BYTES = 1024 * 1024;
4
+ const MAX_TOTAL_JSON_BYTES = 8 * MAX_JSON_BYTES;
5
+ const TOTAL_JSON_LIMIT_REASON = `JSON asset discovery exceeds the ${MAX_TOTAL_JSON_BYTES} byte total limit.`;
6
+ export function createAssetCrawl(_required, _optional = {}) {
7
+ return { queue: [], queued: new Set(), failed: [], countRefused: false, depthRefused: false, jsonBytes: 0 };
8
+ }
9
+ /** Bound queue memory as well as requests. Report a limit once instead of silently making an
10
+ * incomplete artifact look successful, or retaining an unbounded list of refused references. */
11
+ export function enqueueAssets({ state, urls, depth, crawlCss }, _optional = {}) {
12
+ for (const url of urls) {
13
+ if (state.queued.has(url))
14
+ continue;
15
+ if (depth > MAX_DEPENDENCY_DEPTH) {
16
+ if (!state.depthRefused)
17
+ state.failed.push({ url, reason: `Asset discovery stopped after ${MAX_DEPENDENCY_DEPTH} dependency levels.` });
18
+ state.depthRefused = true;
19
+ return;
20
+ }
21
+ if (state.queue.length >= MAX_ASSETS) {
22
+ if (!state.countRefused)
23
+ state.failed.push({ url, reason: `Asset discovery stopped after ${MAX_ASSETS} assets.` });
24
+ state.countRefused = true;
25
+ return;
26
+ }
27
+ state.queued.add(url);
28
+ state.queue.push({ url, depth, crawlCss });
29
+ }
30
+ }
31
+ /** Charge actual streamed bytes, including failed attempts; Content-Length is untrusted. */
32
+ function chargeJsonBytes({ state, bytes, chunkBytes }, _optional = {}) {
33
+ state.jsonBytes += chunkBytes;
34
+ if (bytes > MAX_JSON_BYTES)
35
+ throw new Error(`JSON asset exceeds the ${MAX_JSON_BYTES} byte limit.`);
36
+ if (state.jsonBytes > MAX_TOTAL_JSON_BYTES)
37
+ throw new Error(TOTAL_JSON_LIMIT_REASON);
38
+ }
39
+ /** Bound JSON before allocating/parsing it. Other asset types retain their existing byte policy,
40
+ * so introducing recursive manifests does not impose a new size limit on public videos. */
41
+ export async function readAssetData({ response, state }, _optional = {}) {
42
+ if (!/\bjson\b/i.test(response.headers.get('content-type') ?? ''))
43
+ return Buffer.from(await response.arrayBuffer());
44
+ const reader = response.body?.getReader();
45
+ if (!reader)
46
+ return Buffer.alloc(0);
47
+ const chunks = [];
48
+ let bytes = 0;
49
+ try {
50
+ if (state.jsonBytes >= MAX_TOTAL_JSON_BYTES)
51
+ throw new Error(TOTAL_JSON_LIMIT_REASON);
52
+ for (;;) {
53
+ const chunk = await reader.read();
54
+ if (chunk.done)
55
+ break;
56
+ bytes += chunk.value.byteLength;
57
+ chargeJsonBytes({ state, bytes, chunkBytes: chunk.value.byteLength });
58
+ chunks.push(chunk.value);
59
+ }
60
+ return Buffer.concat(chunks, bytes);
61
+ }
62
+ catch (error) {
63
+ // A cancellation failure must not replace the useful bounded-read refusal.
64
+ await reader.cancel().catch(() => { });
65
+ throw error;
66
+ }
67
+ finally {
68
+ reader.releaseLock();
69
+ }
70
+ }
71
+ //# sourceMappingURL=asset-crawl.js.map
@@ -0,0 +1,23 @@
1
+ import type { HtmlUrlLocation } from './html-url-locations.js';
2
+ /** Per HTML document. A UTF-16 code unit needs at most three UTF-8 bytes, so this
3
+ * character budget also keeps scanned inline source below one MiB of UTF-8. */
4
+ export interface DynamicAssetBudget {
5
+ characters: number;
6
+ references: number;
7
+ }
8
+ export declare function dynamicAssetBudget(_required: Record<string, never>, _optional?: {}): DynamicAssetBudget;
9
+ /** Whole root-relative paths only: markup, JSON blobs and executable expressions are not URLs.
10
+ * Prefix admission and path containment are still enforced by the existing crawl/write boundary. */
11
+ export declare function takeDynamicUrl({ value, budget }: {
12
+ value: string;
13
+ budget: DynamicAssetBudget;
14
+ }, _optional?: {}): boolean;
15
+ /** Tokenize comments and whole quoted strings, never execute JavaScript. Consuming whole
16
+ * strings keeps HTML examples inside a JS string from becoming references. Templates are
17
+ * deliberately opaque: interpolation may produce a completely different runtime URL. */
18
+ export declare function scriptAssetLocations({ script, start, budget }: {
19
+ script: string;
20
+ start: number;
21
+ budget: DynamicAssetBudget;
22
+ }, _optional?: {}): HtmlUrlLocation[];
23
+ //# sourceMappingURL=dynamic-asset-locations.d.ts.map
@@ -0,0 +1,34 @@
1
+ export function dynamicAssetBudget(_required, _optional = {}) {
2
+ return { characters: 262144, references: 256 };
3
+ }
4
+ /** Whole root-relative paths only: markup, JSON blobs and executable expressions are not URLs.
5
+ * Prefix admission and path containment are still enforced by the existing crawl/write boundary. */
6
+ export function takeDynamicUrl({ value, budget }, _optional = {}) {
7
+ if (budget.references === 0 || value.length > 2048)
8
+ return false;
9
+ if (!/^\/(?!\/)[^\s\\'"<>`\x00-\x1f\x7f]*$/.test(value))
10
+ return false;
11
+ budget.references--;
12
+ return true;
13
+ }
14
+ /** Tokenize comments and whole quoted strings, never execute JavaScript. Consuming whole
15
+ * strings keeps HTML examples inside a JS string from becoming references. Templates are
16
+ * deliberately opaque: interpolation may produce a completely different runtime URL. */
17
+ export function scriptAssetLocations({ script, start, budget }, _optional = {}) {
18
+ const source = script.slice(0, budget.characters);
19
+ budget.characters -= source.length;
20
+ const tokens = /\/\/[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|`(?:\\[\s\S]|[^`\\])*`|"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'/g;
21
+ const locations = [];
22
+ for (const token of source.matchAll(tokens)) {
23
+ if (budget.references === 0)
24
+ break;
25
+ const text = token[0];
26
+ if (text[0] !== '"' && text[0] !== "'")
27
+ continue;
28
+ if (!takeDynamicUrl({ value: text.slice(1, -1), budget }))
29
+ continue;
30
+ locations.push({ start: start + token.index + 1, end: start + token.index + text.length - 1, kind: 'url' });
31
+ }
32
+ return locations;
33
+ }
34
+ //# sourceMappingURL=dynamic-asset-locations.js.map
@@ -9,7 +9,9 @@ export interface HtmlUrlLocation {
9
9
  * @complexity O(n + a log a) in HTML bytes and source attributes; iterative traversal avoids recursion limits. */
10
10
  export declare function htmlUrlLocations({ html }: {
11
11
  html: string;
12
- }, _optional?: {}): HtmlUrlLocation[];
12
+ }, optional?: {
13
+ scriptAssets?: boolean;
14
+ }): HtmlUrlLocation[];
13
15
  /** CSS, Markdown indexes, sitemap and manifest positions use their response format, never an HTML text scan. */
14
16
  export declare function exportUrlLocations({ body, contentType }: {
15
17
  body: string;
@@ -1,5 +1,6 @@
1
1
  import { parse } from 'parse5';
2
2
  import { cssUrlTokens } from './css-urls.js';
3
+ import { dynamicAssetBudget, scriptAssetLocations, takeDynamicUrl } from './dynamic-asset-locations.js';
3
4
  const URL_ATTRIBUTES = new Set(['src', 'href', 'poster']);
4
5
  /** The exact attribute value range, preserving quotes, spacing and all surrounding source bytes. */
5
6
  function attributeLocation({ html, start, end, kind }, _optional = {}) {
@@ -39,8 +40,10 @@ function normalizedUrlAttribute(name) {
39
40
  function styleLocations({ element }, _optional = {}) {
40
41
  if (element.tagName !== 'style')
41
42
  return [];
42
- return element.childNodes.flatMap(child => child.sourceCodeLocation
43
- ? [{ start: child.sourceCodeLocation.startOffset, end: child.sourceCodeLocation.endOffset, kind: 'css' }] : []);
43
+ // parse5 emits style's raw text children with locations when sourceCodeLocationInfo is on.
44
+ return element.childNodes.map(child => ({
45
+ start: child.sourceCodeLocation.startOffset, end: child.sourceCodeLocation.endOffset, kind: 'css',
46
+ }));
44
47
  }
45
48
  /** Canonical identity and feed discovery must remain absolute when a download relocates files. */
46
49
  function isIdentityLink({ element }, _optional = {}) {
@@ -50,11 +53,25 @@ function isIdentityLink({ element }, _optional = {}) {
50
53
  const type = element.attrs.find(attr => attr.name === 'type')?.value.toLowerCase();
51
54
  return rel.includes('canonical') || (rel.includes('alternate') && (type === 'application/rss+xml' || type === 'application/atom+xml'));
52
55
  }
53
- /** Collect one element's real URL/style positions, excluding lookalike strings in text and scripts. */
54
- function elementLocations({ element, html }, _optional = {}) {
56
+ /** Only inline JavaScript and JSON scripts supply literal assets, never external-script fallback text. */
57
+ function inlineLocations({ element, html, budget }, _optional = {}) {
58
+ if (element.tagName !== 'script' || element.attrs.some(attr => attr.name === 'src'))
59
+ return [];
60
+ const type = element.attrs.find(attr => attr.name === 'type')?.value.trim().toLowerCase() ?? '';
61
+ if (!/^(?:|module|(?:text|application)\/(?:javascript|ecmascript)|application\/(?:ld\+)?json)$/.test(type))
62
+ return [];
63
+ const source = element.sourceCodeLocation;
64
+ if (!source?.startTag)
65
+ return [];
66
+ const start = source.startTag.endOffset;
67
+ return scriptAssetLocations({ script: html.slice(start, source.endTag?.startOffset ?? source.endOffset), start, budget });
68
+ }
69
+ /** Collect real URL/style positions and bounded whole-URL data attributes. Inline literals
70
+ * are discovery-only so relocating output never changes authored JavaScript semantics. */
71
+ function elementLocations({ element, html, budget }, _optional = {}) {
55
72
  const locations = [];
56
73
  for (const attr of element.attrs) {
57
- const kind = attributeKind({ element, name: attr.name });
74
+ const kind = assetAttributeKind({ element, attr, budget });
58
75
  const source = element.sourceCodeLocation?.attrs?.[attr.name];
59
76
  if (!kind || !source)
60
77
  continue;
@@ -65,21 +82,38 @@ function elementLocations({ element, html }, _optional = {}) {
65
82
  locations.push(...styleLocations({ element }));
66
83
  return locations;
67
84
  }
85
+ function assetAttributeKind({ element, attr, budget }, _optional = {}) {
86
+ const kind = attributeKind({ element, name: attr.name });
87
+ if (kind)
88
+ return kind;
89
+ if (!attr.name.startsWith('data-'))
90
+ return undefined;
91
+ return takeDynamicUrl({ value: attr.value, budget }) ? 'url' : undefined;
92
+ }
68
93
  /** Source ranges from the workspace's HTML parser; no serialization can alter article content.
69
94
  * @complexity O(n + a log a) in HTML bytes and source attributes; iterative traversal avoids recursion limits. */
70
- export function htmlUrlLocations({ html }, _optional = {}) {
95
+ export function htmlUrlLocations({ html }, optional = {}) {
71
96
  const pending = [parse(html, { sourceCodeLocationInfo: true })];
72
97
  const locations = [];
98
+ const budget = dynamicAssetBudget({});
99
+ const scripts = [];
73
100
  while (pending.length) {
74
101
  const node = pending.pop();
75
102
  if ('childNodes' in node)
76
- for (const child of node.childNodes)
103
+ for (const child of [...node.childNodes].reverse())
77
104
  pending.push(child);
78
- if ('tagName' in node)
79
- locations.push(...elementLocations({ element: node, html }));
105
+ if ('tagName' in node) {
106
+ locations.push(...elementLocations({ element: node, html, budget }));
107
+ if (node.tagName === 'script')
108
+ scripts.push(node);
109
+ }
80
110
  if ('content' in node)
81
111
  pending.push(node.content);
82
112
  }
113
+ // Attributes have priority so crawl admission matches base-path rewriting, which never scans JS.
114
+ if (optional.scriptAssets)
115
+ for (const element of scripts)
116
+ locations.push(...inlineLocations({ element, html, budget }));
83
117
  return locations.sort((a, b) => a.start - b.start);
84
118
  }
85
119
  /** Generated llms indexes use one Markdown list link per line; prose stays untouched.
@@ -1,6 +1,7 @@
1
1
  import { ExportPathError } from "./contracts.js";
2
2
  import { extractAssetUrls, extractHtmlReferences, extractCssUrls, normalizeBasePath, outputFileForUrl, redirectOutcomeFor, renderRedirectStub, rewriteRouteBodyForBasePath, rewriteAssetBodyForBasePath, safeRelativeOutputFile } from './transforms.js';
3
3
  import { trimCharsEnd } from '@jini-ai/core/primitives';
4
+ import { createAssetCrawl, enqueueAssets, readAssetData } from './asset-crawl.js';
4
5
  const BASE_PATH_REWRITE_WARNING = "base-path rewriting is a best-effort TEXT rewrite over already-rendered responses — it cannot rewrite a path a theme's own JavaScript constructs at runtime from a string (same category of gap as the unreferenced-theme-file warning, just invisible to this rewrite instead of to the asset crawl).";
5
6
  async function request(ctx, url) {
6
7
  // Redirects are observed, never followed off the caller's app, for routes and assets alike.
@@ -111,32 +112,32 @@ async function writeAndScanRoute({ ctx, route, state }, out) {
111
112
  out.assets.add(url);
112
113
  enqueueDiscovered({ state, routes: ctx.args.discoverRoutes?.({ path: route.path, html }) ?? [] });
113
114
  }
114
- async function fetchAsset(required) {
115
- const { ctx, url } = required;
115
+ async function fetchAsset({ ctx, item, state }, _optional = {}) {
116
+ const { url } = item;
116
117
  const outputFile = outputFileForUrl({ url });
117
118
  const response = await request(ctx, url);
118
119
  if (!response.ok) {
119
120
  await response.body?.cancel();
120
121
  return { reason: `GET ${url} -> ${response.status}` };
121
122
  }
122
- let data = Buffer.from(await response.arrayBuffer());
123
+ let data = await readAssetData({ response, state });
123
124
  const contentType = response.headers.get('content-type');
124
- const children = stylesheetChildren({ ctx, asset: { url, outputFile, data, contentType }, crawlCss: required.crawlCss });
125
+ const children = assetChildren({ ctx, asset: { url, outputFile, data, contentType }, crawlCss: item.crawlCss });
125
126
  if (/^(?:text\/css|application\/(?:[\w.+-]*\+)?json)\b/.test(contentType ?? '')) {
126
127
  data = Buffer.from(rewriteAssetBodyForBasePath({ body: data.toString('utf8'), contentType: contentType, basePath: ctx.basePath }));
127
128
  }
128
129
  await ctx.args.writer.write({ outputDir: ctx.args.outputDir, outputFile, data });
129
130
  return { asset: { url, outputFile, data, contentType }, children };
130
131
  }
131
- /** Stylesheets and JSON manifests reached from a route are scanned once; never recursive. */
132
- function stylesheetChildren(required) {
132
+ /** JSON dependencies are recursive within the crawl budget. CSS retains its single-hop policy. */
133
+ function assetChildren(required, _optional = {}) {
133
134
  const { ctx, asset } = required;
135
+ if (/\bjson\b/i.test(asset.contentType ?? ''))
136
+ return extractAssetUrls({ html: asset.data.toString('utf8'), prefixes: ctx.args.assetUrlPrefixes }, { format: 'json' });
134
137
  if (!required.crawlCss)
135
138
  return [];
136
139
  if (asset.url.split('?')[0].endsWith('.css'))
137
140
  return extractCssUrls({ css: asset.data.toString('utf8'), cssUrl: asset.url, prefixes: ctx.args.assetUrlPrefixes });
138
- if (/\bjson\b/.test(asset.contentType ?? ''))
139
- return extractAssetUrls({ html: asset.data.toString('utf8'), prefixes: ctx.args.assetUrlPrefixes }, { format: 'json' });
140
141
  return [];
141
142
  }
142
143
  function assetFailureReason(required) {
@@ -145,39 +146,37 @@ function assetFailureReason(required) {
145
146
  }
146
147
  /** Fetch one asset and queue its children, returning its physical output claim on success.
147
148
  * Failed variants leave the destination available for another URL's retry. */
148
- async function fetchAndQueueAsset({ ctx, url, crawlCss, queue }, out) {
149
- const outcome = await fetchAsset({ ctx, url, crawlCss });
149
+ async function fetchAndQueueAsset({ ctx, item, state, succeeded }, _optional = {}) {
150
+ const outcome = await fetchAsset({ ctx, item, state });
150
151
  if ('reason' in outcome) {
151
- out.failed.push({ url, reason: outcome.reason });
152
+ state.failed.push({ url: item.url, reason: outcome.reason });
152
153
  return;
153
154
  }
154
- out.succeeded.push(outcome.asset);
155
- for (const child of outcome.children)
156
- queue.push({ url: child, crawlCss: false });
155
+ succeeded.push(outcome.asset);
156
+ enqueueAssets({ state, urls: outcome.children, depth: item.depth + 1, crawlCss: false });
157
157
  return outcome.asset.outputFile;
158
158
  }
159
- async function writeAssets(ctx, initial) {
160
- const succeeded = [], failed = [];
161
- const seen = new Set(), written = new Set();
162
- const queue = initial.map(url => ({ url, crawlCss: true }));
163
- for (let index = 0; index < queue.length; index++) {
164
- const { url, crawlCss } = queue[index];
165
- if (seen.has(url))
166
- continue;
167
- seen.add(url);
159
+ async function writeAssets({ ctx, initial }, _optional = {}) {
160
+ const succeeded = [];
161
+ const state = createAssetCrawl({});
162
+ const written = new Set();
163
+ enqueueAssets({ state, urls: initial, depth: 0, crawlCss: true });
164
+ for (let index = 0; index < state.queue.length; index++) {
165
+ const item = state.queue[index];
166
+ const { url } = item;
168
167
  try {
169
168
  // Query/cache variants share one static filename; report exactly the file the writer owns.
170
169
  if (written.has(outputFileForUrl({ url })))
171
170
  continue;
172
- const outputFile = await fetchAndQueueAsset({ ctx, url, crawlCss, queue }, { succeeded, failed });
171
+ const outputFile = await fetchAndQueueAsset({ ctx, item, state, succeeded });
173
172
  if (outputFile !== undefined)
174
173
  written.add(outputFile);
175
174
  }
176
175
  catch (error) {
177
- failed.push({ url, reason: assetFailureReason({ ctx, url, error }) });
176
+ state.failed.push({ url, reason: assetFailureReason({ ctx, url, error }) });
178
177
  }
179
178
  }
180
- return { succeeded, failed };
179
+ return { succeeded, failed: state.failed };
181
180
  }
182
181
  async function unreferenced(ctx, manifest, assets) {
183
182
  if (!manifest.activeTheme)
@@ -312,7 +311,7 @@ export async function exportSite(required, optional = {}) {
312
311
  const ctx = { args: required, baseUrl: sessionOrigin({ baseUrl: session.baseUrl }), basePath, timeoutMs };
313
312
  const routes = await writeRoutes(ctx, manifest.routes);
314
313
  const explicitAssets = typeof required.assetUrls === 'function' ? await required.assetUrls() : required.assetUrls ?? [];
315
- const assets = await writeAssets(ctx, [...routes.assets, ...explicitAssets]);
314
+ const assets = await writeAssets({ ctx, initial: [...routes.assets, ...explicitAssets] });
316
315
  return { outputDir: required.outputDir, routes: { succeeded: routes.succeeded, failed: routes.failed }, assets, skippedManifestEntries: [...manifest.skipped, ...routes.skipped],
317
316
  droppedReferences: droppedReferences({ routes: routes.succeeded, assets: assets.succeeded, basePath, baseUrl: ctx.baseUrl }),
318
317
  unreferencedThemeFiles: await unreferenced(ctx, manifest, assets.succeeded), ...(basePath ? { basePath, basePathRewriteWarning: BASE_PATH_REWRITE_WARNING } : {}) };
@@ -42,7 +42,7 @@ export declare function extractHtmlReferences(required: {
42
42
  url: string;
43
43
  attribute: string;
44
44
  }>;
45
- /** Crawl only positions matching the response format; HTML text and script contents stay inert. */
45
+ /** Crawl format-specific positions, including bounded inline asset literals; scripts stay inert. */
46
46
  export declare function extractAssetUrls(required: {
47
47
  html: string;
48
48
  prefixes: readonly string[];
@@ -186,7 +186,7 @@ function assetCandidates(required, optional = {}) {
186
186
  if (optional.format === 'xml')
187
187
  return [...required.html.matchAll(/<(?:[\w-]+:)?(?:loc|url)>([^<]+)<\//g)].map(match => match[1]);
188
188
  const candidates = [];
189
- for (const { start, end, kind } of htmlUrlLocations(required)) {
189
+ for (const { start, end, kind } of htmlUrlLocations(required, { scriptAssets: true })) {
190
190
  if (kind === 'action')
191
191
  continue;
192
192
  const value = required.html.slice(start, end);
@@ -194,7 +194,7 @@ function assetCandidates(required, optional = {}) {
194
194
  }
195
195
  return candidates;
196
196
  }
197
- /** Crawl only positions matching the response format; HTML text and script contents stay inert. */
197
+ /** Crawl format-specific positions, including bounded inline asset literals; scripts stay inert. */
198
198
  export function extractAssetUrls(required, optional = {}) {
199
199
  const found = new Set();
200
200
  for (const url of assetCandidates(required, optional)) {
@@ -249,7 +249,7 @@ export function outputFileForUrl(required, optional = {}) {
249
249
  catch {
250
250
  throw new ExportPathError('Invalid URL encoding — refused');
251
251
  }
252
- const relative = trimCharsEnd({ text: decoded.startsWith('/') ? decoded.slice(1) : decoded, chars: '/' });
252
+ const relative = trimCharsEnd({ text: decoded.slice(1), chars: '/' });
253
253
  if (relative)
254
254
  safeRelativeOutputFile({ value: relative });
255
255
  const output = optional.contentRoute && !isJsonRoute(relative) ? contentIndexFile(relative) : relative;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/devops",
3
- "version": "0.7.3-next.3",
3
+ "version": "0.7.4",
4
4
  "description": "DevOps capabilities for deployment, source control, and CI/CD, exposed through independent subpaths.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -189,7 +189,7 @@
189
189
  "typescript": "opt-in: typescript source analysis — TypeScript source analysis could not load typescript. Install typescript to enable this feature, or check its installed version and native binaries.",
190
190
  "undici": "opt-in: custom http dispatchers; import @jini-ai/devops/deploy/node — Custom HTTP dispatchers could not load undici. Install undici to enable this feature, or check its installed version and native binaries.",
191
191
  "electron": "opt-in: desktop runtime selection; import @jini-ai/devops/local-dev — Desktop runtime selection could not load electron. Install electron to run the dev server on Electron-as-node, or use stock Node.",
192
- "react": "opt-in: react publish result view, ShowMoreImports and share expiry controls; import @jini-ai/devops/deploy/react, @jini-ai/devops/backup/site/react/ShowMoreImports or @jini-ai/devops/react/site-share-expiry — The publish result view, ShowMoreImports or share expiry controls could not load react. Install react to enable this feature, or check its installed version."
192
+ "react": "opt-in: react publish result view, ShowMoreImports and share expiry controls; import @jini-ai/devops/deploy/react, @jini-ai/devops/backup/site/react/ShowMoreImports, @jini-ai/devops/react/site-share-expiry or their hooks; import @jini-ai/devops/deploy/react/hooks/use-static-publish.hooks — The publish result view, ShowMoreImports or share expiry controls could not load react. Install react to enable this feature, or check its installed version."
193
193
  }
194
194
  },
195
195
  "type": "module",
@@ -1091,14 +1091,14 @@
1091
1091
  "react": "^19.2.0",
1092
1092
  "react-dom": "^19.2.0",
1093
1093
  "undici": "^7.30.1",
1094
- "@jini-ai/daemon": "0.7.3-next.3",
1095
- "@jini-ai/core": "^0.7.3-next.3",
1096
- "@jini-ai/platform": "^0.7.3-next.3",
1097
- "@jini-ai/integrations": "0.7.3-next.3",
1098
- "@jini-ai/db": "0.7.3-next.3"
1094
+ "@jini-ai/core": "^0.7.4",
1095
+ "@jini-ai/daemon": "0.7.4",
1096
+ "@jini-ai/db": "0.7.4",
1097
+ "@jini-ai/integrations": "0.7.4",
1098
+ "@jini-ai/platform": "^0.7.4"
1099
1099
  },
1100
1100
  "dependencies": {
1101
- "@jini-ai/core": "^0.7.3-next.3"
1101
+ "@jini-ai/core": "^0.7.4"
1102
1102
  },
1103
1103
  "peerDependencies": {
1104
1104
  "typescript": "^5.6.0",