@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
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.37";
191
+ readonly sdk: "0.1.0-rc.38";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -62,6 +62,9 @@ export declare function allowedHostProblem(entry: string): string | undefined;
62
62
  */
63
63
  export declare function trustProxyEntryProblem(entry: string): string | undefined;
64
64
  export declare const KernelConfigSchema: z.ZodObject<{
65
+ platform: z.ZodPrefault<z.ZodObject<{
66
+ name: z.ZodOptional<z.ZodString>;
67
+ }, z.core.$strict>>;
65
68
  db: z.ZodPrefault<z.ZodObject<{
66
69
  url: z.ZodString;
67
70
  poolMax: z.ZodDefault<z.ZodNumber>;
@@ -130,6 +133,7 @@ export declare const KernelConfigSchema: z.ZodObject<{
130
133
  accessTokenTtlSeconds: z.ZodDefault<z.ZodNumber>;
131
134
  refreshTokenTtlDays: z.ZodDefault<z.ZodNumber>;
132
135
  cookieSecure: z.ZodDefault<z.ZodBoolean>;
136
+ appRedirectUris: z.ZodDefault<z.ZodArray<z.ZodString>>;
133
137
  setupToken: z.ZodOptional<z.ZodPreprocess<z.ZodOptional<z.ZodString>, unknown>>;
134
138
  loginSources: z.ZodDefault<z.ZodArray<z.ZodString>>;
135
139
  trustedIdentitySources: z.ZodDefault<z.ZodArray<z.ZodString>>;
@@ -22,6 +22,8 @@ function isValidMasterKey(value) {
22
22
  * 插件名同清单规则(不能是 `local`),租户 id 非空、不含空白;与 identity/external.ts 的身份源键规则一致。
23
23
  */
24
24
  const TRUSTED_SOURCE_RE = /^(?!local:)[a-z0-9][a-z0-9._-]{0,213}:\S{1,256}$/;
25
+ /** Schemes an app redirect URI never uses: the consent page navigates to it. */
26
+ const UNSAFE_REDIRECT_RE = /^\s*(?:javascript|data|vbscript|file):/i;
25
27
  /** `sandbox.limits.maxCommandSeconds` 的默认值。 */
26
28
  export const DEFAULT_MAX_COMMAND_SECONDS = 7200;
27
29
  /** access token 寿命上限(秒);会话吊销标记的 TTL 按它计算,与实例当前配置无关。 */
@@ -304,6 +306,19 @@ export function trustProxyEntryProblem(entry) {
304
306
  return undefined;
305
307
  }
306
308
  export const KernelConfigSchema = z.strictObject({
309
+ platform: z
310
+ .strictObject({
311
+ name: z
312
+ .string()
313
+ .min(1)
314
+ .max(64)
315
+ .optional()
316
+ .meta(meta({
317
+ hot: true,
318
+ description: "The platform's display name (1 to 64 characters), shown by native clients and the installed web app before sign-in (GET /api/v1/meta); unset: clients show their own name",
319
+ })),
320
+ })
321
+ .prefault({}),
307
322
  db: z
308
323
  .strictObject({
309
324
  url: z
@@ -681,6 +696,19 @@ export const KernelConfigSchema = z.strictObject({
681
696
  .meta(meta({
682
697
  description: "Set the Secure attribute on session cookies; set false only for local trials over plain http",
683
698
  })),
699
+ appRedirectUris: z
700
+ .array(z
701
+ .string()
702
+ .min(1)
703
+ .max(2048)
704
+ .refine((v) => URL.canParse(v) && !v.includes("#") && !UNSAFE_REDIRECT_RE.test(v), {
705
+ message: "Each entry must be an absolute URI without a fragment (for example capybara://auth/callback); javascript:, data:, vbscript: and file: are not allowed",
706
+ }))
707
+ .max(20)
708
+ .default(["capybara://auth/callback"])
709
+ .meta(meta({
710
+ description: "Redirect URIs native apps may receive a sign-in code at (desktop client spec §6.5), matched exactly; a fork that ships its own build under another scheme adds its URI here",
711
+ })),
684
712
  setupToken: z
685
713
  // An empty value means "not set" (compose passes ${CAPYBARA_SETUP_TOKEN:-}). Env values are
686
714
  // JSON-parsed, so an all-digit or true / false token arrives as a number or boolean: it is
@@ -714,6 +742,7 @@ export const KernelConfigSchema = z.strictObject({
714
742
  accessTokenTtlSeconds: 900,
715
743
  refreshTokenTtlDays: 30,
716
744
  cookieSecure: true,
745
+ appRedirectUris: ["capybara://auth/callback"],
717
746
  loginSources: [],
718
747
  trustedIdentitySources: [],
719
748
  }),
@@ -1,5 +1,6 @@
1
1
  import { type PresignedUpload } from "@capybara-hq/plugin-sdk";
2
2
  import type { AttachmentPurpose } from "../db/kernel-schema.js";
3
+ import { CacheService } from "../infra/cache/cache.service.js";
3
4
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
4
5
  import { KernelDb } from "../infra/database/kernel-db.js";
5
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -142,9 +143,13 @@ export declare class AttachmentsService {
142
143
  private readonly access;
143
144
  private readonly log;
144
145
  readonly txHost: TransactionHost;
146
+ /** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
147
+ private readonly cache;
145
148
  constructor(db: KernelDb, storage: Pick<StorageService, "available" | "assertAvailable" | "kernel">, config: Pick<KernelConfigService, "get">,
146
149
  /** viewer 能否访问该会话(与会话流相同的规则)。 */
147
- access: Pick<ConversationAccess, "isAccessible">, log: Pick<KernelLogger, "info" | "warn">, txHost: TransactionHost);
150
+ access: Pick<ConversationAccess, "isAccessible">, log: Pick<KernelLogger, "info" | "warn">, txHost: TransactionHost,
151
+ /** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
152
+ cache: Pick<CacheService, "get" | "set">);
148
153
  /** 单个附件的大小上限:配置的 `maxBytes`,图片再受 `MEDIA_LIMITS.imageBytes` 限制。 */
149
154
  private limitFor;
150
155
  /** 当前配置下的上限(不需要对象存储)。 */
@@ -237,6 +242,9 @@ export declare class AttachmentsService {
237
242
  * not the recorded one (content replaced, logged as a warning). Every other error (storage
238
243
  * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
239
244
  * placeholder. An id in `caps` is read by range up to that many leading bytes (the `text/*` cap).
245
+ * A whole image comes back as its model-sized copy ({@link fitImageForModel}), whose media type
246
+ * may differ from the row's; the copy is cached for {@link MODEL_IMAGE_CACHE_SECONDS} under the
247
+ * attachment's id and etag, so later steps of the conversation only check the object's head.
240
248
  */
241
249
  fetchMedia(orgId: string, conversationId: string, ids: readonly string[], caps?: ReadonlyMap<string, number>): Promise<Map<string, MediaBytes | null>>;
242
250
  /**
@@ -12,6 +12,7 @@ import { MEDIA_LIMITS } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { sql } from "kysely";
14
14
  import { ApiError } from "../errors.js";
15
+ import { CacheService } from "../infra/cache/cache.service.js";
15
16
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
16
17
  import { KernelDb } from "../infra/database/kernel-db.js";
17
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -22,6 +23,7 @@ import { KERNEL_LOGGER } from "../infra/tokens.js";
22
23
  import { StorageService } from "../storage/storage.service.js";
23
24
  import { ConversationAccess } from "./access.js";
24
25
  import { acceptedContent, isImageContentType, isMediaContentType } from "./media-types.js";
26
+ import { fitImageForModel, MODEL_IMAGE_CACHE_SECONDS, modelImageKey, parseModelImage, serializeModelImage, } from "./model-image.js";
25
27
  /** 预签名上传的有效期(秒)。尽量短:表单在有效期内可被再次使用(内容替换由 etag 核对兜底)。 */
26
28
  export const ATTACHMENT_UPLOAD_TTL_SECONDS = 300;
27
29
  /** 下载跳转的预签名有效期(秒);不短于 {@link ATTACHMENT_DOWNLOAD_CACHE_SECONDS}(浏览器缓存的跳转仍可用)。 */
@@ -151,15 +153,19 @@ let AttachmentsService = class AttachmentsService {
151
153
  access;
152
154
  log;
153
155
  txHost;
156
+ cache;
154
157
  constructor(db, storage, config,
155
158
  /** viewer 能否访问该会话(与会话流相同的规则)。 */
156
- access, log, txHost) {
159
+ access, log, txHost,
160
+ /** where the model-sized copies of images are kept between steps ({@link fetchMedia}) */
161
+ cache) {
157
162
  this.db = db;
158
163
  this.storage = storage;
159
164
  this.config = config;
160
165
  this.access = access;
161
166
  this.log = log;
162
167
  this.txHost = txHost;
168
+ this.cache = cache;
163
169
  }
164
170
  /** 单个附件的大小上限:配置的 `maxBytes`,图片再受 `MEDIA_LIMITS.imageBytes` 限制。 */
165
171
  limitFor(contentType) {
@@ -569,6 +575,9 @@ let AttachmentsService = class AttachmentsService {
569
575
  * not the recorded one (content replaced, logged as a warning). Every other error (storage
570
576
  * unavailable, network) throws (Ruling M4) for the caller to treat as retryable, never a
571
577
  * placeholder. An id in `caps` is read by range up to that many leading bytes (the `text/*` cap).
578
+ * A whole image comes back as its model-sized copy ({@link fitImageForModel}), whose media type
579
+ * may differ from the row's; the copy is cached for {@link MODEL_IMAGE_CACHE_SECONDS} under the
580
+ * attachment's id and etag, so later steps of the conversation only check the object's head.
572
581
  */
573
582
  async fetchMedia(orgId, conversationId, ids, caps) {
574
583
  const out = new Map();
@@ -590,11 +599,28 @@ let AttachmentsService = class AttachmentsService {
590
599
  if (!r)
591
600
  return out.set(id, null);
592
601
  const cap = caps?.get(id);
602
+ const where = { orgId, conversationId, attachmentId: id };
603
+ // a whole image already scaled for the model: the cached copy, once the object checks out
604
+ const cacheKey = cap === undefined && isImageContentType(r.content_type)
605
+ ? modelImageKey(orgId, r)
606
+ : undefined;
607
+ const cached = cacheKey === undefined ? null : parseModelImage(await this.cache.get(cacheKey));
608
+ if (cached) {
609
+ const head = await store.head(r.object_key);
610
+ if (!head)
611
+ return out.set(id, null);
612
+ if (head.size !== Number(r.size) || !this.sameContent(r.etag, head.etag, where)) {
613
+ if (head.size !== Number(r.size)) {
614
+ this.log.warn("attachment size changed after finalize; treating it as unavailable", where);
615
+ }
616
+ return out.set(id, null);
617
+ }
618
+ return out.set(id, cached);
619
+ }
593
620
  const want = cap !== undefined && cap < Number(r.size) ? Math.max(1, cap) : Number(r.size);
594
621
  const got = await store.get(r.object_key, want < Number(r.size) ? { range: { start: 0, end: want - 1 } } : undefined);
595
622
  if (!got)
596
623
  return out.set(id, null);
597
- const where = { orgId, conversationId, attachmentId: id };
598
624
  if (got.head.size !== Number(r.size) || !this.sameContent(r.etag, got.head.etag, where)) {
599
625
  if (got.head.size !== Number(r.size)) {
600
626
  this.log.warn("attachment size changed after finalize; treating it as unavailable", where);
@@ -605,7 +631,18 @@ let AttachmentsService = class AttachmentsService {
605
631
  // 提供方没按范围读、给了整个对象时只留开头
606
632
  const all = await readAll(got.body);
607
633
  const data = all.byteLength === Number(r.size) ? all.subarray(0, want) : all;
608
- out.set(id, data.byteLength === want ? { mediaType: r.content_type, data } : null);
634
+ if (data.byteLength !== want)
635
+ return out.set(id, null);
636
+ const media = { mediaType: r.content_type, data };
637
+ if (cacheKey === undefined) {
638
+ return out.set(id, media);
639
+ }
640
+ // a whole image goes out as the model-sized copy (the stored object stays unchanged)
641
+ const fitted = await fitImageForModel(media);
642
+ if (fitted !== media) {
643
+ await this.cache.set(cacheKey, serializeModelImage(fitted), MODEL_IMAGE_CACHE_SECONDS);
644
+ }
645
+ out.set(id, fitted);
609
646
  }));
610
647
  return out;
611
648
  }
@@ -1020,7 +1057,8 @@ AttachmentsService = __decorate([
1020
1057
  __param(2, Inject(KernelConfigService)),
1021
1058
  __param(3, Inject(ConversationAccess)),
1022
1059
  __param(4, Inject(KERNEL_LOGGER)),
1023
- __param(5, Inject(TransactionHost))
1060
+ __param(5, Inject(TransactionHost)),
1061
+ __param(6, Inject(CacheService))
1024
1062
  ], AttachmentsService);
1025
1063
  export { AttachmentsService };
1026
1064
  /**
@@ -0,0 +1,33 @@
1
+ import type { MediaBytes } from "../runtime/context/build.js";
2
+ /**
3
+ * The longest edge, in pixels, of an image sent to a model. Providers scale larger images down on
4
+ * their side anyway (to roughly 1.5k-2k pixels), so the extra pixels only cost upload time on every
5
+ * request that carries the image again.
6
+ */
7
+ export declare const MODEL_IMAGE_MAX_EDGE = 2048;
8
+ /** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
9
+ export declare const MODEL_IMAGE_KEEP_BYTES = 1048576;
10
+ /**
11
+ * The copy of an image a model request carries. Images over {@link MODEL_IMAGE_KEEP_BYTES} or
12
+ * larger than {@link MODEL_IMAGE_MAX_EDGE} on an edge are scaled to fit that edge (never enlarged)
13
+ * and re-encoded: JPEG when every pixel is opaque, WebP when some are transparent, so transparency
14
+ * stays visible. The result is a pure function of the stored bytes, so rebuilding a recorded request
15
+ * gives the same copy. The stored attachment is never changed. Bytes that fail to decode, and a
16
+ * re-encoded copy no smaller than the original, are returned unchanged.
17
+ */
18
+ export declare function fitImageForModel(media: MediaBytes): Promise<MediaBytes>;
19
+ /** How long a model-sized copy stays cached (the steps of a conversation reuse it). */
20
+ export declare const MODEL_IMAGE_CACHE_SECONDS = 3600;
21
+ /**
22
+ * The cache key of an attachment's model-sized copy: its id plus its recorded etag (or size), with
23
+ * the scaling version, so a changed rule or object never serves an old copy.
24
+ */
25
+ export declare const modelImageKey: (orgId: string, row: {
26
+ id: string;
27
+ etag: string | null;
28
+ size: number | string;
29
+ }) => string;
30
+ /** The cached form of a copy: its media type, a newline, then the bytes in base64. */
31
+ export declare function serializeModelImage(media: MediaBytes): string;
32
+ /** A cached copy read back, or null on a miss or a value that is not one. */
33
+ export declare function parseModelImage(raw: string | undefined): MediaBytes | null;
@@ -0,0 +1,71 @@
1
+ import sharp from "sharp";
2
+ /**
3
+ * The longest edge, in pixels, of an image sent to a model. Providers scale larger images down on
4
+ * their side anyway (to roughly 1.5k-2k pixels), so the extra pixels only cost upload time on every
5
+ * request that carries the image again.
6
+ */
7
+ export const MODEL_IMAGE_MAX_EDGE = 2048;
8
+ /** An image at most this large and within {@link MODEL_IMAGE_MAX_EDGE} is sent unchanged. */
9
+ export const MODEL_IMAGE_KEEP_BYTES = 1_048_576;
10
+ /** Quality of the re-encoded copy (JPEG, or WebP for an image with transparent pixels). */
11
+ const QUALITY = 85;
12
+ /** Types {@link fitImageForModel} re-encodes; others (GIF, which may be animated) pass through. */
13
+ const RESIZABLE = new Set(["image/png", "image/jpeg", "image/webp"]);
14
+ /**
15
+ * The copy of an image a model request carries. Images over {@link MODEL_IMAGE_KEEP_BYTES} or
16
+ * larger than {@link MODEL_IMAGE_MAX_EDGE} on an edge are scaled to fit that edge (never enlarged)
17
+ * and re-encoded: JPEG when every pixel is opaque, WebP when some are transparent, so transparency
18
+ * stays visible. The result is a pure function of the stored bytes, so rebuilding a recorded request
19
+ * gives the same copy. The stored attachment is never changed. Bytes that fail to decode, and a
20
+ * re-encoded copy no smaller than the original, are returned unchanged.
21
+ */
22
+ export async function fitImageForModel(media) {
23
+ if (!RESIZABLE.has(media.mediaType))
24
+ return media;
25
+ try {
26
+ const image = sharp(media.data, { failOn: "error" });
27
+ const meta = await image.metadata();
28
+ if (media.data.byteLength <= MODEL_IMAGE_KEEP_BYTES &&
29
+ Math.max(meta.width, meta.height) <= MODEL_IMAGE_MAX_EDGE) {
30
+ return media;
31
+ }
32
+ const opaque = !meta.hasAlpha || (await image.stats()).isOpaque;
33
+ const resized = image.autoOrient().resize({
34
+ width: MODEL_IMAGE_MAX_EDGE,
35
+ height: MODEL_IMAGE_MAX_EDGE,
36
+ fit: "inside",
37
+ withoutEnlargement: true,
38
+ });
39
+ const data = opaque
40
+ ? await resized.flatten({ background: "#ffffff" }).jpeg({ quality: QUALITY }).toBuffer()
41
+ : await resized.webp({ quality: QUALITY }).toBuffer();
42
+ if (data.byteLength >= media.data.byteLength)
43
+ return media;
44
+ return { mediaType: opaque ? "image/jpeg" : "image/webp", data: new Uint8Array(data) };
45
+ }
46
+ catch {
47
+ return media;
48
+ }
49
+ }
50
+ /** How long a model-sized copy stays cached (the steps of a conversation reuse it). */
51
+ export const MODEL_IMAGE_CACHE_SECONDS = 3600;
52
+ /**
53
+ * The cache key of an attachment's model-sized copy: its id plus its recorded etag (or size), with
54
+ * the scaling version, so a changed rule or object never serves an old copy.
55
+ */
56
+ export const modelImageKey = (orgId, row) => `model_image:v1:${orgId}:${row.id}:${row.etag ?? `size-${row.size}`}`;
57
+ /** The cached form of a copy: its media type, a newline, then the bytes in base64. */
58
+ export function serializeModelImage(media) {
59
+ return `${media.mediaType}\n${Buffer.from(media.data).toString("base64")}`;
60
+ }
61
+ /** A cached copy read back, or null on a miss or a value that is not one. */
62
+ export function parseModelImage(raw) {
63
+ if (raw === undefined)
64
+ return null;
65
+ const nl = raw.indexOf("\n");
66
+ const mediaType = raw.slice(0, nl);
67
+ if (nl < 0 || !RESIZABLE.has(mediaType))
68
+ return null;
69
+ const data = Buffer.from(raw.slice(nl + 1), "base64");
70
+ return data.byteLength === 0 ? null : { mediaType, data: new Uint8Array(data) };
71
+ }
@@ -1419,6 +1419,15 @@ export interface ScheduledTasksTable {
1419
1419
  }
1420
1420
  /** Why a file share was revoked (0161). */
1421
1421
  export type FileShareRevokeReason = "creator" | "admin" | "conversation_deleted" | "member_offboarded" | "creator_lost_access";
1422
+ /** 0164: the platform icon of one purpose (mobile layout spec §10.2.1); no row: the default. */
1423
+ export interface PlatformIconsTable {
1424
+ purpose: "app" | "maskable" | "favicon";
1425
+ /** Relative to the kernel's `deployment/` prefix: `platform-icons/<purpose>-<sha256>.<ext>`. */
1426
+ object_key: string;
1427
+ sha256: string;
1428
+ content_type: string;
1429
+ updated_at: Ts;
1430
+ }
1422
1431
  /**
1423
1432
  * 0161: a link to a frozen snapshot of one conversation file (file sharing spec §1). The row stays
1424
1433
  * after a revoke or expiry; `object_key` is null once the snapshot is freed.
@@ -1653,6 +1662,7 @@ export interface KernelDatabase {
1653
1662
  scheduled_task_runs: ScheduledTaskRunsTable;
1654
1663
  scheduled_task_grants: ScheduledTaskGrantsTable;
1655
1664
  file_shares: FileSharesTable;
1665
+ platform_icons: PlatformIconsTable;
1656
1666
  skills: SkillsTable;
1657
1667
  skill_versions: SkillVersionsTable;
1658
1668
  skill_change_requests: SkillChangeRequestsTable;
package/dist/errors.d.ts CHANGED
@@ -28,6 +28,15 @@ export declare const ERROR_CODES: {
28
28
  readonly "auth.rate_limited": 429;
29
29
  readonly "auth.session_required": 403;
30
30
  readonly "auth.password_change_required": 403;
31
+ /** Native-app sign-in: the redirect URI is not one of `auth.appRedirectUris` (exact match). */
32
+ readonly "app_auth.redirect_uri_invalid": 400;
33
+ /**
34
+ * Native-app sign-in: the code is unknown, used, expired, for another redirect URI or verifier,
35
+ * or its account or browser session is no longer valid; start the sign-in again.
36
+ */
37
+ readonly "app_auth.code_invalid": 400;
38
+ /** Native-app sign-in needs `http.publicUrl` (the issuer the app checks). */
39
+ readonly "app_auth.unavailable": 503;
31
40
  readonly "token.not_found": 404;
32
41
  readonly "org.not_found": 404;
33
42
  readonly "org.creation_disabled": 403;
@@ -167,6 +176,16 @@ export declare const ERROR_CODES: {
167
176
  * a removed theme's versions are still served.
168
177
  */
169
178
  readonly "theme.not_found": 404;
179
+ /** A platform icon upload of the wrong type for its purpose (mobile layout spec §10.2.1). */
180
+ readonly "platform_icon.invalid_type": 400;
181
+ /** A PNG platform icon that is not exactly 512 × 512 (§10.2.1). */
182
+ readonly "platform_icon.invalid_size": 400;
183
+ /** A platform icon file over 1 MiB (§10.2.1). */
184
+ readonly "platform_icon.too_large": 413;
185
+ /** No object store to keep or serve the platform icon in (§10.2.1). */
186
+ readonly "platform_icon.storage_unavailable": 503;
187
+ /** No platform icon of that purpose is uploaded, or the URL's hash is not the current one. */
188
+ readonly "platform_icon.not_found": 404;
170
189
  /**
171
190
  * An `extension.client` section whose extension manifest lacks `permissions.client: true`
172
191
  * (client extensions spec §5.4: client code is always declared and reviewed).
package/dist/errors.js CHANGED
@@ -28,6 +28,15 @@ export const ERROR_CODES = {
28
28
  "auth.rate_limited": 429,
29
29
  "auth.session_required": 403,
30
30
  "auth.password_change_required": 403,
31
+ /** Native-app sign-in: the redirect URI is not one of `auth.appRedirectUris` (exact match). */
32
+ "app_auth.redirect_uri_invalid": 400,
33
+ /**
34
+ * Native-app sign-in: the code is unknown, used, expired, for another redirect URI or verifier,
35
+ * or its account or browser session is no longer valid; start the sign-in again.
36
+ */
37
+ "app_auth.code_invalid": 400,
38
+ /** Native-app sign-in needs `http.publicUrl` (the issuer the app checks). */
39
+ "app_auth.unavailable": 503,
31
40
  "token.not_found": 404,
32
41
  "org.not_found": 404,
33
42
  "org.creation_disabled": 403,
@@ -167,6 +176,16 @@ export const ERROR_CODES = {
167
176
  * a removed theme's versions are still served.
168
177
  */
169
178
  "theme.not_found": 404,
179
+ /** A platform icon upload of the wrong type for its purpose (mobile layout spec §10.2.1). */
180
+ "platform_icon.invalid_type": 400,
181
+ /** A PNG platform icon that is not exactly 512 × 512 (§10.2.1). */
182
+ "platform_icon.invalid_size": 400,
183
+ /** A platform icon file over 1 MiB (§10.2.1). */
184
+ "platform_icon.too_large": 413,
185
+ /** No object store to keep or serve the platform icon in (§10.2.1). */
186
+ "platform_icon.storage_unavailable": 503,
187
+ /** No platform icon of that purpose is uploaded, or the URL's hash is not the current one. */
188
+ "platform_icon.not_found": 404,
170
189
  /**
171
190
  * An `extension.client` section whose extension manifest lacks `permissions.client: true`
172
191
  * (client extensions spec §5.4: client code is always declared and reviewed).
@@ -54,6 +54,7 @@ import { FilePreviewersController } from "../files/previewers.controller.js";
54
54
  import { GitModule } from "../git/git.module.js";
55
55
  import { HtmlModule } from "../html/html.module.js";
56
56
  import { HtmlDocumentController } from "../html/html-document.controller.js";
57
+ import { AppAuthController } from "../identity/app-auth.controller.js";
57
58
  import { AuthController } from "../identity/auth.controller.js";
58
59
  import { AuthGuard } from "../identity/auth.guard.js";
59
60
  import { IdentityModule } from "../identity/identity.module.js";
@@ -89,6 +90,8 @@ import { InvocableSkillsController } from "../skills/invocable.controller.js";
89
90
  import { SkillsController } from "../skills/skills.controller.js";
90
91
  import { SkillsModule } from "../skills/skills.module.js";
91
92
  import { StorageModule } from "../storage/storage.module.js";
93
+ import { PlatformIconController } from "../themes/platform-icon.controller.js";
94
+ import { PlatformIconPublicController } from "../themes/platform-icon-public.controller.js";
92
95
  import { OrgThemesController } from "../themes/themes.controller.js";
93
96
  import { ThemesModule } from "../themes/themes.module.js";
94
97
  import { PlatformThemeController, ThemeDeliveryController, } from "../themes/themes-public.controller.js";
@@ -103,9 +106,12 @@ import { AdminUiController } from "../ui/admin-ui.controller.js";
103
106
  import { SlotsController } from "../ui/slots.controller.js";
104
107
  import { UiModule } from "../ui/ui.module.js";
105
108
  import { UiController } from "../ui/views.controller.js";
109
+ import { MetaController } from "./meta.controller.js";
106
110
  /** Every controller of the kernel API. */
107
111
  const CONTROLLERS = [
108
112
  AuthController,
113
+ AppAuthController,
114
+ MetaController,
109
115
  MeController,
110
116
  InitialPasswordsController,
111
117
  OrgsController,
@@ -184,6 +190,8 @@ const CONTROLLERS = [
184
190
  OrgThemesController,
185
191
  ThemeDeliveryController,
186
192
  PlatformThemeController,
193
+ PlatformIconController,
194
+ PlatformIconPublicController,
187
195
  DeviceAuthController,
188
196
  ClientDeliveryController,
189
197
  OrgClientController,
package/dist/http/app.js CHANGED
@@ -77,6 +77,12 @@ const LARGE_BODY_ROUTES = new Set([
77
77
  "/api/v1/orgs/:orgId/connectors/preview",
78
78
  ]);
79
79
  const LARGE_BODY_LIMIT = 6 * 1024 * 1024;
80
+ /**
81
+ * The platform icon upload (mobile layout spec §10.2.1): a file of up to 1 MiB as JSON base64 is
82
+ * about 1.4 MB; 2 MiB lets a file somewhat over the limit reach `platform_icon.too_large`.
83
+ */
84
+ const PLATFORM_ICON_ROUTE = "/api/v1/admin/platform/icons/:purpose";
85
+ const PLATFORM_ICON_BODY_LIMIT = 2 * 1024 * 1024;
80
86
  /**
81
87
  * Sets up the Fastify side of the kernel's Nest application (built by `buildKernelApp` from
82
88
  * `KernelModule`, which provides the health endpoints and the API) without connecting to anything,
@@ -107,6 +113,9 @@ export async function createHttpApp(opts, app) {
107
113
  if (LARGE_BODY_ROUTES.has(r.url) && [r.method].flat().includes("POST")) {
108
114
  r.bodyLimit = LARGE_BODY_LIMIT;
109
115
  }
116
+ if (r.url === PLATFORM_ICON_ROUTE && [r.method].flat().includes("PUT")) {
117
+ r.bodyLimit = PLATFORM_ICON_BODY_LIMIT;
118
+ }
110
119
  const upload = PACKAGE_UPLOAD_ROUTES.has(r.url) || ORG_PACKAGE_UPLOAD_ROUTES.has(r.url);
111
120
  if (upload && opts.packageMaxBytes !== undefined) {
112
121
  r.bodyLimit = opts.packageMaxBytes + 1;
@@ -0,0 +1,33 @@
1
+ import { z } from "zod";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { PlatformIconService } from "../themes/platform-icon.service.js";
4
+ /** Pre-sign-in discovery document native clients and the PWA manifest read. */
5
+ export declare const MetaResponseSchema: z.ZodObject<{
6
+ name: z.ZodNullable<z.ZodString>;
7
+ icon: z.ZodNullable<z.ZodString>;
8
+ icons: z.ZodObject<{
9
+ app: z.ZodNullable<z.ZodString>;
10
+ maskable: z.ZodNullable<z.ZodString>;
11
+ favicon: z.ZodNullable<z.ZodString>;
12
+ }, z.core.$strip>;
13
+ protocols: z.ZodObject<{
14
+ device: z.ZodObject<{
15
+ min: z.ZodNumber;
16
+ max: z.ZodNumber;
17
+ }, z.core.$strip>;
18
+ }, z.core.$strip>;
19
+ features: z.ZodObject<{
20
+ localDevices: z.ZodBoolean;
21
+ appSignIn: z.ZodBoolean;
22
+ }, z.core.$strip>;
23
+ }, z.core.$strip>;
24
+ export type MetaResponse = z.infer<typeof MetaResponseSchema>;
25
+ /** `GET /api/v1/meta`: public, never cached, reveals only what a client needs before signing in. */
26
+ export declare class MetaController {
27
+ private readonly config;
28
+ private readonly icons;
29
+ constructor(config: KernelConfigService, icons: PlatformIconService);
30
+ meta(): Promise<MetaResponse>;
31
+ /** A customised platform icon's versioned URL (the one the manifest uses); null for the default. */
32
+ private iconUrl;
33
+ }
@@ -0,0 +1,72 @@
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 { DEVICE_PROTOCOL_VERSION } from "@capybara-hq/plugin-sdk";
11
+ import { Controller, Get, Header, Inject } from "@nestjs/common";
12
+ import { z } from "zod";
13
+ import { Public } from "../identity/principal.js";
14
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
+ import { PlatformIconService } from "../themes/platform-icon.service.js";
16
+ /** Pre-sign-in discovery document native clients and the PWA manifest read. */
17
+ export const MetaResponseSchema = z.object({
18
+ name: z.string().nullable(),
19
+ icon: z.string().nullable(),
20
+ icons: z.object({
21
+ app: z.string().nullable(),
22
+ maskable: z.string().nullable(),
23
+ favicon: z.string().nullable(),
24
+ }),
25
+ protocols: z.object({
26
+ device: z.object({ min: z.number().int(), max: z.number().int() }),
27
+ }),
28
+ features: z.object({ localDevices: z.boolean(), appSignIn: z.boolean() }),
29
+ });
30
+ /** `GET /api/v1/meta`: public, never cached, reveals only what a client needs before signing in. */
31
+ let MetaController = class MetaController {
32
+ config;
33
+ icons;
34
+ constructor(config, icons) {
35
+ this.config = config;
36
+ this.icons = icons;
37
+ }
38
+ async meta() {
39
+ const config = this.config.get();
40
+ const [app, maskable, favicon] = await Promise.all([
41
+ this.iconUrl("app"),
42
+ this.iconUrl("maskable"),
43
+ this.iconUrl("favicon"),
44
+ ]);
45
+ return {
46
+ name: config.platform.name ?? null,
47
+ icon: app,
48
+ icons: { app, maskable, favicon },
49
+ protocols: { device: { min: DEVICE_PROTOCOL_VERSION, max: DEVICE_PROTOCOL_VERSION } },
50
+ features: {
51
+ localDevices: true,
52
+ // The authorize route answers app_auth.unavailable without http.publicUrl.
53
+ appSignIn: Boolean(config.http.publicUrl),
54
+ },
55
+ };
56
+ }
57
+ /** A customised platform icon's versioned URL (the one the manifest uses); null for the default. */
58
+ async iconUrl(purpose) {
59
+ return (await this.icons.current(purpose))?.url ?? null;
60
+ }
61
+ };
62
+ __decorate([
63
+ Public(),
64
+ Get(),
65
+ Header("cache-control", "no-store")
66
+ ], MetaController.prototype, "meta", null);
67
+ MetaController = __decorate([
68
+ Controller("api/v1/meta"),
69
+ __param(0, Inject(KernelConfigService)),
70
+ __param(1, Inject(PlatformIconService))
71
+ ], MetaController);
72
+ export { MetaController };
@@ -0,0 +1,25 @@
1
+ import type { FastifyReply, FastifyRequest } from "fastify";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import type { Account } from "./accounts.js";
4
+ import { AppAuthService } from "./app-auth.js";
5
+ import { type AppAuthorizeBody, type AppTokenBody } from "./app-auth.schemas.js";
6
+ import { type Principal } from "./principal.js";
7
+ /**
8
+ * Native-app sign-in (`/api/v1/app-auth`, desktop client spec §6.5; RFC 8252 with PKCE):
9
+ * - `POST /authorize` (web session only, CSRF header): the person's consent on the page
10
+ * `/apps/authorize` → `{ redirect }` with `code`, `state` and `iss`, or `error=access_denied`
11
+ * with `deny: true`; an unlisted redirect URI is `app_auth.redirect_uri_invalid`;
12
+ * - `POST /token` (public, CSRF header, `app-auth-token-ip`): the app exchanges the code with
13
+ * its verifier → `{ account }` and the session cookies, or `app_auth.code_invalid`.
14
+ */
15
+ export declare class AppAuthController {
16
+ private readonly auth;
17
+ private readonly config;
18
+ constructor(auth: AppAuthService, config: KernelConfigService);
19
+ authorize(principal: Principal, body: AppAuthorizeBody): Promise<{
20
+ redirect: string;
21
+ }>;
22
+ token(body: AppTokenBody, req: FastifyRequest, reply: FastifyReply): Promise<{
23
+ account: Account;
24
+ }>;
25
+ }