@capybara-hq/kernel 0.1.0-rc.52 → 0.1.0-rc.54

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 (51) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/config/schema.d.ts +4 -0
  3. package/dist/config/schema.js +29 -0
  4. package/dist/conversations/attachments.service.d.ts +9 -1
  5. package/dist/conversations/attachments.service.js +42 -4
  6. package/dist/conversations/model-image.d.ts +33 -0
  7. package/dist/conversations/model-image.js +71 -0
  8. package/dist/db/kernel-schema.d.ts +10 -0
  9. package/dist/errors.d.ts +19 -0
  10. package/dist/errors.js +19 -0
  11. package/dist/http/api.module.js +8 -0
  12. package/dist/http/app.js +9 -0
  13. package/dist/http/meta.controller.d.ts +33 -0
  14. package/dist/http/meta.controller.js +72 -0
  15. package/dist/identity/app-auth.controller.d.ts +25 -0
  16. package/dist/identity/app-auth.controller.js +64 -0
  17. package/dist/identity/app-auth.d.ts +66 -0
  18. package/dist/identity/app-auth.js +203 -0
  19. package/dist/identity/app-auth.schemas.d.ts +47 -0
  20. package/dist/identity/app-auth.schemas.js +43 -0
  21. package/dist/identity/identity.module.d.ts +1 -1
  22. package/dist/identity/identity.module.js +4 -1
  23. package/dist/infra/config/kernel-config.service.js +2 -0
  24. package/dist/infra/outbox/registry.d.ts +14 -0
  25. package/dist/infra/outbox/registry.js +15 -0
  26. package/dist/infra/throttler/named-throttlers.d.ts +3 -2
  27. package/dist/infra/throttler/named-throttlers.js +14 -2
  28. package/dist/platform/exclusions.js +23 -0
  29. package/dist/platform/operation.js +1 -1
  30. package/dist/platform/ops/platform-icons.ops.d.ts +14 -0
  31. package/dist/platform/ops/platform-icons.ops.js +117 -0
  32. package/dist/platform/platform-ops.module.d.ts +2 -1
  33. package/dist/platform/platform-ops.module.js +3 -0
  34. package/dist/platform/route-schemas.js +3 -0
  35. package/dist/runtime/context/build.js +10 -2
  36. package/dist/runtime/maintenance.d.ts +5 -2
  37. package/dist/runtime/maintenance.js +15 -4
  38. package/dist/themes/platform-icon-objects.d.ts +51 -0
  39. package/dist/themes/platform-icon-objects.js +113 -0
  40. package/dist/themes/platform-icon-public.controller.d.ts +17 -0
  41. package/dist/themes/platform-icon-public.controller.js +58 -0
  42. package/dist/themes/platform-icon.controller.d.ts +22 -0
  43. package/dist/themes/platform-icon.controller.js +65 -0
  44. package/dist/themes/platform-icon.schemas.d.ts +48 -0
  45. package/dist/themes/platform-icon.schemas.js +53 -0
  46. package/dist/themes/platform-icon.service.d.ts +83 -0
  47. package/dist/themes/platform-icon.service.js +301 -0
  48. package/dist/themes/themes.module.d.ts +4 -1
  49. package/dist/themes/themes.module.js +9 -4
  50. package/package.json +5 -4
  51. package/src/migrations/0164_platform_icons.sql +10 -0
