@capybara-hq/kernel 0.1.0-rc.59 → 0.1.0-rc.60

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 (139) hide show
  1. package/dist/admin/admin.controller.d.ts +10 -5
  2. package/dist/admin/admin.controller.js +16 -7
  3. package/dist/admin/admin.schemas.js +2 -1
  4. package/dist/admin/audit-log.service.d.ts +1 -0
  5. package/dist/admin/audit-log.service.js +4 -1
  6. package/dist/admin/extensions.schemas.js +2 -0
  7. package/dist/agents/admin-agents.d.ts +1 -0
  8. package/dist/agents/admin-agents.js +4 -1
  9. package/dist/agents/agents.controller.d.ts +1 -10
  10. package/dist/agents/agents.controller.js +2 -14
  11. package/dist/agents/agents.schemas.d.ts +10 -0
  12. package/dist/agents/agents.schemas.js +19 -0
  13. package/dist/background/tasks.service.d.ts +5 -0
  14. package/dist/background/tasks.service.js +10 -3
  15. package/dist/catalog/admin-catalog.schemas.js +2 -0
  16. package/dist/catalog/component-scope.schemas.js +2 -0
  17. package/dist/catalog/marketplaces.service.d.ts +1 -1
  18. package/dist/catalog/org-plugin-uploads.schemas.js +2 -0
  19. package/dist/catalog/requests.service.d.ts +2 -0
  20. package/dist/catalog/requests.service.js +4 -1
  21. package/dist/channels/cards.d.ts +9 -0
  22. package/dist/channels/cards.js +32 -1
  23. package/dist/channels/phrases.d.ts +5 -0
  24. package/dist/channels/phrases.js +5 -0
  25. package/dist/conversations/attachments.service.d.ts +34 -0
  26. package/dist/conversations/attachments.service.js +124 -21
  27. package/dist/conversations/conversations.controller.d.ts +5 -1
  28. package/dist/conversations/conversations.controller.js +11 -5
  29. package/dist/conversations/conversations.service.d.ts +5 -0
  30. package/dist/conversations/conversations.service.js +10 -0
  31. package/dist/conversations/event-people.d.ts +12 -0
  32. package/dist/conversations/event-people.js +28 -0
  33. package/dist/db/kernel-schema.d.ts +18 -0
  34. package/dist/devices/devices.service.d.ts +3 -2
  35. package/dist/devices/devices.service.js +17 -2
  36. package/dist/errors.d.ts +1 -0
  37. package/dist/errors.js +1 -0
  38. package/dist/evals/trajectory.service.d.ts +3 -0
  39. package/dist/evals/trajectory.service.js +2 -0
  40. package/dist/extensions/installs.d.ts +3 -0
  41. package/dist/extensions/installs.js +1 -0
  42. package/dist/http/api.module.js +2 -0
  43. package/dist/http/meta.controller.d.ts +1 -0
  44. package/dist/http/meta.controller.js +6 -1
  45. package/dist/identity/account-avatar.controller.d.ts +30 -0
  46. package/dist/identity/account-avatar.controller.js +117 -0
  47. package/dist/identity/account-avatar.d.ts +67 -0
  48. package/dist/identity/account-avatar.js +136 -0
  49. package/dist/identity/account-avatars.service.d.ts +77 -0
  50. package/dist/identity/account-avatars.service.js +321 -0
  51. package/dist/identity/accounts.d.ts +26 -0
  52. package/dist/identity/accounts.js +70 -2
  53. package/dist/identity/app-auth.controller.d.ts +2 -1
  54. package/dist/identity/app-auth.controller.js +2 -1
  55. package/dist/identity/app-auth.d.ts +24 -7
  56. package/dist/identity/app-auth.js +19 -9
  57. package/dist/identity/app-auth.schemas.d.ts +16 -3
  58. package/dist/identity/app-auth.schemas.js +5 -2
  59. package/dist/identity/external.js +7 -1
  60. package/dist/identity/identity.module.d.ts +2 -1
  61. package/dist/identity/identity.module.js +7 -1
  62. package/dist/identity/me.controller.d.ts +29 -5
  63. package/dist/identity/me.controller.js +57 -6
  64. package/dist/identity/me.schemas.d.ts +36 -0
  65. package/dist/identity/me.schemas.js +30 -0
  66. package/dist/identity/principal.d.ts +2 -2
  67. package/dist/identity/principal.js +2 -2
  68. package/dist/local-devices/local-device-gateway.d.ts +2 -0
  69. package/dist/local-devices/local-device-gateway.js +8 -1
  70. package/dist/local-devices/relay.d.ts +10 -9
  71. package/dist/local-devices/relay.js +32 -9
  72. package/dist/local-devices/targets.d.ts +12 -0
  73. package/dist/local-devices/targets.js +18 -2
  74. package/dist/orgs/members.service.d.ts +3 -1
  75. package/dist/orgs/members.service.js +9 -2
  76. package/dist/platform/exclusions.js +33 -57
  77. package/dist/platform/file-ref.d.ts +87 -0
  78. package/dist/platform/file-ref.js +164 -0
  79. package/dist/platform/operation.d.ts +26 -0
  80. package/dist/platform/ops/agent-skills.ops.d.ts +2 -0
  81. package/dist/platform/ops/agent-skills.ops.js +156 -4
  82. package/dist/platform/ops/agents.ops.d.ts +3 -1
  83. package/dist/platform/ops/agents.ops.js +75 -17
  84. package/dist/platform/ops/approvals.ops.js +5 -0
  85. package/dist/platform/ops/catalog-admin.ops.d.ts +9 -1
  86. package/dist/platform/ops/catalog-admin.ops.js +86 -3
  87. package/dist/platform/ops/components.ops.d.ts +3 -1
  88. package/dist/platform/ops/components.ops.js +61 -2
  89. package/dist/platform/ops/connectors.ops.js +15 -1
  90. package/dist/platform/ops/devices.ops.js +6 -1
  91. package/dist/platform/ops/extensions-admin.ops.d.ts +6 -4
  92. package/dist/platform/ops/extensions-admin.ops.js +109 -6
  93. package/dist/platform/ops/inbox.ops.js +10 -0
  94. package/dist/platform/ops/list-handoff.d.ts +10 -0
  95. package/dist/platform/ops/list-handoff.js +11 -0
  96. package/dist/platform/ops/marketplaces.ops.js +2 -1
  97. package/dist/platform/ops/org-plugins.ops.d.ts +12 -3
  98. package/dist/platform/ops/org-plugins.ops.js +97 -6
  99. package/dist/platform/ops/requests.ops.js +9 -0
  100. package/dist/platform/ops/skills.ops.d.ts +5 -1
  101. package/dist/platform/ops/skills.ops.js +98 -4
  102. package/dist/platform/ops/summary.d.ts +5 -0
  103. package/dist/platform/ops/summary.js +10 -0
  104. package/dist/platform/parity.d.ts +6 -4
  105. package/dist/platform/parity.js +94 -68
  106. package/dist/roles/worker.module.js +5 -0
  107. package/dist/sandbox/request-not-sent.d.ts +13 -0
  108. package/dist/sandbox/request-not-sent.js +18 -0
  109. package/dist/schedules/scheduled-tasks.service.d.ts +10 -6
  110. package/dist/schedules/scheduled-tasks.service.js +13 -16
  111. package/dist/shares/shares.service.d.ts +1 -0
  112. package/dist/shares/shares.service.js +9 -3
  113. package/dist/skills/changes.service.d.ts +1 -0
  114. package/dist/skills/changes.service.js +4 -7
  115. package/dist/skills/skills.controller.d.ts +3 -7
  116. package/dist/skills/skills.controller.js +3 -16
  117. package/dist/skills/skills.schemas.d.ts +5 -0
  118. package/dist/skills/skills.schemas.js +17 -0
  119. package/dist/skills/skills.service.d.ts +3 -1
  120. package/dist/skills/skills.service.js +13 -4
  121. package/dist/tools/admin-connectors.d.ts +1 -0
  122. package/dist/tools/admin-connectors.js +4 -1
  123. package/dist/tools/approvals.service.d.ts +16 -2
  124. package/dist/tools/approvals.service.js +13 -0
  125. package/dist/tools/builtins/builtin-tools.d.ts +3 -0
  126. package/dist/tools/builtins/builtin-tools.js +29 -9
  127. package/dist/tools/builtins/platform.d.ts +23 -0
  128. package/dist/tools/builtins/platform.js +95 -6
  129. package/dist/tools/builtins/sandbox/common.d.ts +5 -0
  130. package/dist/tools/builtins/sandbox/common.js +11 -0
  131. package/dist/tools/builtins/skill-load.js +4 -4
  132. package/dist/tools/pipeline.js +10 -3
  133. package/dist/tools/questions.controller.js +2 -2
  134. package/dist/tools/questions.service.d.ts +7 -1
  135. package/dist/tools/questions.service.js +9 -2
  136. package/dist/tools/registry.d.ts +6 -0
  137. package/dist/tools/tools.module.js +3 -0
  138. package/package.json +3 -3
  139. package/src/migrations/0171_account_avatar.sql +26 -0
