@capybara-hq/kernel 0.1.0-rc.53 → 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 (46) 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/db/kernel-schema.d.ts +10 -0
  5. package/dist/errors.d.ts +19 -0
  6. package/dist/errors.js +19 -0
  7. package/dist/http/api.module.js +8 -0
  8. package/dist/http/app.js +9 -0
  9. package/dist/http/meta.controller.d.ts +33 -0
  10. package/dist/http/meta.controller.js +72 -0
  11. package/dist/identity/app-auth.controller.d.ts +25 -0
  12. package/dist/identity/app-auth.controller.js +64 -0
  13. package/dist/identity/app-auth.d.ts +66 -0
  14. package/dist/identity/app-auth.js +203 -0
  15. package/dist/identity/app-auth.schemas.d.ts +47 -0
  16. package/dist/identity/app-auth.schemas.js +43 -0
  17. package/dist/identity/identity.module.d.ts +1 -1
  18. package/dist/identity/identity.module.js +4 -1
  19. package/dist/infra/config/kernel-config.service.js +2 -0
  20. package/dist/infra/outbox/registry.d.ts +14 -0
  21. package/dist/infra/outbox/registry.js +15 -0
  22. package/dist/infra/throttler/named-throttlers.d.ts +3 -2
  23. package/dist/infra/throttler/named-throttlers.js +14 -2
  24. package/dist/platform/exclusions.js +23 -0
  25. package/dist/platform/operation.js +1 -1
  26. package/dist/platform/ops/platform-icons.ops.d.ts +14 -0
  27. package/dist/platform/ops/platform-icons.ops.js +117 -0
  28. package/dist/platform/platform-ops.module.d.ts +2 -1
  29. package/dist/platform/platform-ops.module.js +3 -0
  30. package/dist/platform/route-schemas.js +3 -0
  31. package/dist/runtime/maintenance.d.ts +5 -2
  32. package/dist/runtime/maintenance.js +15 -4
  33. package/dist/themes/platform-icon-objects.d.ts +51 -0
  34. package/dist/themes/platform-icon-objects.js +113 -0
  35. package/dist/themes/platform-icon-public.controller.d.ts +17 -0
  36. package/dist/themes/platform-icon-public.controller.js +58 -0
  37. package/dist/themes/platform-icon.controller.d.ts +22 -0
  38. package/dist/themes/platform-icon.controller.js +65 -0
  39. package/dist/themes/platform-icon.schemas.d.ts +48 -0
  40. package/dist/themes/platform-icon.schemas.js +53 -0
  41. package/dist/themes/platform-icon.service.d.ts +83 -0
  42. package/dist/themes/platform-icon.service.js +301 -0
  43. package/dist/themes/themes.module.d.ts +4 -1
  44. package/dist/themes/themes.module.js +9 -4
  45. package/package.json +3 -3
  46. package/src/migrations/0164_platform_icons.sql +10 -0