@@ -0,0 +1,117 @@
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 { z } from "zod";
12
+ import { PlatformIconBody, PlatformIconParams, } from "../../themes/platform-icon.schemas.js";
13
+ import { PlatformIconService } from "../../themes/platform-icon.service.js";
14
+ import { defineOperation } from "../operation.js";
15
+ import { PlatformOperations } from "../registry.js";
16
+ import { precheckBy, viaAgent } from "./errors.js";
17
+ const SetIconInput = PlatformIconParams.merge(PlatformIconBody).strict();
18
+ const ClearIconInput = PlatformIconParams.strict();
19
+ /** The card's name of an icon purpose. */
20
+ const NAMES = {
21
+ app: { zh: "应用图标", en: "app icon" },
22
+ maskable: { zh: "可遮罩应用图标", en: "maskable app icon" },
23
+ favicon: { zh: "网站图标(SVG)", en: "SVG favicon" },
24
+ };
25
+ /**
26
+ * The platform icon setting through the `Platform` tool (mobile layout spec §10.2.1): the list,
27
+ * upload and restore of `/api/v1/admin/platform/icons*`, run through the same service. The public
28
+ * read of the bytes is a transport exclusion.
29
+ */
30
+ let PlatformIconsOperations = class PlatformIconsOperations {
31
+ registry;
32
+ icons;
33
+ constructor(registry, icons) {
34
+ this.registry = registry;
35
+ this.icons = icons;
36
+ }
37
+ onModuleInit() {
38
+ this.registry.register([
39
+ defineOperation({
40
+ id: "admin.icons",
41
+ description: "List the platform icons the super admin uploaded: the app icon (app), its maskable variant (maskable) and the SVG favicon (favicon), each with its public URL, SHA-256 and when it was set. The installed web app, the browser tab and the native clients use them; a purpose not listed uses the built-in Capybara icon.",
42
+ input: z.object({}).strict(),
43
+ example: {},
44
+ authz: { superAdmin: true },
45
+ mirrors: ["GET /api/v1/admin/platform/icons"],
46
+ confirm: "read",
47
+ run: () => this.icons.list(),
48
+ }),
49
+ defineOperation({
50
+ id: "admin.set-icon",
51
+ description: "Upload a platform icon (super admin), given as standard base64 of the file, at most 1 MiB: app and maskable take a PNG (image/png) of exactly 512 × 512 pixels (maskable keeps its subject inside the central 80 % safe zone); favicon takes an SVG (image/svg+xml) of at most 128 KiB with a viewBox and no script, style element or external reference. It replaces the purpose's previous upload for every org and every installed app. The platform audit log records it.",
52
+ input: SetIconInput,
53
+ example: { purpose: "app", contentType: "image/png", dataBase64: "iVBORw0KGgo..." },
54
+ authz: { superAdmin: true },
55
+ mirrors: ["PUT /api/v1/admin/platform/icons/:purpose"],
56
+ confirm: "platform",
57
+ errors: [
58
+ {
59
+ code: "platform_icon.invalid_type",
60
+ next: "Send app and maskable as a PNG (image/png) and favicon as an SVG (image/svg+xml) with a viewBox and no script; the message says what was wrong.",
61
+ },
62
+ {
63
+ code: "platform_icon.invalid_size",
64
+ next: "Resize the PNG to exactly 512 × 512 pixels and upload it again.",
65
+ },
66
+ {
67
+ code: "platform_icon.too_large",
68
+ next: "Make the file at most 1 MiB (1048576 bytes), an SVG favicon at most 128 KiB (131072 bytes), and upload it again.",
69
+ },
70
+ {
71
+ code: "platform_icon.storage_unavailable",
72
+ next: {
73
+ superAdmin: "This deployment has no object storage: install and configure an object-store plugin in the admin console, then upload again.",
74
+ member: "This deployment has no object storage; ask the super admin to set one up.",
75
+ },
76
+ },
77
+ ],
78
+ precheck: (i) => precheckBy(() => this.icons.check(i.purpose, i.contentType, i.dataBase64)),
79
+ summary: async (i) => {
80
+ const n = NAMES[i.purpose];
81
+ const bytes = Math.floor((i.dataBase64.length * 3) / 4);
82
+ return {
83
+ zh: `把平台的${n.zh}换成上传的文件(约 ${bytes} 字节),所有组织和已安装的应用都会使用它`,
84
+ en: `Replace the platform ${n.en} with the uploaded file (about ${bytes} bytes); every org and installed app uses it`,
85
+ };
86
+ },
87
+ run: (i, ctx) => this.icons.set(i.purpose, i.contentType, i.dataBase64, { accountId: ctx.actorAccountId }, viaAgent("admin.set-icon", ctx)),
88
+ }),
89
+ defineOperation({
90
+ id: "admin.clear-icon",
91
+ description: "Restore the built-in Capybara icon for one platform icon purpose (super admin): app, maskable or favicon. The uploaded file is deleted. The platform audit log records it.",
92
+ input: ClearIconInput,
93
+ example: { purpose: "maskable" },
94
+ authz: { superAdmin: true },
95
+ mirrors: ["DELETE /api/v1/admin/platform/icons/:purpose"],
96
+ confirm: "platform",
97
+ summary: async (i) => {
98
+ const n = NAMES[i.purpose];
99
+ return {
100
+ zh: `把平台的${n.zh}恢复为内置的 Capybara 图标`,
101
+ en: `Restore the built-in Capybara ${n.en} for the platform`,
102
+ };
103
+ },
104
+ run: async (i, ctx) => {
105
+ const cleared = await this.icons.clear(i.purpose, { accountId: ctx.actorAccountId }, viaAgent("admin.clear-icon", ctx));
106
+ return { purpose: i.purpose, cleared };
107
+ },
108
+ }),
109
+ ]);
110
+ }
111
+ };
112
+ PlatformIconsOperations = __decorate([
113
+ Injectable(),
114
+ __param(0, Inject(PlatformOperations)),
115
+ __param(1, Inject(PlatformIconService))
116
+ ], PlatformIconsOperations);
117
+ export { PlatformIconsOperations };
@@ -23,6 +23,7 @@ import { OrgSettingsOperations } from "./ops/org-settings.ops.js";
23
23
  import { OrgsOperations } from "./ops/orgs.ops.js";
24
24
  import { OutboxOperations } from "./ops/outbox.ops.js";
25
25
  import { PlatformOperationsProvider } from "./ops/platform.ops.js";
26
+ import { PlatformIconsOperations } from "./ops/platform-icons.ops.js";
26
27
  import { PluginsOperations } from "./ops/plugins.ops.js";
27
28
  import { PreviewersOperations } from "./ops/previewers.ops.js";
28
29
  import { RequestsOperations } from "./ops/requests.ops.js";
@@ -36,7 +37,7 @@ import { UiOperations } from "./ops/ui.ops.js";
36
37
  * One provider per domain, each taking `PlatformOperations` as its first constructor argument:
37
38
  * the parity test in `tools/checks` builds the operations from it without a Nest app.
38
39
  */
