@capybara-hq/kernel 0.1.0-rc.53 → 0.1.0-rc.55

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 (190) hide show
  1. package/dist/admin/admin.schemas.d.ts +11 -1
  2. package/dist/catalog/catalog.module.js +1 -1
  3. package/dist/catalog/marketplaces.service.d.ts +1 -1
  4. package/dist/catalog/requests.service.d.ts +5 -5
  5. package/dist/catalog/requests.service.js +9 -9
  6. package/dist/channels/cards.d.ts +4 -3
  7. package/dist/channels/cards.js +25 -16
  8. package/dist/channels/phrases.d.ts +15 -4
  9. package/dist/channels/phrases.js +15 -1
  10. package/dist/config/load.d.ts +26 -7
  11. package/dist/config/load.js +60 -9
  12. package/dist/config/permission-migration.d.ts +17 -9
  13. package/dist/config/permission-migration.js +60 -9
  14. package/dist/config/schema.d.ts +15 -1
  15. package/dist/config/schema.js +66 -11
  16. package/dist/conversations/events.d.ts +247 -5
  17. package/dist/conversations/events.js +127 -16
  18. package/dist/conversations/permission-profiles.controller.d.ts +12 -2
  19. package/dist/conversations/permission-profiles.service.d.ts +12 -2
  20. package/dist/conversations/permission-profiles.service.js +11 -4
  21. package/dist/db/kernel-schema.d.ts +18 -2
  22. package/dist/devices/device-projects.service.d.ts +1 -1
  23. package/dist/devices/device-projects.service.js +6 -6
  24. package/dist/devices/devices.controller.d.ts +10 -8
  25. package/dist/devices/devices.controller.js +14 -18
  26. package/dist/devices/devices.schemas.d.ts +5 -5
  27. package/dist/devices/devices.schemas.js +5 -5
  28. package/dist/devices/devices.service.d.ts +188 -175
  29. package/dist/devices/devices.service.js +284 -292
  30. package/dist/devices/dto.d.ts +43 -23
  31. package/dist/devices/dto.js +45 -49
  32. package/dist/devices/project-rules.d.ts +0 -10
  33. package/dist/devices/project-rules.js +0 -5
  34. package/dist/errors.d.ts +43 -19
  35. package/dist/errors.js +43 -19
  36. package/dist/evals/reconstruct.d.ts +12 -3
  37. package/dist/evals/reconstruct.js +10 -6
  38. package/dist/evals/recorded-permission-context.d.ts +6 -4
  39. package/dist/evals/recorded-permission-context.js +15 -9
  40. package/dist/evals/run-replay.d.ts +6 -1
  41. package/dist/evals/run-replay.js +7 -2
  42. package/dist/evals/worker.js +3 -1
  43. package/dist/http/api.module.js +8 -0
  44. package/dist/http/app.js +9 -0
  45. package/dist/http/meta.controller.d.ts +33 -0
  46. package/dist/http/meta.controller.js +72 -0
  47. package/dist/identity/app-auth.controller.d.ts +25 -0
  48. package/dist/identity/app-auth.controller.js +64 -0
  49. package/dist/identity/app-auth.d.ts +66 -0
  50. package/dist/identity/app-auth.js +203 -0
  51. package/dist/identity/app-auth.schemas.d.ts +47 -0
  52. package/dist/identity/app-auth.schemas.js +43 -0
  53. package/dist/identity/identity.module.d.ts +1 -1
  54. package/dist/identity/identity.module.js +4 -1
  55. package/dist/identity/settings.d.ts +45 -18
  56. package/dist/identity/settings.js +151 -51
  57. package/dist/infra/config/kernel-config.service.d.ts +1 -1
  58. package/dist/infra/config/kernel-config.service.js +19 -5
  59. package/dist/infra/outbox/registry.d.ts +14 -0
  60. package/dist/infra/outbox/registry.js +15 -0
  61. package/dist/infra/throttler/named-throttlers.d.ts +3 -2
  62. package/dist/infra/throttler/named-throttlers.js +14 -2
  63. package/dist/local-devices/device-auth.controller.d.ts +1 -1
  64. package/dist/local-devices/device-auth.controller.js +1 -1
  65. package/dist/local-devices/device-auth.d.ts +4 -4
  66. package/dist/local-devices/device-auth.js +1 -1
  67. package/dist/local-devices/device-policy.service.d.ts +18 -9
  68. package/dist/local-devices/device-policy.service.js +21 -61
  69. package/dist/local-devices/device-routes.d.ts +3 -1
  70. package/dist/local-devices/device-routes.js +15 -4
  71. package/dist/local-devices/instance-bindings.js +5 -2
  72. package/dist/local-devices/local-device-gateway.d.ts +2 -2
  73. package/dist/local-devices/local-device-gateway.js +3 -3
  74. package/dist/local-devices/local-device-provider.d.ts +4 -4
  75. package/dist/local-devices/local-device-provider.js +23 -9
  76. package/dist/local-devices/local-devices.module.d.ts +1 -1
  77. package/dist/local-devices/local-devices.module.js +1 -1
  78. package/dist/local-devices/machines.d.ts +40 -16
  79. package/dist/local-devices/machines.js +89 -61
  80. package/dist/local-devices/owner-report.d.ts +16 -14
  81. package/dist/local-devices/owner-report.js +24 -30
  82. package/dist/local-devices/owner-reports.js +26 -8
  83. package/dist/local-devices/policy-summary.d.ts +25 -44
  84. package/dist/local-devices/policy-summary.js +26 -71
  85. package/dist/local-devices/relay.d.ts +6 -6
  86. package/dist/local-devices/relay.js +10 -8
  87. package/dist/net/public-address.d.ts +1 -1
  88. package/dist/net/public-address.js +5 -2
  89. package/dist/orgs/device-network-setting.d.ts +82 -0
  90. package/dist/orgs/device-network-setting.js +142 -0
  91. package/dist/orgs/settings.service.d.ts +103 -66
  92. package/dist/orgs/settings.service.js +201 -137
  93. package/dist/overrides.d.ts +5 -1
  94. package/dist/overrides.js +2 -0
  95. package/dist/platform/exclusions.js +24 -1
  96. package/dist/platform/operation.js +2 -2
  97. package/dist/platform/ops/admin.ops.js +20 -11
  98. package/dist/platform/ops/devices.ops.js +70 -5
  99. package/dist/platform/ops/org-settings.ops.js +10 -6
  100. package/dist/platform/ops/orgs.ops.js +2 -1
  101. package/dist/platform/ops/platform-icons.ops.d.ts +14 -0
  102. package/dist/platform/ops/platform-icons.ops.js +117 -0
  103. package/dist/platform/platform-ops.module.d.ts +2 -1
  104. package/dist/platform/platform-ops.module.js +3 -0
  105. package/dist/platform/route-schemas.js +3 -0
  106. package/dist/runtime/context/permission-profile.d.ts +17 -8
  107. package/dist/runtime/context/permission-profile.js +126 -45
  108. package/dist/runtime/maintenance.d.ts +5 -2
  109. package/dist/runtime/maintenance.js +15 -4
  110. package/dist/runtime/permission-context.service.d.ts +1 -1
  111. package/dist/runtime/permission-context.service.js +5 -3
  112. package/dist/runtime/project/knowledge.d.ts +5 -4
  113. package/dist/runtime/project/knowledge.js +2 -1
  114. package/dist/runtime/project/knowledge.service.js +16 -13
  115. package/dist/sandbox/cloud-permission-snapshot.js +22 -3
  116. package/dist/sandbox/device-sandbox-settings.d.ts +230 -0
  117. package/dist/sandbox/device-sandbox-settings.js +470 -0
  118. package/dist/sandbox/device-sandbox.d.ts +187 -0
  119. package/dist/sandbox/device-sandbox.js +236 -0
  120. package/dist/sandbox/held-operations.js +15 -7
  121. package/dist/sandbox/modes.d.ts +49 -24
  122. package/dist/sandbox/modes.js +27 -19
  123. package/dist/sandbox/operation-authority-types.d.ts +6 -5
  124. package/dist/sandbox/operation-authority-types.js +7 -8
  125. package/dist/sandbox/operation-authority.d.ts +23 -9
  126. package/dist/sandbox/operation-authority.js +179 -97
  127. package/dist/sandbox/permission-auto-grants.d.ts +42 -0
  128. package/dist/sandbox/permission-auto-grants.js +145 -0
  129. package/dist/sandbox/permission-call-grants.d.ts +12 -4
  130. package/dist/sandbox/permission-call-grants.js +84 -35
  131. package/dist/sandbox/permission-call-grants.module.js +10 -3
  132. package/dist/sandbox/permission-call-types.d.ts +39 -5
  133. package/dist/sandbox/permission-ceiling-writes.d.ts +29 -3
  134. package/dist/sandbox/permission-ceiling-writes.js +38 -4
  135. package/dist/sandbox/permission-config-publication.d.ts +44 -2
  136. package/dist/sandbox/permission-config-publication.js +230 -59
  137. package/dist/sandbox/permission-context-types.d.ts +2 -2
  138. package/dist/sandbox/permission-facts.d.ts +144 -15
  139. package/dist/sandbox/permission-facts.js +258 -70
  140. package/dist/sandbox/permission-runtime-reports.d.ts +5 -4
  141. package/dist/sandbox/permission-runtime-reports.js +19 -29
  142. package/dist/sandbox/review/classifier.d.ts +8 -0
  143. package/dist/sandbox/review/classifier.js +10 -0
  144. package/dist/sandbox/review/permission-candidate.d.ts +69 -5
  145. package/dist/sandbox/review/permission-candidate.js +153 -30
  146. package/dist/sandbox/review/review.service.d.ts +19 -3
  147. package/dist/sandbox/review/review.service.js +59 -11
  148. package/dist/sandbox/review/rules.js +23 -3
  149. package/dist/sandbox/sandbox.service.d.ts +29 -11
  150. package/dist/sandbox/sandbox.service.js +51 -26
  151. package/dist/skills/invoke.js +3 -2
  152. package/dist/themes/platform-icon-objects.d.ts +51 -0
  153. package/dist/themes/platform-icon-objects.js +113 -0
  154. package/dist/themes/platform-icon-public.controller.d.ts +17 -0
  155. package/dist/themes/platform-icon-public.controller.js +58 -0
  156. package/dist/themes/platform-icon.controller.d.ts +22 -0
  157. package/dist/themes/platform-icon.controller.js +65 -0
  158. package/dist/themes/platform-icon.schemas.d.ts +48 -0
  159. package/dist/themes/platform-icon.schemas.js +53 -0
  160. package/dist/themes/platform-icon.service.d.ts +83 -0
  161. package/dist/themes/platform-icon.service.js +301 -0
  162. package/dist/themes/themes.module.d.ts +4 -1
  163. package/dist/themes/themes.module.js +9 -4
  164. package/dist/tools/approvals.service.d.ts +26 -116
  165. package/dist/tools/approvals.service.js +42 -346
  166. package/dist/tools/builtins/sandbox/bash.d.ts +16 -3
  167. package/dist/tools/builtins/sandbox/bash.js +80 -28
  168. package/dist/tools/builtins/sandbox/common.d.ts +39 -14
  169. package/dist/tools/builtins/sandbox/common.js +47 -24
  170. package/dist/tools/builtins/sandbox/deliver.js +7 -4
  171. package/dist/tools/builtins/skill-load.d.ts +2 -2
  172. package/dist/tools/builtins/skill-load.js +4 -3
  173. package/dist/tools/device-op-resolver.d.ts +4 -10
  174. package/dist/tools/device-op-resolver.js +8 -19
  175. package/dist/tools/network-asks.d.ts +52 -15
  176. package/dist/tools/network-asks.js +55 -25
  177. package/dist/tools/pipeline.d.ts +26 -14
  178. package/dist/tools/pipeline.js +144 -61
  179. package/dist/tools/registry.d.ts +6 -0
  180. package/dist/tools/tools.module.js +1 -1
  181. package/package.json +4 -4
  182. package/src/migrations/0164_platform_icons.sql +10 -0
  183. package/src/migrations/0165_device_network_columns.sql +50 -0
  184. package/src/migrations/0166_permission_grant_full_access.sql +17 -0
  185. package/src/migrations/0167_device_network_backfill.sql +32 -0
  186. package/src/migrations/0168_binding_installed_connection.sql +6 -0
  187. package/dist/orgs/cloud-network-setting.d.ts +0 -33
  188. package/dist/orgs/cloud-network-setting.js +0 -47
  189. package/dist/sandbox/platform-full-access.d.ts +0 -110
  190. package/dist/sandbox/platform-full-access.js +0 -198