@@ -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 {};
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
3
+ /** Text without control, format or unassigned characters (it lands in a user agent and the audit). */
4
+ const PRINTABLE_RE = /^[^\p{C}]+$/u;
5
+ const printable = (max) => z
6
+ .string()
7
+ .min(1)
8
+ .max(max)
9
+ .regex(PRINTABLE_RE, { message: "Must contain only printable characters" });
10
+ /**
11
+ * `POST /api/v1/app-auth/authorize` (desktop client spec §6.5): the person consents on the web to
12
+ * sign a native app in. `codeChallenge` is BASE64URL(SHA-256(verifier)), always 43 characters;
13
+ * only the `S256` method exists. `deny` answers the `error=access_denied` redirect instead.
14
+ */
15
+ export const AppAuthorizeBodySchema = z
16
+ .object({
17
+ client: z.literal("desktop"),
18
+ redirectUri: z.string().min(1).max(2048),
19
+ codeChallenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/, {
20
+ message: "Must be the base64url SHA-256 of the code verifier (43 characters)",
21
+ }),
22
+ codeChallengeMethod: z.literal("S256"),
23
+ state: printable(512),
24
+ name: printable(64),
25
+ appVersion: printable(32),
26
+ deny: z.boolean().optional(),
27
+ })
28
+ .strict();
29
+ export class AppAuthorizeBodyDto extends createZodDto(AppAuthorizeBodySchema, "AppAuthorizeBody") {
30
+ }
31
+ /**
32
+ * `POST /api/v1/app-auth/token`: the app exchanges the one-time code with its PKCE verifier. Only
33
+ * the shape is checked here; every content failure answers `app_auth.code_invalid` (the service).
34
+ */
35
+ export const AppTokenBodySchema = z
36
+ .object({
37
+ code: z.string().max(256),
38
+ codeVerifier: z.string().max(256),
39
+ redirectUri: z.string().max(2048),
40
+ })
41
+ .strict();
42
+ export class AppTokenBodyDto extends createZodDto(AppTokenBodySchema, "AppTokenBody") {
43
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Identity: accounts, sessions, API tokens, deployment settings and the super admin lock,
3
- * external identities with IM binding and third-party sign-in.
3
+ * external identities with IM binding and third-party sign-in, native-app sign-in.
4
4
  */
5
5
  export declare class IdentityModule {
6
6
  }
@@ -11,6 +11,7 @@ import { OrgLockModule } from "../orgs/org-lock.js";
11
11
  import { PermissionAuthorityModule } from "../sandbox/permission-authority.module.js";
12
12
  import { AccountsModule } from "./accounts.js";
13
13
  import { ApiTokenService } from "./api-tokens.js";
14
+ import { AppAuthService } from "./app-auth.js";
14
15
  import { IdentityBinding } from "./binding.js";
15
16
  import { ExternalIdentities } from "./external.js";
16
17
  import { ExternalIdentityLock } from "./external-identity-lock.js";
@@ -21,7 +22,7 @@ import { SsoFlow } from "./sso.js";
21
22
  import { SuperAdminLockModule } from "./super-admin.js";
22
23
  /**
23
24
  * Identity: accounts, sessions, API tokens, deployment settings and the super admin lock,
24
- * external identities with IM binding and third-party sign-in.
25
+ * external identities with IM binding and third-party sign-in, native-app sign-in.
25
26
  */
26
27
  let IdentityModule = class IdentityModule {
27
28
  };
@@ -44,6 +45,7 @@ IdentityModule = __decorate([
44
45
  IdentityBinding,
45
46
  SsoFlow,
46
47
  InitialPasswords,
48
+ AppAuthService,
47
49
  ],
48
50
  exports: [
49
51
  AccountsModule,
@@ -55,6 +57,7 @@ IdentityModule = __decorate([
55
57
  IdentityBinding,
56
58
  SsoFlow,
57
59
  InitialPasswords,
60
+ AppAuthService,
58
61
  ],
59
62
  })
60
63
  ], IdentityModule);
@@ -20,6 +20,8 @@ import { KERNEL_CONFIG_INPUT, KERNEL_LOGGER } from "../tokens.js";
20
20
  * takes effect" cannot happen.
21
21
  */
22
22
  const HOT_APPLIERS = {
23
+ // GET /api/v1/meta reads the platform name on every request.
24
+ "platform.name": () => { },
23
25
  "log.level": (k, v) => k.log.setLevel(String(v)),
24
26
  // The runtime reads the concurrency cap through the config service on every quota request.
25
27
  "runtime.orgConcurrency": () => { },
@@ -32,6 +32,20 @@ export declare const OUTBOX_JOBS: {
32
32
  readonly removeOnComplete: true;
33
33
  };
34
34
  };