39
- export declare const PLATFORM_OPERATION_PROVIDERS: readonly [typeof PlatformOperationsProvider, typeof SkillsOperations, typeof AgentsOperations, typeof AgentTemplatesOperations, typeof PluginsOperations, typeof MarketplacesOperations, typeof RequestsOperations, typeof ConnectorsOperations, typeof ExtensionsOperations, typeof ConversationsOperations, typeof ComponentsOperations, typeof AccountsOperations, typeof OrgsOperations, typeof AdminOperations, typeof CatalogAdminOperations, typeof OrgPluginsOperations, typeof ExtensionsAdminOperations, typeof ModelsOperations, typeof InboxOperations, typeof ApprovalsOperations, typeof ChannelsOperations, typeof OrgSettingsOperations, typeof EvalsOperations, typeof BackgroundOperations, typeof PreviewersOperations, typeof DevicesOperations, typeof AgentSkillsOperations, typeof ThemesOperations, typeof SetupOperations, typeof UiOperations, typeof AdminItemsOperations, typeof SchedulesOperations, typeof OutboxOperations, typeof SharesOperations];
40
+ export declare const PLATFORM_OPERATION_PROVIDERS: readonly [typeof PlatformOperationsProvider, typeof SkillsOperations, typeof AgentsOperations, typeof AgentTemplatesOperations, typeof PluginsOperations, typeof MarketplacesOperations, typeof RequestsOperations, typeof ConnectorsOperations, typeof ExtensionsOperations, typeof ConversationsOperations, typeof ComponentsOperations, typeof AccountsOperations, typeof OrgsOperations, typeof AdminOperations, typeof CatalogAdminOperations, typeof OrgPluginsOperations, typeof ExtensionsAdminOperations, typeof ModelsOperations, typeof InboxOperations, typeof ApprovalsOperations, typeof ChannelsOperations, typeof OrgSettingsOperations, typeof EvalsOperations, typeof BackgroundOperations, typeof PreviewersOperations, typeof DevicesOperations, typeof AgentSkillsOperations, typeof ThemesOperations, typeof SetupOperations, typeof UiOperations, typeof AdminItemsOperations, typeof SchedulesOperations, typeof OutboxOperations, typeof SharesOperations, typeof PlatformIconsOperations];
40
41
  /**
41
42
  * The `Platform` tool's operations (ruling P2): one provider per domain, each registering its
42
43
  * operations into `PlatformOperations` from `onModuleInit`. It imports the domain modules, which
@@ -52,6 +52,7 @@ import { OrgSettingsOperations } from "./ops/org-settings.ops.js";
52
52
  import { OrgsOperations } from "./ops/orgs.ops.js";
53
53
  import { OutboxOperations } from "./ops/outbox.ops.js";
54
54
  import { PlatformOperationsProvider } from "./ops/platform.ops.js";
55
+ import { PlatformIconsOperations } from "./ops/platform-icons.ops.js";
55
56
  import { PluginsOperations } from "./ops/plugins.ops.js";
56
57
  import { PreviewersOperations } from "./ops/previewers.ops.js";
57
58
  import { RequestsOperations } from "./ops/requests.ops.js";
@@ -114,6 +115,8 @@ export const PLATFORM_OPERATION_PROVIDERS = [
114
115
  OutboxOperations,
115
116
  // shared file links (file sharing spec §10)
116
117
  SharesOperations,
118
+ // the platform icon (mobile layout spec §10.2.1)
119
+ PlatformIconsOperations,
117
120
  ];
118
121
  /**
119
122
  * The `Platform` tool's operations (ruling P2): one provider per domain, each registering its
@@ -30,6 +30,7 @@ import { SETUP_CHECK_ROUTES } from "../setup/setup-checks.schemas.js";
30
30
  import { SETUP_GUIDE_ROUTES } from "../setup/setup-guides.schemas.js";
31
31
  import { SHARE_ROUTES } from "../shares/shares.schemas.js";
32
32
  import { SKILL_ROUTES } from "../skills/skills.schemas.js";
33
+ import { PLATFORM_ICON_ROUTES } from "../themes/platform-icon.schemas.js";
33
34
  import { THEME_ROUTES } from "../themes/themes.schemas.js";
34
35
  import { APPROVAL_ROUTES } from "../tools/approvals.schemas.js";
35
36
  import { CONNECTOR_ROUTES } from "../tools/connectors.schemas.js";
@@ -74,6 +75,8 @@ export const ROUTE_SCHEMAS = [
74
75
  ...ME_ROUTES,
75
76
  // themes (themes spec §9)
76
77
  ...THEME_ROUTES,
78
+ // the platform icon (mobile layout spec §10.2.1)
79
+ ...PLATFORM_ICON_ROUTES,
77
80
  // a plugin's suggested appearance (client extensions spec §6.5)
78
81
  ...APPEARANCE_ROUTES,
79
82
  // setup guide checks (setup guides v2 §10.3, §12)
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { MEDIA_LIMITS, } from "@capybara-hq/plugin-sdk";
2
+ import { IMAGE_MEDIA_TYPES, MEDIA_LIMITS, } from "@capybara-hq/plugin-sdk";
3
3
  import { renderBackgroundFinished } from "../../background/render.js";
4
4
  import { isAbsorbable, } from "../../conversations/events.js";
5
5
  import { catalogText, isAlwaysLoaded } from "../../tools/builtins/tool-search.js";
@@ -493,7 +493,15 @@ export function resolveMedia(content, model, ctx) {
493
493
  data: Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64"),
494
494
  };
495
495
  out.push(b.type === "image"
496
- ? { type: "image", mediaType: b.mediaType, source, ...(b.name !== undefined && { name }) }
496
+ ? {
497
+ type: "image",
498
+ // the fetched copy's type: an image may arrive re-encoded for the model
499
+ mediaType: IMAGE_MEDIA_TYPES.includes(got.mediaType)
500
+ ? got.mediaType
501
+ : b.mediaType,
502
+ source,
503
+ ...(b.name !== undefined && { name }),
504
+ }
497
505
  : {
498
506
  type: "document",
499
507
  mediaType: b.mediaType,
@@ -10,6 +10,7 @@ import { SandboxOperationReconcileJob } from "../sandbox/operation-reconcile.job
10
10
  import { SandboxService } from "../sandbox/sandbox.service.js";
11
11
  import { ScheduledTaskFirer } from "../schedules/fire.js";
12
12
  import { ShareObjects } from "../shares/share-objects.js";
13
+ import { PlatformIconObjects } from "../themes/platform-icon-objects.js";
13
14
  import { DeviceOpResolver } from "../tools/device-op-resolver.js";
14
15
  import { ToolDrift } from "../tools/drift.js";
15
16
  import { PermissionApprovalJobs } from "../tools/permission-approval-jobs.js";
@@ -27,7 +28,8 @@ export declare const MAINTENANCE_CONCURRENCY = 5;
27
28
  * {@link processStopTree} and `deliver-to-parent` → {@link processDeliverToParent} (both in
28
29
  * runtime/subagents/tree-jobs.ts, over {@link Waits}), `owned-plugin-cleanup` →
29
30
  * {@link OwnedPluginCleanup}, `sched-fire` and `sched-settle` → {@link ScheduledTaskFirer}, `device-op-resolve` →
30
- * {@link DeviceOpResolver}, `share-object-delete` → {@link ShareObjects}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
31
+ * {@link DeviceOpResolver}, `share-object-delete` → {@link ShareObjects}, `platform-icon-delete` →
32
+ * {@link PlatformIconObjects}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
31
33
  * such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
32
34
  * maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
33
35
  * test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
@@ -49,8 +51,9 @@ export declare class MaintenanceProcessor extends WorkerHost<Worker> {
49
51
  private readonly log;
50
52
  private readonly operations;
51
53
  private readonly shareObjects;
54
+ private readonly platformIcons;
52
55
  private readonly snapshots?;
53
- constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, scheduledTasks: Pick<ScheduledTaskFirer, "fire" | "settle">, deviceOps: Pick<DeviceOpResolver, "resolve">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke">, shareObjects: Pick<ShareObjects, "deleteObject">, snapshots?: Pick<CloudPermissionSnapshots, "reconcileDevice"> | undefined);
56
+ constructor(permissionApprovals: Pick<PermissionApprovalJobs, "recheck">, waits: Pick<Waits, "processTimeout" | "childFinished" | "stopChildren" | "stopDescendantsOfStopped" | "stopTree">, sandbox: Pick<SandboxService, "destroyDevice" | "resetFileSystem" | "revokeDeadHolder">, drift: Pick<ToolDrift, "check">, directory: Pick<DirectorySync, "runSyncJob">, deletion: Pick<RunDeletion, "stopOrg" | "stopTree">, offboarding: Pick<Offboarding, "stopRun">, runs: Pick<RunQueue, "ensureRun">, ownedCleanup: Pick<OwnedPluginCleanup, "run">, scheduledTasks: Pick<ScheduledTaskFirer, "fire" | "settle">, deviceOps: Pick<DeviceOpResolver, "resolve">, scheduled: Pick<ScheduledRuns, "runNow">, log: Pick<KernelLogger, "error" | "warn">, operations: Pick<SandboxOperationReconcileJob, "reconcile" | "revoke">, shareObjects: Pick<ShareObjects, "deleteObject">, platformIcons: Pick<PlatformIconObjects, "deleteObject">, snapshots?: Pick<CloudPermissionSnapshots, "reconcileDevice"> | undefined);
54
57
  process(job: Job, token?: string): Promise<void>;
55
58
  /** Starts consuming (worker role, after the extensions loaded; built with `autorun: false`). */