@@ -0,0 +1,321 @@
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 { randomUUID } from "node:crypto";
11
+ import { Inject, Injectable } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { AGENT_AVATAR_CONTENT_TYPES, AGENT_AVATAR_DOWNLOAD_TTL_SECONDS, AGENT_AVATAR_MAX_BYTES, AGENT_AVATAR_TTL_HOURS, ATTACHMENT_UPLOAD_TTL_SECONDS, MAX_PENDING_AGENT_AVATARS, normalizeContentType, sniffMatches, } from "../conversations/attachments.service.js";
14
+ import { ApiError } from "../errors.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 { LockService } from "../infra/lock/lock.service.js";
19
+ import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
20
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
21
+ import { StorageService } from "../storage/storage.service.js";
22
+ /** The hourly cleanup of expired, unbound account avatar uploads (`@LockedCron`). */
23
+ export const ACCOUNT_AVATAR_CLEANUP_JOB = "account-avatar-cleanup";
24
+ /** Rows one claim of the cleanup takes. */
25
+ const CLEANUP_BATCH = 100;
26
+ /** How many leading bytes `prepare` reads to check the image signature. */
27
+ const SNIFF_BYTES = 64;
28
+ /** The object key under `deployment/` (the kernel adds that prefix). */
29
+ const objectKey = (accountId, uploadId) => `account-avatars/${accountId}/${uploadId}`;
30
+ const notFound = () => new ApiError("attachment.not_found", "Avatar upload not found");
31
+ const isAvatarType = (contentType) => AGENT_AVATAR_CONTENT_TYPES.includes(contentType);
32
+ async function readAll(body) {
33
+ return new Uint8Array(await new Response(body).arrayBuffer());
34
+ }
35
+ /**
36
+ * A person's own avatar uploads (account profile spec §5.3): register → the browser uploads to
37
+ * the presigned URL → `prepare` checks the object → `bind` in the profile write's transaction.
38
+ * Bytes live under `deployment/account-avatars/<accountId>/<uploadId>`; an unbound upload carries
39
+ * `expires_at` and is swept by {@link AccountAvatarCleanupJob}. No in-process state.
40
+ */
41
+ let AccountAvatarsService = class AccountAvatarsService {
42
+ db;
43
+ txHost;
44
+ storage;
45
+ log;
46
+ constructor(db, txHost, storage, log) {
47
+ this.db = db;
48
+ this.txHost = txHost;
49
+ this.storage = storage;
50
+ this.log = log;
51
+ }
52
+ /**
53
+ * Registers a `pending` upload (intent first: the row, expiring in 24 h, is written before the
54
+ * presigned upload is returned, so a crash leaves only an expiring row). A type other than
55
+ * png / jpeg / webp → `attachment.type_not_allowed`; over 2 MB → `attachment.too_large`; already
56
+ * 10 pending uploads → `attachment.too_many_pending` (soft: concurrent calls may pass together);
57
+ * no object store → `storage.unavailable`.
58
+ */
59
+ async createUpload(accountId, input) {
60
+ this.storage.assertAvailable();
61
+ const contentType = normalizeContentType(input.contentType);
62
+ if (!isAvatarType(contentType)) {
63
+ throw new ApiError("attachment.type_not_allowed", `Avatar type ${JSON.stringify(contentType)} is not allowed; use PNG, JPEG or WebP`);
64
+ }
65
+ if (input.size > AGENT_AVATAR_MAX_BYTES) {
66
+ throw new ApiError("attachment.too_large", `Avatar is ${input.size} bytes, over the limit of ${AGENT_AVATAR_MAX_BYTES} bytes`);
67
+ }
68
+ const pending = await this.db
69
+ .selectFrom("account_avatar_uploads")
70
+ .select((eb) => eb.fn.countAll().as("n"))
71
+ .where("account_id", "=", accountId)
72
+ .where("status", "=", "pending")
73
+ .where(sql `expires_at is null or expires_at > now()`)
74
+ .executeTakeFirst();
75
+ if (Number(pending?.n ?? 0) >= MAX_PENDING_AGENT_AVATARS) {
76
+ throw new ApiError("attachment.too_many_pending", `Too many unfinished avatar uploads (at most ${MAX_PENDING_AGENT_AVATARS}); finish or wait for them first`);
77
+ }
78
+ const uploadId = randomUUID();
79
+ const key = objectKey(accountId, uploadId);
80
+ await this.db
81
+ .insertInto("account_avatar_uploads")
82
+ .values({
83
+ id: uploadId,
84
+ account_id: accountId,
85
+ storage_key: key,
86
+ content_type: contentType,
87
+ size: input.size,
88
+ status: "pending",
89
+ expires_at: sql `now() + make_interval(hours => ${AGENT_AVATAR_TTL_HOURS})`,
90
+ })
91
+ .execute();
92
+ const upload = await this.storage.deployment().presignPut(key, {
93
+ contentType,
94
+ maxSize: input.size,
95
+ ttlSeconds: ATTACHMENT_UPLOAD_TTL_SECONDS,
96
+ });
97
+ return {
98
+ uploadId,
99
+ upload,
100
+ expiresAt: new Date(Date.now() + ATTACHMENT_UPLOAD_TTL_SECONDS * 1000).toISOString(),
101
+ };
102
+ }
103
+ /**
104
+ * Makes the account's upload ready to be bound (outside any transaction: it reads the object
105
+ * store). Not the account's, or expired → `attachment.not_found`. A `pending` upload is checked
106
+ * against the store: no object → `attachment.not_ready`; a size other than declared, a stored
107
+ * type or an image signature other than declared → the object is deleted and
108
+ * `attachment.too_large` / `attachment.not_ready` / `attachment.type_not_allowed`. The expiry of
109
+ * an unbound upload is extended so the cleanup cannot remove it before {@link bind} runs.
110
+ */
111
+ async prepare(accountId, uploadId) {
112
+ this.storage.assertAvailable();
113
+ const row = await this.db
114
+ .selectFrom("account_avatar_uploads")
115
+ .select([
116
+ "status",
117
+ "content_type",
118
+ "size",
119
+ "storage_key",
120
+ sql `expires_at is not null and expires_at <= now()`.as("expired"),
121
+ ])
122
+ .where("id", "=", uploadId)
123
+ .where("account_id", "=", accountId)
124
+ .executeTakeFirst();
125
+ if (!row || row.expired || !isAvatarType(row.content_type))
126
+ throw notFound();
127
+ if (row.status === "pending") {
128
+ const size = await this.check(row.storage_key, row.content_type, Number(row.size));
129
+ await this.db
130
+ .updateTable("account_avatar_uploads")
131
+ .set({ status: "ready", size })
132
+ .where("id", "=", uploadId)
133
+ .where("status", "=", "pending")
134
+ .execute();
135
+ }
136
+ await this.db
137
+ .updateTable("account_avatar_uploads")
138
+ .set({ expires_at: sql `now() + make_interval(hours => ${AGENT_AVATAR_TTL_HOURS})` })
139
+ .where("id", "=", uploadId)
140
+ // never revives a row that expired since the SELECT: the cleanup may be deleting its object
141
+ .where("expires_at", ">", sql `now()`)
142
+ .execute();
143
+ }
144
+ /** The store-side checks of {@link prepare}; returns the stored size. */
145
+ async check(key, contentType, declared) {
146
+ const store = this.storage.deployment();
147
+ const head = await store.head(key);
148
+ if (!head)
149
+ throw new ApiError("attachment.not_ready", "The avatar has not been uploaded yet");
150
+ const reject = async (err) => {
151
+ await store.delete(key);
152
+ throw err;
153
+ };
154
+ if (head.size !== declared) {
155
+ await reject(head.size > declared
156
+ ? new ApiError("attachment.too_large", "Uploaded avatar is larger than declared")
157
+ : new ApiError("attachment.not_ready", `Uploaded avatar is ${head.size} bytes, but ${declared} bytes were declared; upload it again`));
158
+ }
159
+ if (normalizeContentType(head.contentType) !== contentType) {
160
+ await reject(new ApiError("attachment.type_not_allowed", "Uploaded avatar type does not match"));
161
+ }
162
+ const got = await store.get(key, {
163
+ range: { start: 0, end: Math.max(0, Math.min(declared, SNIFF_BYTES) - 1) },
164
+ });
165
+ const data = got ? await readAll(got.body) : new Uint8Array();
166
+ if (!sniffMatches(contentType, data.subarray(0, SNIFF_BYTES))) {
167
+ await reject(new ApiError("attachment.type_not_allowed", `Uploaded avatar is not ${contentType}`));
168
+ }
169
+ return head.size;
170
+ }
171
+ /**
172
+ * In the caller's transaction: binds the account's ready, unexpired upload (row lock; its
173
+ * `expires_at` is cleared, so the cleanup keeps it) and expires every other upload of the
174
+ * account, the previous avatar among them. `null` binds none (the avatar is removed). An upload
175
+ * that is not the account's ready one → `attachment.not_ready` while pending, else
176
+ * `attachment.not_found`; binding the bound upload again is fine.
177
+ */
178
+ async bind(accountId, uploadId) {
179
+ const trx = this.db.db;
180
+ if (uploadId !== null) {
181
+ const row = await trx
182
+ .selectFrom("account_avatar_uploads")
183
+ .select([
184
+ "status",
185
+ sql `expires_at is not null and expires_at <= now()`.as("expired"),
186
+ ])
187
+ .where("id", "=", uploadId)
188
+ .where("account_id", "=", accountId)
189
+ .forUpdate()
190
+ .executeTakeFirst();
191
+ if (!row || row.expired)
192
+ throw notFound();
193
+ if (row.status !== "ready") {
194
+ throw new ApiError("attachment.not_ready", "The avatar has not been uploaded yet");
195
+ }
196
+ await trx
197
+ .updateTable("account_avatar_uploads")
198
+ .set({ expires_at: null })
199
+ .where("id", "=", uploadId)
200
+ .execute();
201
+ }
202
+ await trx
203
+ .updateTable("account_avatar_uploads")
204
+ .set({ expires_at: sql `now()` })
205
+ .where("account_id", "=", accountId)
206
+ .$if(uploadId !== null, (q) => q.where("id", "<>", uploadId))
207
+ .where(sql `expires_at is null or expires_at > now()`)
208
+ .execute();
209
+ }
210
+ /**
211
+ * A short-lived presigned GET (inline, with the checked type) of the account's bound upload;
212
+ * null when there is none, or its object is gone or no longer the size checked.
213
+ */
214
+ async objectUrl(accountId, uploadId) {
215
+ this.storage.assertAvailable();
216
+ const row = await this.db
217
+ .selectFrom("account_avatar_uploads")
218
+ .select(["storage_key", "content_type", "size"])
219
+ .where("id", "=", uploadId)
220
+ .where("account_id", "=", accountId)
221
+ .where("status", "=", "ready")
222
+ .where("expires_at", "is", null)
223
+ .executeTakeFirst();
224
+ if (!row)
225
+ return null;
226
+ const store = this.storage.deployment();
227
+ const head = await store.head(row.storage_key);
228
+ if (!head || head.size !== Number(row.size))
229
+ return null;
230
+ return store.presignGet(row.storage_key, {
231
+ ttlSeconds: AGENT_AVATAR_DOWNLOAD_TTL_SECONDS,
232
+ disposition: "inline",
233
+ responseContentType: row.content_type,
234
+ });
235
+ }
236
+ /**
237
+ * Deletes expired uploads (`expires_at < now()`), bound ones never, in batches of 100: the rows
238
+ * are read without a lock, each object is deleted outside any transaction, then its row
239
+ * (`DELETE … WHERE id AND expires_at < now()`). This needs no claim because an expired row can
240
+ * never come back: {@link prepare} extends only an unexpired expiry and {@link bind} refuses an
241
+ * expired row, so nothing binds a row whose object is being deleted. A failed object delete
242
+ * keeps the row for the next run. Does nothing without an object store. Returns the rows deleted.
243
+ */
244
+ async deleteExpired() {
245
+ if (!this.storage.available)
246
+ return 0;
247
+ const store = this.storage.deployment();
248
+ let deleted = 0;
249
+ // rows this run already handled (deleted, failed, or gone meanwhile): never read twice
250
+ const seen = [];
251
+ for (;;) {
252
+ const batch = await this.db
253
+ .selectFrom("account_avatar_uploads")
254
+ .select(["id", "account_id", "storage_key"])
255
+ .where("expires_at", "<", sql `now()`)
256
+ .$if(seen.length > 0, (q) => q.where("id", "not in", seen))
257
+ .orderBy("expires_at")
258
+ .limit(CLEANUP_BATCH)
259
+ .execute();
260
+ for (const r of batch) {
261
+ seen.push(r.id);
262
+ try {
263
+ await store.delete(r.storage_key);
264
+ }
265
+ catch (err) {
266
+ this.log.warn("cannot delete expired account avatar upload; will retry", {
267
+ accountId: r.account_id,
268
+ uploadId: r.id,
269
+ err,
270
+ });
271
+ continue;
272
+ }
273
+ const gone = await this.db
274
+ .deleteFrom("account_avatar_uploads")
275
+ .where("id", "=", r.id)
276
+ .where("expires_at", "<", sql `now()`)
277
+ .executeTakeFirst();
278
+ deleted += Number(gone.numDeletedRows);
279
+ }
280
+ if (batch.length < CLEANUP_BATCH)
281
+ return deleted;
282
+ }
283
+ }
284
+ };
285
+ __decorate([
286
+ Transactional({ propagation: "mandatory" })
287
+ ], AccountAvatarsService.prototype, "bind", null);
288
+ AccountAvatarsService = __decorate([
289
+ Injectable(),
290
+ __param(0, Inject(KernelDb)),
291
+ __param(1, Inject(TransactionHost)),
292
+ __param(2, Inject(StorageService)),
293
+ __param(3, Inject(KERNEL_LOGGER))
294
+ ], AccountAvatarsService);
295
+ export { AccountAvatarsService };
296
+ /** Deletes expired account avatar uploads once per hour across replicas; the worker role's. */
297
+ let AccountAvatarCleanupJob = class AccountAvatarCleanupJob {
298
+ avatars;
299
+ lockService;
300
+ log;
301
+ constructor(avatars, lockService, log) {
302
+ this.avatars = avatars;
303
+ this.lockService = lockService;
304
+ this.log = log;
305
+ }
306
+ async run() {
307
+ const n = await this.avatars.deleteExpired();
308
+ if (n > 0)
309
+ this.log.info("expired account avatar uploads deleted", { count: n });
310
+ }
311
+ };
312
+ __decorate([
313
+ LockedCron("0 * * * *", { name: ACCOUNT_AVATAR_CLEANUP_JOB })
314
+ ], AccountAvatarCleanupJob.prototype, "run", null);
315
+ AccountAvatarCleanupJob = __decorate([
316
+ Injectable(),
317
+ __param(0, Inject(AccountAvatarsService)),
318
+ __param(1, Inject(LockService)),
319
+ __param(2, Inject(KERNEL_LOGGER))
320
+ ], AccountAvatarCleanupJob);
321
+ export { AccountAvatarCleanupJob };
@@ -4,6 +4,7 @@ import type { AccountsTable } from "../db/kernel-schema.js";
4
4
  import { KernelDb } from "../infra/database/kernel-db.js";