35
+ readonly "platform-icon-delete": {
36
+ readonly queue: "cap-kernel-maintenance";
37
+ readonly idempotent: "Deletes one icon object only when the purpose's row does not name it, under the purpose's lock; deleting a missing object is a no-op";
38
+ readonly processedIn: "packages/kernel/src/runtime/maintenance.ts";
39
+ readonly opts: {
40
+ readonly attempts: 10;
41
+ readonly backoff: {
42
+ readonly type: "exponential";
43
+ readonly delay: 5000;
44
+ };
45
+ readonly removeOnComplete: true;
46
+ readonly removeOnFail: true;
47
+ };
48
+ };
35
49
  readonly "permission-approval-recheck": {
36
50
  readonly queue: "cap-kernel-maintenance";
37
51
  readonly idempotent: "Reads the current revision and resumes only waiting runs without another pending wait; queued runs are unchanged.";
@@ -29,6 +29,21 @@ export const OUTBOX_JOBS = {
29
29
  processedIn: "packages/kernel/src/runtime/maintenance.ts",
30
30
  opts: { attempts: 10, backoff: { type: "exponential", delay: 5000 }, removeOnComplete: true },
31
31
  },
32
+ // `themes/platform-icon-objects.ts` PLATFORM_ICON_DELETE_JOB: owed by an icon upload (its own
33
+ // object's delayed orphan check), a replace and a clear (the object the row stopped naming)
34
+ "platform-icon-delete": {
35
+ queue: "cap-kernel-maintenance",
36
+ idempotent: "Deletes one icon object only when the purpose's row does not name it, under the purpose's lock; deleting a missing object is a no-op",
37
+ processedIn: "packages/kernel/src/runtime/maintenance.ts",
38
+ // removed on failure too: the ids are content addressed, so a kept failed job would swallow a
39
+ // later owing of the same deletion
40
+ opts: {
41
+ attempts: 10,
42
+ backoff: { type: "exponential", delay: 5000 },
43
+ removeOnComplete: true,
44
+ removeOnFail: true,
45
+ },
46
+ },
32
47
  "permission-approval-recheck": {
33
48
  queue: "cap-kernel-maintenance",
34
49
  idempotent: "Reads the current revision and resumes only waiting runs without another pending wait; queued runs are unchanged.",
@@ -36,8 +36,9 @@ export interface NamedThrottler {
36
36
  *
37
37
  * `POST /api/v1/device/authorize` and `POST /api/v1/device/token` opt in to `device-authorize-ip`
38
38
  * and `device-token-ip` with `@Throttled` (every request counts; neither checks a guessable
39
- * credential: the device code is 32 random bytes). `POST …/guides/:guideId/checks/:checkId/run`
40
- * opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
39
+ * credential: the device code is 32 random bytes). `POST /api/v1/app-auth/token` opts in to
40
+ * `app-auth-token-ip` the same way (the one-time code is 32 random bytes).
41
+ * `POST …/guides/:guideId/checks/:checkId/run` opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
41
42
  *
42
43
  * `plugin-public-write` is not a Nest route limit: the plugin dispatch counts it for unsafe
43
44
  * methods on `public` extension routes (`PluginRouteAccess`).
@@ -37,8 +37,9 @@ const LOGIN_MSG = "Too many failed login attempts; try again later";
37
37
  *
38
38
  * `POST /api/v1/device/authorize` and `POST /api/v1/device/token` opt in to `device-authorize-ip`
39
39
  * and `device-token-ip` with `@Throttled` (every request counts; neither checks a guessable
40
- * credential: the device code is 32 random bytes). `POST …/guides/:guideId/checks/:checkId/run`
41
- * opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
40
+ * credential: the device code is 32 random bytes). `POST /api/v1/app-auth/token` opts in to
41
+ * `app-auth-token-ip` the same way (the one-time code is 32 random bytes).
42
+ * `POST …/guides/:guideId/checks/:checkId/run` opts in to `setup-check` (setup guides v2 §10.3: each run may call a third party).
42
43
  *
43
44
  * `plugin-public-write` is not a Nest route limit: the plugin dispatch counts it for unsafe
44
45
  * methods on `public` extension routes (`PluginRouteAccess`).
@@ -151,6 +152,17 @@ export const NAMED_THROTTLERS = [
151
152
  message: "Too many device sign-in polls; try again later",
152
153
  getTracker: ip,
153
154
  },
155
+ // native-app sign-in code exchanges per client address (@Throttled like device-token-ip): 60.
156
+ // The code is 32 random bytes and dies at its first try, so this only bounds the load
157
+ {
158
+ name: "app-auth-token-ip",
159
+ group: "app-auth-token",
160
+ onSuccess: "clear",
161
+ limit: 60,
162
+ ttl: CREDENTIAL_WINDOW_MS,
163
+ message: "Too many app sign-in attempts; try again later",
164
+ getTracker: ip,
165
+ },
154
166
  // user codes tried per signed-in person (guessing another machine's code): 10, refunded on success
155
167
  {
156
168
  name: "device-code-account",
@@ -66,6 +66,23 @@ export const PLATFORM_EXCLUSIONS = [
66
66
  category: "human-only",
67
67
  reason: "Fetches an extension package and returns its permission review; installing it means confirming those permissions, which only a person does (spec §6.4)",
68
68
  },
69
+ // meta
70
+ {
71
+ route: "GET /api/v1/meta",
72
+ category: "transport",
73
+ reason: "Pre-sign-in discovery for native clients: platform name, icon and protocol ranges",
74
+ },
75
+ // native-app sign-in (desktop client spec §6.5)
76
+ {
77
+ route: "POST /api/v1/app-auth/authorize",
78
+ category: "human-only",
79
+ reason: "A person consents in the browser to sign a native app in",
80
+ },
81
+ {
82
+ route: "POST /api/v1/app-auth/token",
83
+ category: "transport",
84
+ reason: "A native app exchanges a one-time sign-in code; nothing for an agent",
85
+ },
69
86
  // setup
70
87
  {
71
88
  route: "GET /api/v1/setup",
@@ -862,6 +879,12 @@ export const PLATFORM_EXCLUSIONS = [
862
879
  category: "transport",
863
880
  reason: "Serves a theme version's font and logo bytes to the browser",
864
881
  },
882
+ // the platform icon (mobile layout spec §10.2.1)
883
+ {
884
+ route: "GET /api/v1/platform/icon/:purpose",
885
+ category: "transport",
886
+ reason: "Public image delivery for the manifest and favicons",
887
+ },
865
888
  {
866
889
  route: "GET /api/v1/platform/theme",
867
890
  category: "transport",
@@ -57,7 +57,7 @@ export const PLATFORM_DOMAINS = [
57
57
  },
58
58
  {
59
59
  id: "admin",
60
- description: "The admin console (super admin): dashboard totals, deployment settings, the org's members, and the agents and connectors of the org (read, delete, disable or enable; other orgs' only in the console).",
60
+ description: "The admin console (super admin): dashboard totals, deployment settings, the platform icon, the org's members, and the agents and connectors of the org (read, delete, disable or enable; other orgs' only in the console).",
61
61
  },
62
62
  {
63
63
  id: "models",
@@ -0,0 +1,14 @@
1
+ import { type OnModuleInit } from "@nestjs/common";
2
+ import { PlatformIconService } from "../../themes/platform-icon.service.js";
3
+ import { PlatformOperations } from "../registry.js";
4
+ /**
5
+ * The platform icon setting through the `Platform` tool (mobile layout spec §10.2.1): the list,
6
+ * upload and restore of `/api/v1/admin/platform/icons*`, run through the same service. The public
7
+ * read of the bytes is a transport exclusion.
8
+ */
9
+ export declare class PlatformIconsOperations implements OnModuleInit {
10
+ private readonly registry;
11
+ private readonly icons;
12
+ constructor(registry: PlatformOperations, icons: PlatformIconService);
13
+ onModuleInit(): void;
14
+ }
@@ -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