56
59
  start(): void;
@@ -33,6 +33,7 @@ import { SandboxService } from "../sandbox/sandbox.service.js";
33
33
  import { ScheduledTaskFireModule, ScheduledTaskFirer } from "../schedules/fire.js";
34
34
  import { SCHED_FIRE_JOB, SCHED_SETTLE_JOB, } from "../schedules/job-ids.js";
35
35
  import { SHARE_OBJECT_DELETE_JOB, ShareObjects, ShareObjectsModule, } from "../shares/share-objects.js";
36
+ import { PLATFORM_ICON_DELETE_JOB, PlatformIconObjects, PlatformIconObjectsModule, } from "../themes/platform-icon-objects.js";
36
37
  import { DeviceOpResolver } from "../tools/device-op-resolver.js";
37
38
  import { ToolDrift } from "../tools/drift.js";
38
39
  import { DRIFT_CONNECTOR_JOB } from "../tools/job-ids.js";
@@ -55,7 +56,8 @@ export const MAINTENANCE_CONCURRENCY = 5;
55
56
  * {@link processStopTree} and `deliver-to-parent` → {@link processDeliverToParent} (both in
56
57
  * runtime/subagents/tree-jobs.ts, over {@link Waits}), `owned-plugin-cleanup` →
57
58
  * {@link OwnedPluginCleanup}, `sched-fire` and `sched-settle` → {@link ScheduledTaskFirer}, `device-op-resolve` →