5
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
6
6
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
7
+ import { type AccountAvatar, type AccountView } from "./account-avatar.js";
7
8
  import { SuperAdminLock } from "./super-admin.js";
8
9
  export interface Account {
9
10
  id: string;
@@ -24,6 +25,19 @@ export type AccountPatch = {
24
25
  status?: "active" | "disabled";
25
26
  isSuperAdmin?: boolean;
26
27
  };
28
+ /** The longest display name a profile change may set, in code points (account profile §5.1). */
29
+ export declare const DISPLAY_NAME_MAX_CHARS = 64;
30
+ /**
31
+ * The name rule of the two profile PATCH routes: the name is trimmed, and when it differs from
32
+ * the stored (trimmed) one it must have at most {@link DISPLAY_NAME_MAX_CHARS} code points; an
33
+ * unchanged name passes even when an older one is longer. Returns the trimmed name.
34
+ */
35
+ export declare function checkDisplayNameChange(stored: string, next: string): string;
36
+ /** What a person may change on their own profile (`PATCH /me/profile`). */
37
+ export type ProfilePatch = {
38
+ displayName?: string;
39
+ avatar?: AccountAvatar | null;
40
+ };
27
41
  /** 构造 `Account` 所需的 accounts 列(供跨表查询 select 使用)。 */
28
42
  export declare const ACCOUNT_COLUMNS: readonly ["accounts.id", "accounts.display_name", "accounts.email", "accounts.status", "accounts.is_super_admin", "accounts.must_change_password", "accounts.created_at"];
29
43
  type AccountRow = Pick<Selectable<AccountsTable>, "id" | "display_name" | "email" | "status" | "is_super_admin" | "must_change_password" | "created_at">;
@@ -137,6 +151,18 @@ export declare class AccountsService {
137
151
  changePassword(accountId: string, password: string, exceptSessionId: string): Promise<string[]>;
138
152
  private changePasswordIn;
139
153
  update(id: string, patch: AccountPatch, actorAccountId: string, actorTokenId?: string): Promise<Account>;
154
+ /**
155
+ * A person changes their own profile (account profile spec §5.3), in one transaction: the
156
+ * account row is locked, a changed name passes {@link checkDisplayNameChange}, `bindAvatar`
157
+ * binds the new upload (or none for `avatar: null`; the caller's `AccountAvatarsService.bind`,
158
+ * which needs the object store this module does not import), the row is written and
159
+ * `account.profile_updated` audited (actor = the account; `detail` = the new name and
160
+ * `avatar: "upload" | "removed"`, never the image). An empty patch writes nothing. The upload
161
+ * must already be prepared (outside any transaction). Missing account → `account.not_found`.
162
+ */
163
+ updateProfile(accountId: string, patch: ProfilePatch, actorTokenId?: string, opts?: {
164
+ bindAvatar?: (uploadId: string | null) => Promise<void>;
165
+ }): Promise<AccountView>;
140
166
  /**
141
167
  * A super admin changes an account. Disabling (`status: "disabled"`) revokes the
142
168
  * account's sessions (`sessions.revoked_at`) and personal tokens in **the same PG transaction**,
@@ -18,10 +18,25 @@ import { Transactional } from "../infra/database/transactional.decorator.js";
18
18
  import { PermissionCeilingWritesModule } from "../sandbox/permission-authority.module.js";
19
19
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
20
20
  import { assertThemeOnForAccount } from "../themes/theme-state.js";
21
+ import { withAvatarUrl } from "./account-avatar.js";
21
22
  import { audit } from "./audit.js";
22
23
  import { MAX_PASSWORD_LENGTH, normalizeLogin, validatePassword } from "./login.js";
23
24
  import { DUMMY_PASSWORD_HASH, hashPassword, verifyPassword } from "./passwords.js";
24
25
  import { SuperAdminLock, SuperAdminLockModule } from "./super-admin.js";
26
+ /** The longest display name a profile change may set, in code points (account profile §5.1). */
27
+ export const DISPLAY_NAME_MAX_CHARS = 64;
28
+ /**
29
+ * The name rule of the two profile PATCH routes: the name is trimmed, and when it differs from
30
+ * the stored (trimmed) one it must have at most {@link DISPLAY_NAME_MAX_CHARS} code points; an
31
+ * unchanged name passes even when an older one is longer. Returns the trimmed name.
32
+ */
33
+ export function checkDisplayNameChange(stored, next) {
34
+ const name = next.trim();
35
+ if (name !== stored.trim() && [...name].length > DISPLAY_NAME_MAX_CHARS) {
36
+ throw new ApiError("account.display_name_too_long", `The name has ${[...name].length} characters; at most ${DISPLAY_NAME_MAX_CHARS} are allowed`);
37
+ }
38
+ return name;
39
+ }
25
40
  /** 构造 `Account` 所需的 accounts 列(供跨表查询 select 使用)。 */
26
41
  export const ACCOUNT_COLUMNS = [
27
42
  "accounts.id",
@@ -328,6 +343,55 @@ let AccountsService = class AccountsService {
328
343
  async update(id, patch, actorAccountId, actorTokenId) {
329
344
  return (await this.updateAccount(id, patch, actorAccountId, actorTokenId)).account;
330
345
  }
346
+ /**
347
+ * A person changes their own profile (account profile spec §5.3), in one transaction: the
348
+ * account row is locked, a changed name passes {@link checkDisplayNameChange}, `bindAvatar`
349
+ * binds the new upload (or none for `avatar: null`; the caller's `AccountAvatarsService.bind`,
350
+ * which needs the object store this module does not import), the row is written and
351
+ * `account.profile_updated` audited (actor = the account; `detail` = the new name and
352
+ * `avatar: "upload" | "removed"`, never the image). An empty patch writes nothing. The upload
353
+ * must already be prepared (outside any transaction). Missing account → `account.not_found`.
354
+ */
355
+ async updateProfile(accountId, patch, actorTokenId, opts = {}) {
356
+ const before = await this.db
357
+ .selectFrom("accounts")
358
+ .selectAll()
359
+ .where("id", "=", accountId)
360
+ .forUpdate()
361
+ .executeTakeFirst();
362
+ if (!before)
363
+ throw new ApiError("account.not_found", "Account not found");
364
+ if (patch.displayName === undefined && patch.avatar === undefined) {
365
+ return withAvatarUrl(this.db.db, toAccount(before));
366
+ }
367
+ const values = { updated_at: new Date() };
368
+ const detail = {};
369
+ if (patch.displayName !== undefined) {
370
+ values.display_name = checkDisplayNameChange(before.display_name, patch.displayName);
371
+ detail.displayName = values.display_name;
372
+ }
373
+ if (patch.avatar !== undefined) {
374
+ if (!opts.bindAvatar)
375
+ throw new Error("updateProfile: an avatar change needs bindAvatar");
376
+ await opts.bindAvatar(patch.avatar?.uploadId ?? null);
377
+ values.avatar = patch.avatar === null ? null : JSON.stringify(patch.avatar);
378
+ detail.avatar = patch.avatar === null ? "removed" : "upload";
379
+ }
380
+ const row = await this.db
381
+ .updateTable("accounts")
382
+ .set(values)
383
+ .where("id", "=", accountId)
384
+ .returningAll()
385
+ .executeTakeFirstOrThrow();
386
+ await audit(this.db.db, {
387
+ actorAccountId: accountId,
388
+ ...(actorTokenId !== undefined && { actorTokenId }),
389
+ action: "account.profile_updated",
390
+ target: accountId,
391
+ detail,
392
+ });
393
+ return withAvatarUrl(this.db.db, toAccount(row));
394
+ }
331
395
  /**
332
396
  * A super admin changes an account. Disabling (`status: "disabled"`) revokes the
333
397
  * account's sessions (`sessions.revoked_at`) and personal tokens in **the same PG transaction**,
@@ -506,8 +570,9 @@ let AccountsService = class AccountsService {
506
570
  async applyUpdate(before, patch, auditAs) {
507
571
  const id = before.id;
508
572
  const values = { updated_at: new Date() };
509
- if (patch.displayName !== undefined)
510
- values.display_name = patch.displayName;
573
+ if (patch.displayName !== undefined) {
574
+ values.display_name = checkDisplayNameChange(before.display_name, patch.displayName);
575
+ }
511
576
  if (patch.status !== undefined && patch.status !== before.status) {
512
577
  await this.ceilings.lock({}, "platform");
513
578
  await this.ceilings.publishLocked({}, "platform", patch.status === "disabled" ? (_scope, row) => row.account_id === id : false);
@@ -579,6 +644,9 @@ __decorate([
579
644
  __decorate([
580
645
  Transactional()
581
646
  ], AccountsService.prototype, "changePasswordIn", null);
647
+ __decorate([
648
+ Transactional()
649
+ ], AccountsService.prototype, "updateProfile", null);
582
650
  __decorate([
583
651
  Transactional({ propagation: "mandatory" })
584
652
  ], AccountsService.prototype, "lockForUpdate", null);
@@ -10,7 +10,8 @@ import { type Principal } from "./principal.js";
10
10
  * `/apps/authorize` → `{ redirect }` with `code`, `state` and `iss`, or `error=access_denied`
11
11
  * with `deny: true`; an unlisted redirect URI is `app_auth.redirect_uri_invalid`;
12
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`.
13
+ * its verifier → `{ account }` and the session cookies, or `app_auth.code_invalid`
14
+ * (`auth.account_disabled` for an account that is not active).
14
15
  */
15
16
  export declare class AppAuthController {
16
17
  private readonly auth;
@@ -22,7 +22,8 @@ import { CurrentPrincipal, Public, requireUser, SessionOnly } from "./principal.
22
22
  * `/apps/authorize` → `{ redirect }` with `code`, `state` and `iss`, or `error=access_denied`
23
23
  * with `deny: true`; an unlisted redirect URI is `app_auth.redirect_uri_invalid`;
24
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`.
25
+ * its verifier → `{ account }` and the session cookies, or `app_auth.code_invalid`
26
+ * (`auth.account_disabled` for an account that is not active).
26
27
  */
27
28
  let AppAuthController = class AppAuthController {
28
29
  auth;
@@ -3,13 +3,24 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
5
  import { type Account, AccountsService } from "./accounts.js";
6
- import type { AppAuthorizeBody, AppTokenBody } from "./app-auth.schemas.js";
6
+ import type { AppAuthorizeBody, AppClient, AppTokenBody } from "./app-auth.schemas.js";
7
7
  import type { UserPrincipal } from "./principal.js";
8
8
  import { type IssuedSession, SessionService } from "./sessions.js";
9
9
  /** How long a sign-in code lives, seconds (one use within this window). */
10
10
  export declare const APP_AUTH_CODE_TTL_SECONDS = 60;
11
11
  /** The stored grant of one code: `capk:app-auth-code:<sha256(code)>`. The code is never stored. */
12
12
  export declare const appAuthCodeKey: (code: string) => string;
13
+ /** What a code stands for, as JSON under its key. */
14
+ interface CodeGrant {
15
+ accountId: string;
16
+ /** The browser session that consented: the exchange fails once it signed out. */
17
+ sessionId: string;
18
+ client: AppClient;
19
+ redirectUri: string;
20
+ codeChallenge: string;
21
+ name: string;
22
+ appVersion: string;
23
+ }
13
24
  /** BASE64URL(SHA-256(verifier)): the PKCE `S256` challenge (RFC 7636 §4.2). */
14
25
  export declare function s256(verifier: string): string;
15
26
  /**
@@ -20,11 +31,16 @@ export declare function buildRedirect(uri: string, params: Record<string, string
20
31
  /** Whether `uri` is one of `allowed`, compared as exact strings (no prefix, no case folding). */
21
32
  export declare function isAllowedRedirect(uri: string, allowed: readonly string[]): boolean;
22
33
  /**
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.
34
+ * The session user agent of an app session: `Capybara Desktop/<appVersion> (<name>)` or
35
+ * `Capybara Mobile/<appVersion> (<name>)`.
36
+ */
37
+ export declare const appUserAgent: (g: Pick<CodeGrant, "client" | "appVersion" | "name">) => string;
38
+ /**
39
+ * Native-app sign-in (desktop client spec §6.5, mobile spec §4.3): the authorization code flow with
40
+ * PKCE for native apps (RFC 8252, RFC 7636). The signed-in person consents on the web
41
+ * (`authorize`), which issues a one-time code bound to the PKCE challenge, the redirect URI and
42
+ * the browser session; the app exchanges it (`token`) for an ordinary web session of its own.
43
+ * State lives only in Redis, under the code's hash with a 60 s TTL, so any replica can exchange it.
28
44
  */
29
45
  export declare class AppAuthService {
30
46
  private readonly db;
@@ -46,7 +62,7 @@ export declare class AppAuthService {
46
62
  * The app's exchange: the code is taken from Redis with GETDEL before anything else (one use:
47
63
  * a wrong verifier or redirect URI burns it too), then checked against `redirectUri` and
48
64
  * `S256(codeVerifier)`; the session is created in {@link signIn}. Every failure is
49
- * `app_auth.code_invalid`.
65
+ * `app_auth.code_invalid`, except an account that is not active: `auth.account_disabled`.
50
66
  */
51
67
  token(body: AppTokenBody, meta: {
52
68
  ip: string;
@@ -64,3 +80,4 @@ export declare class AppAuthService {
64
80
  /** `iss`: `http.publicUrl` without a trailing slash, the origin the app checks (RFC 9207). */
65
81
  private issuer;
66
82
  }
83
+ export {};
@@ -46,15 +46,22 @@ export function buildRedirect(uri, params) {
46
46
  export function isAllowedRedirect(uri, allowed) {
47
47
  return allowed.includes(uri);
48
48
  }
49
- /** The session user agent of an app session: `Capybara Desktop/<appVersion> (<name>)`. */
50
- const appUserAgent = (g) => `Capybara Desktop/${g.appVersion} (${g.name})`;
49
+ const CLIENT_PRODUCT = {
50
+ desktop: "Capybara Desktop",
51
+ mobile: "Capybara Mobile",
52
+ };
53
+ /**
54
+ * The session user agent of an app session: `Capybara Desktop/<appVersion> (<name>)` or
55
+ * `Capybara Mobile/<appVersion> (<name>)`.
56
+ */
57
+ export const appUserAgent = (g) => `${CLIENT_PRODUCT[g.client]}/${g.appVersion} (${g.name})`;
51
58
  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
59
  /**
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.
60
+ * Native-app sign-in (desktop client spec §6.5, mobile spec §4.3): the authorization code flow with
61
+ * PKCE for native apps (RFC 8252, RFC 7636). The signed-in person consents on the web
62
+ * (`authorize`), which issues a one-time code bound to the PKCE challenge, the redirect URI and
63
+ * the browser session; the app exchanges it (`token`) for an ordinary web session of its own.
64
+ * State lives only in Redis, under the code's hash with a 60 s TTL, so any replica can exchange it.
58
65
  */
59
66
  let AppAuthService = class AppAuthService {
60
67
  db;
@@ -112,7 +119,7 @@ let AppAuthService = class AppAuthService {
112
119
  * The app's exchange: the code is taken from Redis with GETDEL before anything else (one use:
113
120
  * a wrong verifier or redirect URI burns it too), then checked against `redirectUri` and
114
121
  * `S256(codeVerifier)`; the session is created in {@link signIn}. Every failure is
115
- * `app_auth.code_invalid`.
122
+ * `app_auth.code_invalid`, except an account that is not active: `auth.account_disabled`.
116
123
  */
117
124
  async token(body, meta) {
118
125
  if (!CODE_RE.test(body.code))
@@ -143,8 +150,11 @@ let AppAuthService = class AppAuthService {
143
150
  .where("id", "=", grant.accountId)
144
151
  .forShare()
145
152
  .executeTakeFirst();
146
- if (row?.status !== "active")
153
+ if (!row)
147
154
  throw codeInvalid();
155
+ // the app tells the person why (desktop client spec §6.6) instead of a generic failed code
156
+ if (row.status !== "active")
157
+ throw new ApiError("auth.account_disabled", "Account is disabled");
148
158
  const consenting = await this.db
149
159
  .selectFrom("sessions")
150
160
  .select("id")
@@ -1,11 +1,20 @@
1
1
  import { z } from "zod";
2
+ /** The native apps that sign in this way: the desktop app and the mobile app (mobile spec §4.3). */
3
+ export declare const AppClientSchema: z.ZodEnum<{
4
+ desktop: "desktop";
5
+ mobile: "mobile";
6
+ }>;
7
+ export type AppClient = z.infer<typeof AppClientSchema>;
2
8
  /**
3
9
  * `POST /api/v1/app-auth/authorize` (desktop client spec §6.5): the person consents on the web to
4
10
  * sign a native app in. `codeChallenge` is BASE64URL(SHA-256(verifier)), always 43 characters;
5
11
  * only the `S256` method exists. `deny` answers the `error=access_denied` redirect instead.
6
12
  */
7
13
  export declare const AppAuthorizeBodySchema: z.ZodObject<{
8
- client: z.ZodLiteral<"desktop">;
14
+ client: z.ZodEnum<{
15
+ desktop: "desktop";
16
+ mobile: "mobile";
17
+ }>;
9
18
  redirectUri: z.ZodString;
10
19
  codeChallenge: z.ZodString;
11
20
  codeChallengeMethod: z.ZodLiteral<"S256">;
@@ -16,7 +25,10 @@ export declare const AppAuthorizeBodySchema: z.ZodObject<{
16
25
  }, z.core.$strict>;
17
26
  export type AppAuthorizeBody = z.infer<typeof AppAuthorizeBodySchema>;
18
27
  declare const AppAuthorizeBodyDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
19
- client: z.ZodLiteral<"desktop">;
28
+ client: z.ZodEnum<{
29
+ desktop: "desktop";
30
+ mobile: "mobile";
31
+ }>;
20
32
  redirectUri: z.ZodString;
21
33
  codeChallenge: z.ZodString;
22
34
  codeChallengeMethod: z.ZodLiteral<"S256">;
@@ -29,7 +41,8 @@ export declare class AppAuthorizeBodyDto extends AppAuthorizeBodyDto_base {
29
41
  }
30
42
  /**
31
43
  * `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).
44
+ * the shape is checked here; every content failure answers `app_auth.code_invalid` (the service),
45
+ * except a disabled account: `auth.account_disabled`.
33
46
  */
34
47
  export declare const AppTokenBodySchema: z.ZodObject<{
35
48
  code: z.ZodString;