@@ -48,9 +48,14 @@ export interface RunReplayResult {
48
48
  * reports `permission_profile_changed`.
49
49
  */
50
50
  permissionContextDrift?: true;
51
+ /**
52
+ * Set when an original request of the run rebuilds another device sandbox block than its
53
+ * recorded metadata names; the result reports `device_sandbox_changed`.
54
+ */
55
+ deviceSandboxDrift?: true;
51
56
  }
52
57
  /** 原运行(基线)的同形摘要。 */
53
- export type RunBaseline = Omit<RunReplayResult, "conversationId" | "outcome" | "unmatched" | "permissionContextDrift">;
58
+ export type RunBaseline = Omit<RunReplayResult, "conversationId" | "outcome" | "unmatched" | "permissionContextDrift" | "deviceSandboxDrift">;
54
59
  /** 测试钩子。 */
55
60
  export interface EvalReplayHooks {
56
61
  /** 种子已写入(评测对话已记到结果上)、loop 开始之前调用:抛错即模拟此时崩溃。 */
@@ -375,7 +375,7 @@ export async function replayRun(d, s, candidate, evalRunId, signal) {
375
375
  // recorded permission context (spec B4), both before anything is seeded so an invalid recording
376
376
  // fails as `eval.snapshot_invalid` without an eval conversation: the original-coordinate
377
377
  // diagnostics, and the recorded-only feeder (undefined for a recording without markers)
378
- const permissionContextDrift = recordedRunPermissionDrift(s);
378
+ const permissionDrift = recordedRunPermissionDrift(s);
379
379
  const permissionContext = recordedPermissionContext(s, eventLog, { conversationId, runId });
380
380
  // the recorded tool results (reviews validated here) are read before the seed too, so an
381
381
  // invalid recording leaves no eval conversation either
@@ -677,6 +677,11 @@ export async function replayRun(d, s, candidate, evalRunId, signal) {
677
677
  outcome: outcome.kind,
678
678
  ...summary,
679
679
  unmatched: pipeline.unmatched(),
680
- ...(permissionContextDrift && { permissionContextDrift: true }),
680
+ ...(permissionDrift.includes("permission_profile_changed") && {
681
+ permissionContextDrift: true,
682
+ }),
683
+ ...(permissionDrift.includes("device_sandbox_changed") && {
684
+ deviceSandboxDrift: true,
685
+ }),
681
686
  };
682
687
  }
@@ -692,11 +692,13 @@ let EvalWorker = class EvalWorker {
692
692
  return;
693
693
  const baseline = runBaseline(s);
694
694
  // in DRIFT_ORDER: subagent_changed, permission_profile_changed (a recorded permission
695
- // context the snapshot cannot reproduce), model_switched (the candidate replaced the person's
695
+ // context the snapshot cannot reproduce), device_sandbox_changed (another rebuilt device
696
+ // sandbox block than the recorded one), model_switched (the candidate replaced the person's
696
697
  // switch), then tool_unmatched
697
698
  const drift = [
698
699
  ...(subagentCaseChanged(s, resolved) ? ["subagent_changed"] : []),
699
700
  ...(out.permissionContextDrift ? ["permission_profile_changed"] : []),
701
+ ...(out.deviceSandboxDrift ? ["device_sandbox_changed"] : []),
700
702
  ...(resolved.overridesSwitch ? ["model_switched"] : []),
701
703
  ...(out.unmatched > 0 ? ["tool_unmatched"] : []),
702
704
  ];
@@ -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
+ }
@@ -0,0 +1,64 @@
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, HttpCode, Inject, Post, Req, Res } from "@nestjs/common";
11
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
12
+ import { Throttled } from "../infra/throttler/throttler.guard.js";
13
+ import { ZBody } from "../infra/validation/zod-params.js";
14
+ import { AppAuthService } from "./app-auth.js";
15
+ import { AppAuthorizeBodyDto, AppTokenBodyDto, } from "./app-auth.schemas.js";
16
+ import { clientMeta } from "./auth.controller.js";
17
+ import { setSessionCookies } from "./cookies.js";
18
+ import { CurrentPrincipal, Public, requireUser, SessionOnly } from "./principal.js";
19
+ /**
20
+ * Native-app sign-in (`/api/v1/app-auth`, desktop client spec §6.5; RFC 8252 with PKCE):
21
+ * - `POST /authorize` (web session only, CSRF header): the person's consent on the page
22
+ * `/apps/authorize` → `{ redirect }` with `code`, `state` and `iss`, or `error=access_denied`
23
+ * with `deny: true`; an unlisted redirect URI is `app_auth.redirect_uri_invalid`;
24
+ * - `POST /token` (public, CSRF header, `app-auth-token-ip`): the app exchanges the code with
25
+ * its verifier → `{ account }` and the session cookies, or `app_auth.code_invalid`.
26
+ */
27
+ let AppAuthController = class AppAuthController {
28
+ auth;
29
+ config;
30
+ constructor(auth, config) {
31
+ this.auth = auth;
32
+ this.config = config;
33
+ }
34
+ async authorize(principal, body) {
35
+ return this.auth.authorize(requireUser(principal), body);
36
+ }
37
+ async token(body, req, reply) {
38
+ const { account, session } = await this.auth.token(body, { ip: clientMeta(req).ip });
39
+ setSessionCookies(reply, session, this.config.get());
40
+ return { account };
41
+ }
42
+ };
43
+ __decorate([
44
+ Post("authorize"),
45
+ SessionOnly(),
46
+ HttpCode(200),
47
+ __param(0, CurrentPrincipal()),
48
+ __param(1, ZBody(AppAuthorizeBodyDto))
49
+ ], AppAuthController.prototype, "authorize", null);
50
+ __decorate([
51
+ Post("token"),
52
+ Public(),
53
+ HttpCode(200),
54
+ Throttled("app-auth-token-ip"),
55
+ __param(0, ZBody(AppTokenBodyDto)),
56
+ __param(1, Req()),
57
+ __param(2, Res({ passthrough: true }))
58
+ ], AppAuthController.prototype, "token", null);
59
+ AppAuthController = __decorate([
60
+ Controller("api/v1/app-auth"),
61
+ __param(0, Inject(AppAuthService)),
62
+ __param(1, Inject(KernelConfigService))
63
+ ], AppAuthController);
64
+ export { AppAuthController };
@@ -0,0 +1,66 @@
1
+ import type { Redis } from "ioredis";
2
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ import { type Account, AccountsService } from "./accounts.js";
6
+ import type { AppAuthorizeBody, AppTokenBody } from "./app-auth.schemas.js";
7
+ import type { UserPrincipal } from "./principal.js";
8
+ import { type IssuedSession, SessionService } from "./sessions.js";
9
+ /** How long a sign-in code lives, seconds (one use within this window). */
10
+ export declare const APP_AUTH_CODE_TTL_SECONDS = 60;
11
+ /** The stored grant of one code: `capk:app-auth-code:<sha256(code)>`. The code is never stored. */
12
+ export declare const appAuthCodeKey: (code: string) => string;
13
+ /** BASE64URL(SHA-256(verifier)): the PKCE `S256` challenge (RFC 7636 §4.2). */
14
+ export declare function s256(verifier: string): string;
15
+ /**
16
+ * `uri` with `params` appended to its query (values encoded; existing parameters kept). Allowed
17
+ * redirect URIs carry no fragment (the config refuses one).
18
+ */
19
+ export declare function buildRedirect(uri: string, params: Record<string, string>): string;
20
+ /** Whether `uri` is one of `allowed`, compared as exact strings (no prefix, no case folding). */
21
+ export declare function isAllowedRedirect(uri: string, allowed: readonly string[]): boolean;
22
+ /**
23
+ * Native-app sign-in (desktop client spec §6.5): the authorization code flow with PKCE for native
24
+ * apps (RFC 8252, RFC 7636). The signed-in person consents on the web (`authorize`), which issues
25
+ * a one-time code bound to the PKCE challenge, the redirect URI and the browser session; the app
26
+ * exchanges it (`token`) for an ordinary web session of its own. State lives only in Redis, under
27
+ * the code's hash with a 60 s TTL, so any replica can exchange it.
28
+ */
29
+ export declare class AppAuthService {
30
+ private readonly db;
31
+ readonly txHost: TransactionHost;
32
+ private readonly redis;
33
+ private readonly config;
34
+ private readonly sessions;
35
+ private readonly accounts;
36
+ constructor(db: KernelDb, txHost: TransactionHost, redis: Redis, config: Pick<KernelConfigService, "get">, sessions: Pick<SessionService, "create">, accounts: Pick<AccountsService, "get">);
37
+ /**
38
+ * The person's consent from the browser session `principal`: the redirect to hand to the app,
39
+ * with `code`, `state` and `iss`, or with `error=access_denied` (no code) when `deny`. An
40
+ * unlisted redirect URI is refused before anything is stored.
41
+ */
42
+ authorize(principal: UserPrincipal, body: AppAuthorizeBody): Promise<{
43
+ redirect: string;
44
+ }>;
45
+ /**
46
+ * The app's exchange: the code is taken from Redis with GETDEL before anything else (one use:
47
+ * a wrong verifier or redirect URI burns it too), then checked against `redirectUri` and
48
+ * `S256(codeVerifier)`; the session is created in {@link signIn}. Every failure is
49
+ * `app_auth.code_invalid`.
50
+ */
51
+ token(body: AppTokenBody, meta: {
52
+ ip: string;
53
+ }): Promise<{
54
+ account: Account;
55
+ session: IssuedSession;
56
+ }>;
57
+ /**
58
+ * Creates the app's session for a verified grant: the account must be active (its row is held
59
+ * `FOR SHARE`, so a concurrent disable waits for this commit and then revokes the new session
60
+ * too) and the consenting browser session still live. Audits `auth.app_signed_in`.
61
+ */
62
+ private signIn;
63
+ private recordAuthorized;
64
+ /** `iss`: `http.publicUrl` without a trailing slash, the origin the app checks (RFC 9207). */
65
+ private issuer;
66
+ }
@@ -0,0 +1,203 @@
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 { createHash, randomBytes, timingSafeEqual } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { ApiError } from "../errors.js";
14
+ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
+ import { KernelDb } from "../infra/database/kernel-db.js";
16
+ import { TransactionHost } from "../infra/database/transaction-host.js";
17
+ import { Transactional } from "../infra/database/transactional.decorator.js";
18
+ import { REDIS } from "../infra/tokens.js";
19
+ import { AccountsService } from "./accounts.js";
20
+ import { audit } from "./audit.js";
21
+ import { sha256Hex } from "./hash.js";
22
+ import { SessionService } from "./sessions.js";
23
+ /** How long a sign-in code lives, seconds (one use within this window). */
24
+ export const APP_AUTH_CODE_TTL_SECONDS = 60;
25
+ const CODE_PREFIX = "cap_ac_";
26
+ const CODE_RE = /^cap_ac_[A-Za-z0-9_-]{43}$/;
27
+ /** A PKCE code verifier (RFC 7636 §4.1): 43 to 128 unreserved characters. */
28
+ const VERIFIER_RE = /^[A-Za-z0-9._~-]{43,128}$/;
29
+ /** The stored grant of one code: `capk:app-auth-code:<sha256(code)>`. The code is never stored. */
30
+ export const appAuthCodeKey = (code) => `capk:app-auth-code:${sha256Hex(code)}`;
31
+ /** BASE64URL(SHA-256(verifier)): the PKCE `S256` challenge (RFC 7636 §4.2). */
32
+ export function s256(verifier) {
33
+ return createHash("sha256").update(verifier, "ascii").digest("base64url");
34
+ }
35
+ /**
36
+ * `uri` with `params` appended to its query (values encoded; existing parameters kept). Allowed
37
+ * redirect URIs carry no fragment (the config refuses one).
38
+ */
39
+ export function buildRedirect(uri, params) {
40
+ const query = new URLSearchParams(params).toString();
41
+ if (!uri.includes("?"))
42
+ return `${uri}?${query}`;
43
+ return uri.endsWith("?") || uri.endsWith("&") ? `${uri}${query}` : `${uri}&${query}`;
44
+ }
45
+ /** Whether `uri` is one of `allowed`, compared as exact strings (no prefix, no case folding). */
46
+ export function isAllowedRedirect(uri, allowed) {
47
+ return allowed.includes(uri);
48
+ }
49
+ /** The session user agent of an app session: `Capybara Desktop/<appVersion> (<name>)`. */
50
+ const appUserAgent = (g) => `Capybara Desktop/${g.appVersion} (${g.name})`;
51
+ const codeInvalid = () => new ApiError("app_auth.code_invalid", "The sign-in code is invalid, already used or expired; start the sign-in from the app again");
52
+ /**
53
+ * Native-app sign-in (desktop client spec §6.5): the authorization code flow with PKCE for native
54
+ * apps (RFC 8252, RFC 7636). The signed-in person consents on the web (`authorize`), which issues
55
+ * a one-time code bound to the PKCE challenge, the redirect URI and the browser session; the app
56
+ * exchanges it (`token`) for an ordinary web session of its own. State lives only in Redis, under
57
+ * the code's hash with a 60 s TTL, so any replica can exchange it.
58
+ */
59
+ let AppAuthService = class AppAuthService {
60
+ db;
61
+ txHost;
62
+ redis;
63
+ config;
64
+ sessions;
65
+ accounts;
66
+ constructor(db, txHost, redis, config, sessions, accounts) {
67
+ this.db = db;
68
+ this.txHost = txHost;
69
+ this.redis = redis;
70
+ this.config = config;
71
+ this.sessions = sessions;
72
+ this.accounts = accounts;
73
+ }
74
+ /**
75
+ * The person's consent from the browser session `principal`: the redirect to hand to the app,
76
+ * with `code`, `state` and `iss`, or with `error=access_denied` (no code) when `deny`. An
77
+ * unlisted redirect URI is refused before anything is stored.
78
+ */
79
+ async authorize(principal, body) {
80
+ if (principal.via !== "session") {
81
+ throw new ApiError("auth.session_required", "This endpoint requires a web session");
82
+ }
83
+ if (!isAllowedRedirect(body.redirectUri, this.config.get().auth.appRedirectUris)) {
84
+ throw new ApiError("app_auth.redirect_uri_invalid", "The redirect URI is not one this platform allows for apps (auth.appRedirectUris)");
85
+ }
86
+ const iss = this.issuer();
87
+ if (body.deny === true) {
88
+ return {
89
+ redirect: buildRedirect(body.redirectUri, {
90
+ error: "access_denied",
91
+ state: body.state,
92
+ iss,
93
+ }),
94
+ };
95
+ }
96
+ const code = CODE_PREFIX + randomBytes(32).toString("base64url");
97
+ const grant = {
98
+ accountId: principal.account.id,
99
+ sessionId: principal.sessionId,
100
+ client: body.client,
101
+ redirectUri: body.redirectUri,
102
+ codeChallenge: body.codeChallenge,
103
+ name: body.name,
104
+ appVersion: body.appVersion,
105
+ };
106
+ // a plain SET: 32 random bytes do not collide (and `kc-lock` keeps SET NX to LockService)
107
+ await this.redis.set(appAuthCodeKey(code), JSON.stringify(grant), "EX", APP_AUTH_CODE_TTL_SECONDS);
108
+ await this.recordAuthorized(principal.account.id, grant);
109
+ return { redirect: buildRedirect(body.redirectUri, { code, state: body.state, iss }) };
110
+ }
111
+ /**
112
+ * The app's exchange: the code is taken from Redis with GETDEL before anything else (one use:
113
+ * a wrong verifier or redirect URI burns it too), then checked against `redirectUri` and
114
+ * `S256(codeVerifier)`; the session is created in {@link signIn}. Every failure is
115
+ * `app_auth.code_invalid`.
116
+ */
117
+ async token(body, meta) {
118
+ if (!CODE_RE.test(body.code))
119
+ throw codeInvalid();
120
+ const stored = await this.redis.getdel(appAuthCodeKey(body.code));
121
+ if (stored === null)
122
+ throw codeInvalid();
123
+ const grant = JSON.parse(stored);
124
+ if (body.redirectUri !== grant.redirectUri)
125
+ throw codeInvalid();
126
+ if (!VERIFIER_RE.test(body.codeVerifier))
127
+ throw codeInvalid();
128
+ const got = Buffer.from(s256(body.codeVerifier), "ascii");
129
+ const want = Buffer.from(grant.codeChallenge, "ascii");
130
+ if (got.length !== want.length || !timingSafeEqual(got, want))
131
+ throw codeInvalid();
132
+ return this.signIn(grant, meta.ip);
133
+ }
134
+ /**
135
+ * Creates the app's session for a verified grant: the account must be active (its row is held
136
+ * `FOR SHARE`, so a concurrent disable waits for this commit and then revokes the new session
137
+ * too) and the consenting browser session still live. Audits `auth.app_signed_in`.
138
+ */
139
+ async signIn(grant, ip) {
140
+ const row = await this.db
141
+ .selectFrom("accounts")
142
+ .select("status")
143
+ .where("id", "=", grant.accountId)
144
+ .forShare()
145
+ .executeTakeFirst();
146
+ if (row?.status !== "active")
147
+ throw codeInvalid();
148
+ const consenting = await this.db
149
+ .selectFrom("sessions")
150
+ .select("id")
151
+ .where("id", "=", grant.sessionId)
152
+ .where("account_id", "=", grant.accountId)
153
+ .where("revoked_at", "is", null)
154
+ .where("expires_at", ">", sql `now()`)
155
+ .executeTakeFirst();
156
+ if (!consenting)
157
+ throw codeInvalid();
158
+ const account = await this.accounts.get(grant.accountId);
159
+ if (!account)
160
+ throw codeInvalid();
161
+ const session = await this.sessions.create(grant.accountId, {
162
+ userAgent: appUserAgent(grant),
163
+ ip,
164
+ });
165
+ await audit(this.db.db, {
166
+ actorAccountId: grant.accountId,
167
+ action: "auth.app_signed_in",
168
+ detail: { client: grant.client, name: grant.name, sessionId: session.sessionId },
169
+ });
170
+ return { account, session };
171
+ }
172
+ async recordAuthorized(accountId, grant) {
173
+ await audit(this.db.db, {
174
+ actorAccountId: accountId,
175
+ action: "auth.app_authorized",
176
+ detail: { client: grant.client, name: grant.name },
177
+ });
178
+ }
179
+ /** `iss`: `http.publicUrl` without a trailing slash, the origin the app checks (RFC 9207). */
180
+ issuer() {
181
+ const url = this.config.get().http.publicUrl;
182
+ if (!url) {
183
+ throw new ApiError("app_auth.unavailable", "Signing apps in needs http.publicUrl to be configured; ask the super admin");
184
+ }
185
+ return url.replace(/\/+$/, "");
186
+ }
187
+ };
188
+ __decorate([
189
+ Transactional()
190
+ ], AppAuthService.prototype, "signIn", null);
191
+ __decorate([
192
+ Transactional()
193
+ ], AppAuthService.prototype, "recordAuthorized", null);
194
+ AppAuthService = __decorate([
195
+ Injectable(),
196
+ __param(0, Inject(KernelDb)),
197
+ __param(1, Inject(TransactionHost)),
198
+ __param(2, Inject(REDIS)),
199
+ __param(3, Inject(KernelConfigService)),
200
+ __param(4, Inject(SessionService)),
201
+ __param(5, Inject(AccountsService))
202
+ ], AppAuthService);
203
+ export { AppAuthService };
@@ -0,0 +1,47 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * `POST /api/v1/app-auth/authorize` (desktop client spec §6.5): the person consents on the web to
4
+ * sign a native app in. `codeChallenge` is BASE64URL(SHA-256(verifier)), always 43 characters;
5
+ * only the `S256` method exists. `deny` answers the `error=access_denied` redirect instead.
6
+ */
7
+ export declare const AppAuthorizeBodySchema: z.ZodObject<{
8
+ client: z.ZodLiteral<"desktop">;
9
+ redirectUri: z.ZodString;
10
+ codeChallenge: z.ZodString;
11
+ codeChallengeMethod: z.ZodLiteral<"S256">;
12
+ state: z.ZodString;
13
+ name: z.ZodString;
14
+ appVersion: z.ZodString;
15
+ deny: z.ZodOptional<z.ZodBoolean>;
16
+ }, z.core.$strict>;
17
+ export type AppAuthorizeBody = z.infer<typeof AppAuthorizeBodySchema>;
18
+ declare const AppAuthorizeBodyDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
19
+ client: z.ZodLiteral<"desktop">;
20
+ redirectUri: z.ZodString;
21
+ codeChallenge: z.ZodString;
22
+ codeChallengeMethod: z.ZodLiteral<"S256">;
23
+ state: z.ZodString;
24
+ name: z.ZodString;
25
+ appVersion: z.ZodString;
26
+ deny: z.ZodOptional<z.ZodBoolean>;
27
+ }, z.core.$strict>>;
28
+ export declare class AppAuthorizeBodyDto extends AppAuthorizeBodyDto_base {
29
+ }
30
+ /**
31
+ * `POST /api/v1/app-auth/token`: the app exchanges the one-time code with its PKCE verifier. Only
32
+ * the shape is checked here; every content failure answers `app_auth.code_invalid` (the service).
33
+ */
34
+ export declare const AppTokenBodySchema: z.ZodObject<{
35
+ code: z.ZodString;
36
+ codeVerifier: z.ZodString;
37
+ redirectUri: z.ZodString;
38
+ }, z.core.$strict>;
39
+ export type AppTokenBody = z.infer<typeof AppTokenBodySchema>;
40
+ declare const AppTokenBodyDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
41
+ code: z.ZodString;
42
+ codeVerifier: z.ZodString;
43
+ redirectUri: z.ZodString;
44
+ }, z.core.$strict>>;
45
+ export declare class AppTokenBodyDto extends AppTokenBodyDto_base {
46
+ }
47
+ export {};