58
- * {@link DeviceOpResolver}, `share-object-delete` → {@link ShareObjects}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
59
+ * {@link DeviceOpResolver}, `share-object-delete` → {@link ShareObjects}, `platform-icon-delete` →
60
+ * {@link PlatformIconObjects}). The name of a periodic job (a `@LockedCron` / `@LockedInterval` job,
59
61
  * such as `sandbox-suspend-idle`) runs that job's body once ({@link ScheduledRuns.runNow}), as the
60
62
  * maintenance handlers did when those jobs were schedulers on this queue: an operator's or a
61
63
  * test's one-off run, not a second schedule (decision R23 of the Nest kernel spec). Any other
@@ -77,8 +79,9 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
77
79
  log;
78
80
  operations;
79
81
  shareObjects;
82
+ platformIcons;
80
83
  snapshots;
81
- constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, ownedCleanup, scheduledTasks, deviceOps, scheduled, log, operations, shareObjects, snapshots) {
84
+ constructor(permissionApprovals, waits, sandbox, drift, directory, deletion, offboarding, runs, ownedCleanup, scheduledTasks, deviceOps, scheduled, log, operations, shareObjects, platformIcons, snapshots) {
82
85
  super();
83
86
  this.permissionApprovals = permissionApprovals;
84
87
  this.waits = waits;
@@ -95,6 +98,7 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
95
98
  this.log = log;
96
99
  this.operations = operations;
97
100
  this.shareObjects = shareObjects;
101
+ this.platformIcons = platformIcons;
98
102
  this.snapshots = snapshots;
99
103
  }
100
104
  process(job, token) {
@@ -197,6 +201,10 @@ let MaintenanceProcessor = class MaintenanceProcessor extends WorkerHost {
197
201
  case SHARE_OBJECT_DELETE_JOB:
198
202
  await this.shareObjects.deleteObject(job.data);
199
203
  return;
204
+ // a platform icon object no row names any more, or an upload's orphan check (§10.2.1)
205
+ case PLATFORM_ICON_DELETE_JOB:
206
+ await this.platformIcons.deleteObject(job.data);
207
+ return;
200
208
  default:
201
209
  if (await this.scheduled.runNow(job.name))
202
210
  return;
@@ -236,8 +244,9 @@ MaintenanceProcessor = __decorate([
236
244
  __param(12, Inject(KERNEL_LOGGER)),
237
245
  __param(13, Inject(SandboxOperationReconcileJob)),
238
246
  __param(14, Inject(ShareObjects)),
239
- __param(15, Optional()),
240
- __param(15, Inject(CloudPermissionSnapshots))
247
+ __param(15, Inject(PlatformIconObjects)),
248
+ __param(16, Optional()),
249
+ __param(16, Inject(CloudPermissionSnapshots))
241
250
  ], MaintenanceProcessor);
242
251
  export { MaintenanceProcessor };
243
252
  /**
@@ -264,6 +273,8 @@ MaintenanceModule = __decorate([
264
273
  ScheduledTaskFireModule,
265
274
  // the share snapshot deletion
266
275
  ShareObjectsModule,
276
+ // the platform icon object deletion
277
+ PlatformIconObjectsModule,
267
278
  QueueModule.registerQueue(MAINTENANCE_QUEUE_NAME),
268
279
  ],
269
280
  providers: [
@@ -0,0 +1,51 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { LockService } from "../infra/lock/lock.service.js";
3
+ import type { OutboxService } from "../infra/outbox/outbox.service.js";
4
+ import { StorageService } from "../storage/storage.service.js";
5
+ import type { PlatformIconPurpose } from "./platform-icon.schemas.js";
6
+ /** The object key of an icon, relative to the kernel's `deployment/` prefix. */
7
+ export declare const platformIconKey: (purpose: PlatformIconPurpose, sha256: string) => string;
8
+ /** The `LockService` key of a purpose's icon writes and deletions (no `:`). */
9
+ export declare const platformIconLockKey: (purpose: PlatformIconPurpose) => string;
10
+ /** How long a write or the deletion job holds the purpose's lock without renewal, and waits for it. */
11
+ export declare const PLATFORM_ICON_LOCK: {
12
+ readonly ttlMs: 30000;
13
+ readonly waitMs: 10000;
14
+ };
15
+ /** The maintenance job that deletes one icon object no row names. */
16
+ export declare const PLATFORM_ICON_DELETE_JOB = "platform-icon-delete";
17
+ /** Outbox id of the deletion a replace or clear owes for the object the row stopped naming. */
18
+ export declare const platformIconDeleteJobId: (purpose: PlatformIconPurpose, sha256: string) => string;
19
+ /** Outbox id of the delayed check an upload owes for its own object before writing it. */
20
+ export declare const platformIconOrphanJobId: (purpose: PlatformIconPurpose, sha256: string) => string;
21
+ /** How long after an upload starts its orphan check runs (the upload is long done by then). */
22
+ export declare const PLATFORM_ICON_ORPHAN_DELAY_MS: number;
23
+ /** The data of a {@link PLATFORM_ICON_DELETE_JOB}. */
24
+ export interface PlatformIconDeleteData {
25
+ purpose: PlatformIconPurpose;
26
+ objectKey: string;
27
+ }
28
+ /**
29
+ * Owes the deletion of a purpose's object in the caller's transaction: at once (`runAt` absent,
30
+ * a replace or clear) or later (an upload's orphan check, under its own id).
31
+ */
32
+ export declare function owePlatformIconDelete(outbox: Pick<OutboxService, "add">, purpose: PlatformIconPurpose, sha256: string, opts?: {
33
+ orphanCheck?: boolean;
34
+ }): Promise<void>;
35
+ /**
36
+ * Runs a {@link PLATFORM_ICON_DELETE_JOB} (the maintenance processor dispatches it here). Under
37
+ * the purpose's lock it deletes the object unless the purpose's row names it; delivered twice it
38
+ * is harmless (deleting a missing object is a no-op). A lock it cannot take in time throws, and
39
+ * BullMQ retries the job.
40
+ */
41
+ export declare class PlatformIconObjects {
42
+ private readonly db;
43
+ private readonly locks;
44
+ private readonly storage;
45
+ constructor(db: KernelDb, locks: LockService, storage: Pick<StorageService, "deployment">);
46
+ /** Deletes the object unless the row names it; see the class comment. */
47
+ deleteObject(data: PlatformIconDeleteData): Promise<void>;
48
+ }
49
+ /** {@link PlatformIconObjects} for the maintenance worker (storage, the database and locks only). */
50
+ export declare class PlatformIconObjectsModule {
51
+ }
@@ -0,0 +1,113 @@
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, Module } from "@nestjs/common";
11
+ import { KernelDb } from "../infra/database/kernel-db.js";
12
+ import { LockService } from "../infra/lock/lock.service.js";
13
+ import { MAINTENANCE_QUEUE_NAME } from "../runtime/maintenance-queue.js";
14
+ import { StorageModule } from "../storage/storage.module.js";
15
+ import { StorageService } from "../storage/storage.service.js";
16
+ /**
17
+ * Platform icon objects in object storage (mobile layout spec §10.2.1): the icon of a purpose with
18
+ * SHA-256 `h` is `platform-icons/<purpose>-<h>.<png|svg>` under the kernel's `deployment/` prefix,
19
+ * so the same bytes always land on the same key. An upload writes its object before the row that
20
+ * names it; an object no row names is deleted through the outbox ({@link PLATFORM_ICON_DELETE_JOB}):
21
+ * the upload owes a delayed check of its own object first (an upload that never commits leaves no
22
+ * orphan), and a replace or clear owes the deletion of the object the row stops naming.
23
+ *
24
+ * Because keys are content addressed, a later upload of the same bytes may name a key again after
25
+ * its deletion was owed: uploads, clears and the job hold {@link platformIconLockKey} for the
26
+ * purpose, so the job's "no row names it" check and its delete never interleave with an upload
27
+ * between its object write and its commit.
28
+ */
29
+ /** The file extension of a purpose's object (its type is fixed by the purpose). */
30
+ const extensionOf = (purpose) => purpose === "favicon" ? "svg" : "png";
31
+ /** The object key of an icon, relative to the kernel's `deployment/` prefix. */
32
+ export const platformIconKey = (purpose, sha256) => `platform-icons/${purpose}-${sha256}.${extensionOf(purpose)}`;
33
+ /** True when `key` is one {@link platformIconKey} makes for `purpose`. */
34
+ const isIconKeyOf = (purpose, key) => new RegExp(`^platform-icons/${purpose}-[0-9a-f]{64}\\.${extensionOf(purpose)}$`).test(key);
35
+ /** The `LockService` key of a purpose's icon writes and deletions (no `:`). */
36
+ export const platformIconLockKey = (purpose) => `platform-icon-${purpose}`;
37
+ /** How long a write or the deletion job holds the purpose's lock without renewal, and waits for it. */
38
+ export const PLATFORM_ICON_LOCK = { ttlMs: 30_000, waitMs: 10_000 };
39
+ /** The maintenance job that deletes one icon object no row names. */
40
+ export const PLATFORM_ICON_DELETE_JOB = "platform-icon-delete";
41
+ /** Outbox id of the deletion a replace or clear owes for the object the row stopped naming. */
42
+ export const platformIconDeleteJobId = (purpose, sha256) => `platform-icon-delete-${purpose}-${sha256}`;
43
+ /** Outbox id of the delayed check an upload owes for its own object before writing it. */
44
+ export const platformIconOrphanJobId = (purpose, sha256) => `platform-icon-orphan-${purpose}-${sha256}`;
45
+ /** How long after an upload starts its orphan check runs (the upload is long done by then). */
46
+ export const PLATFORM_ICON_ORPHAN_DELAY_MS = 10 * 60 * 1000;
47
+ /**
48
+ * Owes the deletion of a purpose's object in the caller's transaction: at once (`runAt` absent,
49
+ * a replace or clear) or later (an upload's orphan check, under its own id).
50
+ */
51
+ export async function owePlatformIconDelete(outbox, purpose, sha256, opts = {}) {
52
+ const data = { purpose, objectKey: platformIconKey(purpose, sha256) };
53
+ await outbox.add({
54
+ queue: MAINTENANCE_QUEUE_NAME,
55
+ name: PLATFORM_ICON_DELETE_JOB,
56
+ jobId: opts.orphanCheck
57
+ ? platformIconOrphanJobId(purpose, sha256)
58
+ : platformIconDeleteJobId(purpose, sha256),
59
+ data,
60
+ ...(opts.orphanCheck && { runAt: new Date(Date.now() + PLATFORM_ICON_ORPHAN_DELAY_MS) }),
61
+ });
62
+ }
63
+ /**
64
+ * Runs a {@link PLATFORM_ICON_DELETE_JOB} (the maintenance processor dispatches it here). Under
65
+ * the purpose's lock it deletes the object unless the purpose's row names it; delivered twice it
66
+ * is harmless (deleting a missing object is a no-op). A lock it cannot take in time throws, and
67
+ * BullMQ retries the job.
68
+ */
69
+ let PlatformIconObjects = class PlatformIconObjects {
70
+ db;
71
+ locks;
72
+ storage;
73
+ constructor(db, locks, storage) {
74
+ this.db = db;
75
+ this.locks = locks;
76
+ this.storage = storage;
77
+ }
78
+ /** Deletes the object unless the row names it; see the class comment. */
79
+ async deleteObject(data) {
80
+ if (!isIconKeyOf(data.purpose, data.objectKey)) {
81
+ // never delete anything outside the purpose's own icon keys, whatever the job data says
82
+ throw new Error(`platform-icon-delete: unexpected object key for ${data.purpose}`);
83
+ }
84
+ await this.locks.run(platformIconLockKey(data.purpose), PLATFORM_ICON_LOCK, async () => {
85
+ const row = await this.db
86
+ .selectFrom("platform_icons")
87
+ .select("object_key")
88
+ .where("purpose", "=", data.purpose)
89
+ .executeTakeFirst();
90
+ if (row?.object_key === data.objectKey)
91
+ return;
92
+ await this.storage.deployment().delete(data.objectKey);
93
+ });
94
+ }
95
+ };
96
+ PlatformIconObjects = __decorate([
97
+ Injectable(),
98
+ __param(0, Inject(KernelDb)),
99
+ __param(1, Inject(LockService)),
100
+ __param(2, Inject(StorageService))
101
+ ], PlatformIconObjects);
102
+ export { PlatformIconObjects };
103
+ /** {@link PlatformIconObjects} for the maintenance worker (storage, the database and locks only). */
104
+ let PlatformIconObjectsModule = class PlatformIconObjectsModule {
105
+ };
106
+ PlatformIconObjectsModule = __decorate([
107
+ Module({
108
+ imports: [StorageModule],
109
+ providers: [PlatformIconObjects],
110
+ exports: [PlatformIconObjects],
111
+ })
112
+ ], PlatformIconObjectsModule);
113
+ export { PlatformIconObjectsModule };
@@ -0,0 +1,17 @@
1
+ import type { FastifyReply } from "fastify";
2
+ import type { z } from "zod";
3
+ import { PlatformIconParams, PlatformIconQuery } from "./platform-icon.schemas.js";
4
+ import { PlatformIconService } from "./platform-icon.service.js";
5
+ /**
6
+ * The platform icon's bytes (mobile layout spec §10.2.1), public: the PWA manifest, the favicons
7
+ * and native clients read it before sign-in, and an icon is not sensitive. `?v=<sha256>` (the URL
8
+ * the settings list) is cached as immutable; without `v` the response is revalidated; a `v` that is
9
+ * not the current hash, or a purpose with no upload, is 404 `platform_icon.not_found` (the web then
10
+ * uses its built-in icon). The type is fixed by the purpose, with `nosniff`; the SVG favicon also
11
+ * gets a sandbox CSP, so opened directly it runs nothing and loads nothing.
12
+ */
13
+ export declare class PlatformIconPublicController {
14
+ private readonly icons;
15
+ constructor(icons: PlatformIconService);
16
+ icon({ purpose }: z.infer<typeof PlatformIconParams>, { v }: z.infer<typeof PlatformIconQuery>, reply: FastifyReply): Promise<void>;
17
+ }
@@ -0,0 +1,58 @@
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 { Controller, Get, Inject, Res } from "@nestjs/common";
11
+ import { Public } from "../identity/principal.js";
12
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
13
+ import { ZParam, ZQuery } from "../infra/validation/zod-params.js";
14
+ import { PlatformIconParams, PlatformIconQuery } from "./platform-icon.schemas.js";
15
+ import { PlatformIconService } from "./platform-icon.service.js";
16
+ class PlatformIconPublicParamsDto extends createZodDto(PlatformIconParams, "PlatformIconPublicParams") {
17
+ }
18
+ class PlatformIconQueryDto extends createZodDto(PlatformIconQuery, "PlatformIconQuery") {
19
+ }
20
+ /** With the current hash in `v` the URL's bytes never change. */
21
+ const IMMUTABLE = "public, max-age=31536000, immutable";
22
+ /**
23
+ * The platform icon's bytes (mobile layout spec §10.2.1), public: the PWA manifest, the favicons
24
+ * and native clients read it before sign-in, and an icon is not sensitive. `?v=<sha256>` (the URL
25
+ * the settings list) is cached as immutable; without `v` the response is revalidated; a `v` that is
26
+ * not the current hash, or a purpose with no upload, is 404 `platform_icon.not_found` (the web then
27
+ * uses its built-in icon). The type is fixed by the purpose, with `nosniff`; the SVG favicon also
28
+ * gets a sandbox CSP, so opened directly it runs nothing and loads nothing.
29
+ */
30
+ let PlatformIconPublicController = class PlatformIconPublicController {
31
+ icons;
32
+ constructor(icons) {
33
+ this.icons = icons;
34
+ }
35
+ async icon({ purpose }, { v }, reply) {
36
+ const icon = await this.icons.read(purpose, v);
37
+ reply
38
+ .header("content-type", icon.contentType)
39
+ .header("x-content-type-options", "nosniff")
40
+ .header("cache-control", icon.immutable ? IMMUTABLE : "no-cache");
41
+ if (icon.contentType === "image/svg+xml") {
42
+ reply.header("content-security-policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox");
43
+ }
44
+ await reply.send(Buffer.from(icon.bytes.buffer, icon.bytes.byteOffset, icon.bytes.byteLength));
45
+ }
46
+ };
47
+ __decorate([
48
+ Public(),
49
+ Get(":purpose"),
50
+ __param(0, ZParam(PlatformIconPublicParamsDto)),
51
+ __param(1, ZQuery(PlatformIconQueryDto)),
52
+ __param(2, Res())
53
+ ], PlatformIconPublicController.prototype, "icon", null);
54
+ PlatformIconPublicController = __decorate([
55
+ Controller("api/v1/platform/icon"),
56
+ __param(0, Inject(PlatformIconService))
57
+ ], PlatformIconPublicController);
58
+ export { PlatformIconPublicController };
@@ -0,0 +1,22 @@
1
+ import type { z } from "zod";
2
+ import { type Principal } from "../identity/principal.js";
3
+ import { PlatformIconBody, PlatformIconParams, type PlatformIconView } from "./platform-icon.schemas.js";
4
+ import { PlatformIconService } from "./platform-icon.service.js";
5
+ /**
6
+ * The platform icon setting (`/api/v1/admin/platform/icons*`, mobile layout spec §10.2.1): the
7
+ * app icon, its maskable variant and the SVG favicon the PWA manifest, the favicons and native
8
+ * clients use. Super admins only (one installed app per deployment); service tokens 403. The
9
+ * upload is JSON base64 so the Platform tool mirrors it (`admin.set-icon`).
10
+ */
11
+ export declare class PlatformIconController {
12
+ private readonly icons;
13
+ constructor(icons: PlatformIconService);
14
+ /** `{ icons }`: every uploaded icon with its public URL; a purpose not listed uses the default. */
15
+ list(): Promise<{
16
+ icons: PlatformIconView[];
17
+ }>;
18
+ /** Uploads the icon of a purpose (PNG 512 × 512 for app / maskable, SVG for favicon, ≤ 1 MiB). */
19
+ set(principal: Principal, { purpose }: z.infer<typeof PlatformIconParams>, body: z.infer<typeof PlatformIconBody>): Promise<PlatformIconView>;
20
+ /** Restores the built-in icon of a purpose; 204 also when none was uploaded. */
21
+ clear(principal: Principal, { purpose }: z.infer<typeof PlatformIconParams>): Promise<void>;
22
+ }
@@ -0,0 +1,65 @@
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 { Controller, Delete, Get, HttpCode, Inject, Put } from "@nestjs/common";
11
+ import { CurrentPrincipal, SuperAdmin } from "../identity/principal.js";
12
+ import { writeActorOf } from "../identity/write-actor.js";
13
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
14
+ import { ZBody, ZParam } from "../infra/validation/zod-params.js";
15
+ import { PlatformIconBody, PlatformIconParams, } from "./platform-icon.schemas.js";
16
+ import { PlatformIconService } from "./platform-icon.service.js";
17
+ class PlatformIconParamsDto extends createZodDto(PlatformIconParams, "PlatformIconParams") {
18
+ }
19
+ class PlatformIconBodyDto extends createZodDto(PlatformIconBody, "PlatformIconBody") {
20
+ }
21
+ /**
22
+ * The platform icon setting (`/api/v1/admin/platform/icons*`, mobile layout spec §10.2.1): the
23
+ * app icon, its maskable variant and the SVG favicon the PWA manifest, the favicons and native
24
+ * clients use. Super admins only (one installed app per deployment); service tokens 403. The
25
+ * upload is JSON base64 so the Platform tool mirrors it (`admin.set-icon`).
26
+ */
27
+ let PlatformIconController = class PlatformIconController {
28
+ icons;
29
+ constructor(icons) {
30
+ this.icons = icons;
31
+ }
32
+ /** `{ icons }`: every uploaded icon with its public URL; a purpose not listed uses the default. */
33
+ list() {
34
+ return this.icons.list();
35
+ }
36
+ /** Uploads the icon of a purpose (PNG 512 × 512 for app / maskable, SVG for favicon, ≤ 1 MiB). */
37
+ set(principal, { purpose }, body) {
38
+ return this.icons.set(purpose, body.contentType, body.dataBase64, writeActorOf(principal));
39
+ }
40
+ /** Restores the built-in icon of a purpose; 204 also when none was uploaded. */
41
+ async clear(principal, { purpose }) {
42
+ await this.icons.clear(purpose, writeActorOf(principal));
43
+ }
44
+ };
45
+ __decorate([
46
+ Get()
47
+ ], PlatformIconController.prototype, "list", null);
48
+ __decorate([
49
+ Put(":purpose"),
50
+ __param(0, CurrentPrincipal()),
51
+ __param(1, ZParam(PlatformIconParamsDto)),
52
+ __param(2, ZBody(PlatformIconBodyDto))
53
+ ], PlatformIconController.prototype, "set", null);
54
+ __decorate([
55
+ Delete(":purpose"),
56
+ HttpCode(204),
57
+ __param(0, CurrentPrincipal()),
58
+ __param(1, ZParam(PlatformIconParamsDto))
59
+ ], PlatformIconController.prototype, "clear", null);
60
+ PlatformIconController = __decorate([
61
+ Controller("api/v1/admin/platform/icons"),
62
+ SuperAdmin(),
63
+ __param(0, Inject(PlatformIconService))
64
+ ], PlatformIconController);
65
+ export { PlatformIconController };