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

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 (98) hide show
  1. package/dist/admin/admin.module.js +3 -0
  2. package/dist/admin/extensions.controller.d.ts +32 -1
  3. package/dist/admin/extensions.controller.js +72 -3
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/config/schema.d.ts +6 -0
  8. package/dist/config/schema.js +12 -0
  9. package/dist/conversations/event-log.d.ts +12 -3
  10. package/dist/conversations/event-log.js +17 -5
  11. package/dist/ctx/secrets.d.ts +10 -5
  12. package/dist/ctx/secrets.js +16 -5
  13. package/dist/db/kernel-schema.d.ts +34 -2
  14. package/dist/errors.d.ts +7 -0
  15. package/dist/errors.js +7 -0
  16. package/dist/extensions/config-hash.d.ts +2 -0
  17. package/dist/extensions/config-hash.js +1 -1
  18. package/dist/extensions/guide-places.d.ts +5 -1
  19. package/dist/extensions/guide-places.js +9 -2
  20. package/dist/extensions/permission-view.d.ts +6 -4
  21. package/dist/extensions/permission-view.js +6 -3
  22. package/dist/extensions/plugin-guides.d.ts +20 -0
  23. package/dist/extensions/plugin-guides.js +49 -1
  24. package/dist/extensions/registry.js +1 -0
  25. package/dist/http/api.module.js +7 -0
  26. package/dist/http/meta.controller.d.ts +7 -1
  27. package/dist/http/meta.controller.js +14 -3
  28. package/dist/identity/accounts.js +5 -0
  29. package/dist/identity/sessions.d.ts +7 -0
  30. package/dist/identity/sessions.js +26 -4
  31. package/dist/inbox/platform-inbox.service.d.ts +21 -11
  32. package/dist/inbox/platform-inbox.service.js +27 -12
  33. package/dist/inbox/platform-notices.d.ts +15 -1
  34. package/dist/inbox/platform-notices.js +20 -0
  35. package/dist/infra/config/kernel-config.service.js +2 -0
  36. package/dist/infra/outbox/registry.d.ts +36 -0
  37. package/dist/infra/outbox/registry.js +30 -0
  38. package/dist/infra/queue/queue-names.d.ts +1 -1
  39. package/dist/infra/queue/queue-names.js +1 -0
  40. package/dist/orgs/offboarding.js +3 -0
  41. package/dist/overrides.d.ts +4 -0
  42. package/dist/overrides.js +2 -0
  43. package/dist/platform/exclusions.js +15 -0
  44. package/dist/platform/ops/extensions-admin.ops.d.ts +5 -1
  45. package/dist/platform/ops/extensions-admin.ops.js +97 -2
  46. package/dist/platform/ops/inbox.ops.d.ts +1 -1
  47. package/dist/platform/ops/inbox.ops.js +17 -7
  48. package/dist/platform/ops/platform.ops.d.ts +4 -2
  49. package/dist/platform/ops/platform.ops.js +55 -3
  50. package/dist/platform/platform-ops.module.js +2 -0
  51. package/dist/platform/route-schemas.js +3 -0
  52. package/dist/push/delivery.d.ts +88 -0
  53. package/dist/push/delivery.js +269 -0
  54. package/dist/push/fanout.d.ts +29 -0
  55. package/dist/push/fanout.js +95 -0
  56. package/dist/push/jobs.d.ts +43 -0
  57. package/dist/push/jobs.js +19 -0
  58. package/dist/push/preferences.service.d.ts +18 -0
  59. package/dist/push/preferences.service.js +82 -0
  60. package/dist/push/provider-host.d.ts +34 -0
  61. package/dist/push/provider-host.js +94 -0
  62. package/dist/push/push-owed.d.ts +33 -0
  63. package/dist/push/push-owed.js +93 -0
  64. package/dist/push/push-processor.d.ts +40 -0
  65. package/dist/push/push-processor.js +114 -0
  66. package/dist/push/push.controller.d.ts +28 -0
  67. package/dist/push/push.controller.js +92 -0
  68. package/dist/push/push.module.d.ts +6 -0
  69. package/dist/push/push.module.js +29 -0
  70. package/dist/push/push.schemas.d.ts +88 -0
  71. package/dist/push/push.schemas.js +53 -0
  72. package/dist/push/recipients.d.ts +29 -0
  73. package/dist/push/recipients.js +263 -0
  74. package/dist/push/registration-cleanup.d.ts +9 -0
  75. package/dist/push/registration-cleanup.js +16 -0
  76. package/dist/push/registrations.service.d.ts +55 -0
  77. package/dist/push/registrations.service.js +254 -0
  78. package/dist/push/stale.job.d.ts +25 -0
  79. package/dist/push/stale.job.js +76 -0
  80. package/dist/push/texts.d.ts +31 -0
  81. package/dist/push/texts.js +46 -0
  82. package/dist/push/token-store.d.ts +31 -0
  83. package/dist/push/token-store.js +52 -0
  84. package/dist/push/triggers.d.ts +19 -0
  85. package/dist/push/triggers.js +30 -0
  86. package/dist/roles/worker-role.d.ts +7 -4
  87. package/dist/roles/worker-role.js +12 -5
  88. package/dist/roles/worker.module.d.ts +1 -1
  89. package/dist/roles/worker.module.js +4 -1
  90. package/dist/schedules/run-tracker.d.ts +10 -2
  91. package/dist/schedules/run-tracker.js +18 -4
  92. package/dist/setup/setup-checks.schemas.d.ts +29 -0
  93. package/dist/setup/setup-checks.schemas.js +32 -0
  94. package/dist/setup/setup-checks.service.d.ts +36 -3
  95. package/dist/setup/setup-checks.service.js +137 -29
  96. package/package.json +4 -4
  97. package/src/migrations/0172_push.sql +40 -0
  98. package/src/migrations/0173_push_auth_notice.sql +10 -0
@@ -0,0 +1,53 @@
1
+ import { PUSH_LIMITS } from "@capybara-hq/plugin-sdk";
2
+ import { z } from "zod";
3
+ import { createZodDto } from "../infra/validation/create-zod-dto.js";
4
+ /** The push categories a person switches (mobile app spec §9.4); an absent preference is on. */
5
+ export const PUSH_CATEGORIES = ["waiting", "replies", "tasks", "schedules"];
6
+ /**
7
+ * `POST /me/push-registrations`: what the app's shell returns from `push@1.register()`, plus the
8
+ * person's locale and a device name. The token is sealed at rest and never echoed.
9
+ */
10
+ export const PushRegistrationSchema = z
11
+ .object({
12
+ platform: z.enum(["ios", "android"]),
13
+ /** The bundle id / application id of the app build. */
14
+ appId: z
15
+ .string()
16
+ .min(1)
17
+ .max(PUSH_LIMITS.appIdChars)
18
+ .regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),
19
+ /** The push-provider extension (plugin name) the token belongs to. */
20
+ provider: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/),
21
+ token: z.string().min(1).max(PUSH_LIMITS.tokenChars),
22
+ locale: z.enum(["zh", "en"]),
23
+ /** Shown in the person's notification settings; no control or format characters. */
24
+ deviceName: z
25
+ .string()
26
+ .min(1)
27
+ .max(PUSH_LIMITS.deviceNameChars)
28
+ .regex(/^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+$/u),
29
+ })
30
+ .strict();
31
+ export class PushRegistrationDto extends createZodDto(PushRegistrationSchema, "PushRegistrationBody") {
32
+ }
33
+ export const PushRegistrationParams = z.object({ id: z.string().min(1).max(100) }).strict();
34
+ export class PushRegistrationParamsDto extends createZodDto(PushRegistrationParams, "PushRegistrationParams") {
35
+ }
36
+ /** The person's four push switches, as `GET` / `PUT /me/push-preferences` answer them. */
37
+ export const PushPreferencesSchema = z
38
+ .object({
39
+ waiting: z.boolean(),
40
+ replies: z.boolean(),
41
+ tasks: z.boolean(),
42
+ schedules: z.boolean(),
43
+ })
44
+ .strict();
45
+ /** `PUT /me/push-preferences`: the switches to change, at least one. */
46
+ export const PushPreferencesPatchSchema = PushPreferencesSchema.partial().refine((p) => Object.values(p).some((v) => v !== undefined), { message: "give at least one of waiting, replies, tasks, schedules" });
47
+ export class PushPreferencesPatchDto extends createZodDto(PushPreferencesPatchSchema, "PushPreferencesPatch") {
48
+ }
49
+ /** The push routes the Platform operations mirror (`check:platform-ops` keys). */
50
+ export const PUSH_ROUTES = [
51
+ { route: "GET /api/v1/me/push-preferences" },
52
+ { route: "PUT /api/v1/me/push-preferences", body: PushPreferencesPatchSchema },
53
+ ];
@@ -0,0 +1,29 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ import type { PushFanoutData } from "./jobs.js";
3
+ import type { ResolvedPush } from "./texts.js";
4
+ /** An event's push before the event id is attached: who receives it and what it says. */
5
+ export type ResolvedRecipients = Omit<ResolvedPush, "eventId">;
6
+ /**
7
+ * Who an event's push reaches, read when the fanout runs (mobile app spec §9.4, the plan's
8
+ * Triggers table), or null when nothing is pushed. Every check is made now, not when the event was
9
+ * written (review focus 1):
10
+ *
11
+ * - the org is not deleted, and every recipient is an `active` account that is still a member of
12
+ * the event's org (an account of another org never qualifies, whatever a row names);
13
+ * - `waiting`: an approval goes to `requested_for`, else to every member whose role is at least
14
+ * `approver_role` except the run's trigger account (as `canHandle`, review focus 2), and only
15
+ * while it is still `pending`; a question only while pending; both, and a connect request, go to
16
+ * the run's trigger account (an approval assigned to someone goes to that person);
17
+ * - `replies`: chat conversations only, to the conversation's owner, never for a run serving a
18
+ * scheduled task (that pushes as `schedules`);
19
+ * - `tasks`: the root conversation's owner;
20
+ * - `schedules`: the task's owner, for a task run `completed` or `failed` of a task not deleted;
21
+ * - eval conversations (a sub-agent under an eval root too) and deleted conversations never push;
22
+ * - an escalated approval whose run is gone pushes nothing (its initiator is unknown).
23
+ *
24
+ * The path carries the org (`/chat/<root>?org=<orgId>`, `&subagent=<child>` for an event of a
25
+ * sub-agent's log; a schedule run without a conversation opens `/inbox?org=<orgId>`), the thread
26
+ * is the root conversation (`schedule-<taskId>` for a schedule), the title the root's agent name
27
+ * (the task's name).
28
+ */
29
+ export declare function resolveRecipients(db: KernelSchemaDb, source: PushFanoutData["source"]): Promise<ResolvedRecipients | null>;
@@ -0,0 +1,263 @@
1
+ import { ORG_ROLES, roleAtLeast } from "../orgs/roles.js";
2
+ import { rootConversationOf } from "../runtime/subagents/child.js";
3
+ import { pushTriggerOf } from "./triggers.js";
4
+ /**
5
+ * Who an event's push reaches, read when the fanout runs (mobile app spec §9.4, the plan's
6
+ * Triggers table), or null when nothing is pushed. Every check is made now, not when the event was
7
+ * written (review focus 1):
8
+ *
9
+ * - the org is not deleted, and every recipient is an `active` account that is still a member of
10
+ * the event's org (an account of another org never qualifies, whatever a row names);
11
+ * - `waiting`: an approval goes to `requested_for`, else to every member whose role is at least
12
+ * `approver_role` except the run's trigger account (as `canHandle`, review focus 2), and only
13
+ * while it is still `pending`; a question only while pending; both, and a connect request, go to
14
+ * the run's trigger account (an approval assigned to someone goes to that person);
15
+ * - `replies`: chat conversations only, to the conversation's owner, never for a run serving a
16
+ * scheduled task (that pushes as `schedules`);
17
+ * - `tasks`: the root conversation's owner;
18
+ * - `schedules`: the task's owner, for a task run `completed` or `failed` of a task not deleted;
19
+ * - eval conversations (a sub-agent under an eval root too) and deleted conversations never push;
20
+ * - an escalated approval whose run is gone pushes nothing (its initiator is unknown).
21
+ *
22
+ * The path carries the org (`/chat/<root>?org=<orgId>`, `&subagent=<child>` for an event of a
23
+ * sub-agent's log; a schedule run without a conversation opens `/inbox?org=<orgId>`), the thread
24
+ * is the root conversation (`schedule-<taskId>` for a schedule), the title the root's agent name
25
+ * (the task's name).
26
+ */
27
+ export async function resolveRecipients(db, source) {
28
+ return source.kind === "schedule"
29
+ ? resolveSchedule(db, source.taskRunId)
30
+ : resolveConversation(db, source.conversationId, source.seq);
31
+ }
32
+ async function resolveConversation(db, conversationId, seq) {
33
+ const event = await db
34
+ .selectFrom("conversation_events")
35
+ .select(["type", "payload", "run_id"])
36
+ .where("conversation_id", "=", conversationId)
37
+ .where("seq", "=", String(seq))
38
+ .executeTakeFirst();
39
+ if (!event)
40
+ return null;
41
+ const trigger = pushTriggerOf({ type: event.type, payload: event.payload });
42
+ if (trigger === null)
43
+ return null;
44
+ const conv = await db
45
+ .selectFrom("conversations")
46
+ .select(["org_id", "kind", "account_id", "deleted_at"])
47
+ .where("id", "=", conversationId)
48
+ .executeTakeFirst();
49
+ if (!conv || conv.kind === "eval" || conv.deleted_at !== null)
50
+ return null;
51
+ if (trigger.category === "replies" && conv.kind !== "chat")
52
+ return null;
53
+ const orgId = conv.org_id;
54
+ if (!(await orgLive(db, orgId)))
55
+ return null;
56
+ const rootId = conv.kind === "subagent" ? await rootConversationOf(db, conversationId) : conversationId;
57
+ const root = rootId === conversationId
58
+ ? null
59
+ : await db
60
+ .selectFrom("conversations")
61
+ .select(["org_id", "kind", "account_id", "deleted_at"])
62
+ .where("id", "=", rootId)
63
+ .executeTakeFirst();
64
+ if (root !== null &&
65
+ (root === undefined ||
66
+ root.org_id !== orgId ||
67
+ root.kind === "eval" ||
68
+ root.deleted_at !== null)) {
69
+ return null;
70
+ }
71
+ const owner = root?.account_id ?? conv.account_id;
72
+ const payload = event.payload;
73
+ let candidates;
74
+ switch (trigger.text) {
75
+ case "approval": {
76
+ if (typeof payload.approvalId !== "string")
77
+ return null;
78
+ const approval = await db
79
+ .selectFrom("approvals")
80
+ .select(["run_id", "requested_for", "approver_role", "status"])
81
+ .where("id", "=", payload.approvalId)
82
+ .where("org_id", "=", orgId)
83
+ .where("conversation_id", "=", conversationId)
84
+ .executeTakeFirst();
85
+ if (approval?.status !== "pending")
86
+ return null;
87
+ if (approval.requested_for !== null) {
88
+ candidates = [approval.requested_for];
89
+ break;
90
+ }
91
+ const role = approval.approver_role;
92
+ if (role === null || !ORG_ROLES.includes(role))
93
+ return null;
94
+ // without its run the initiator is unknown, and only `canHandle` with it may decide
95
+ const initiator = await triggerAccountOf(db, approval.run_id);
96
+ if (initiator === null)
97
+ return null;
98
+ const roles = ORG_ROLES.filter((r) => roleAtLeast(r, role));
99
+ const rows = await db
100
+ .selectFrom("memberships")
101
+ .select("account_id")
102
+ .where("org_id", "=", orgId)
103
+ .where("role", "in", roles)
104
+ .execute();
105
+ candidates = rows.map((r) => r.account_id).filter((a) => a !== initiator);
106
+ break;
107
+ }
108
+ case "question": {
109
+ if (typeof payload.questionId !== "string")
110
+ return null;
111
+ const question = await db
112
+ .selectFrom("questions")
113
+ .select(["run_id", "status"])
114
+ .where("id", "=", payload.questionId)
115
+ .where("org_id", "=", orgId)
116
+ .where("conversation_id", "=", conversationId)
117
+ .executeTakeFirst();
118
+ if (question?.status !== "pending")
119
+ return null;
120
+ candidates = optional(await triggerAccountOf(db, question.run_id));
121
+ break;
122
+ }
123
+ case "connect":
124
+ candidates = event.run_id === null ? [] : optional(await triggerAccountOf(db, event.run_id));
125
+ break;
126
+ case "runFinished":
127
+ case "runFailed": {
128
+ if (event.run_id === null)
129
+ return null;
130
+ const run = await db
131
+ .selectFrom("runs")
132
+ .select("scheduled_task_run_id")
133
+ .where("id", "=", event.run_id)
134
+ .where("conversation_id", "=", conversationId)
135
+ .executeTakeFirst();
136
+ if (!run || run.scheduled_task_run_id !== null)
137
+ return null;
138
+ candidates = [owner];
139
+ break;
140
+ }
141
+ default:
142
+ candidates = [owner];
143
+ }
144
+ const accountIds = await activeMembers(db, orgId, candidates);
145
+ if (accountIds.length === 0)
146
+ return null;
147
+ const rootRow = await db
148
+ .selectFrom("conversations")
149
+ .select(["agent_id", "title"])
150
+ .where("id", "=", rootId)
151
+ .executeTakeFirstOrThrow();
152
+ const org = encodeURIComponent(orgId);
153
+ const path = rootId === conversationId
154
+ ? `/chat/${rootId}?org=${org}`
155
+ : `/chat/${rootId}?org=${org}&subagent=${conversationId}`;
156
+ return {
157
+ orgId,
158
+ accountIds,
159
+ category: trigger.category,
160
+ path,
161
+ threadId: rootId,
162
+ title: await agentName(db, rootRow.agent_id),
163
+ conversationTitle: rootRow.title,
164
+ text: trigger.text,
165
+ };
166
+ }
167
+ async function resolveSchedule(db, taskRunId) {
168
+ const row = await db
169
+ .selectFrom("scheduled_task_runs")
170
+ .innerJoin("scheduled_tasks", "scheduled_tasks.id", "scheduled_task_runs.task_id")
171
+ .select([
172
+ "scheduled_task_runs.org_id",
173
+ "scheduled_task_runs.status",
174
+ "scheduled_task_runs.conversation_id",
175
+ "scheduled_tasks.id as task_id",
176
+ "scheduled_tasks.org_id as task_org_id",
177
+ "scheduled_tasks.account_id",
178
+ "scheduled_tasks.name",
179
+ ])
180
+ .where("scheduled_task_runs.id", "=", taskRunId)
181
+ // a deleted task pushes nothing
182
+ .where("scheduled_tasks.deleted_at", "is", null)
183
+ .executeTakeFirst();
184
+ if (!row || row.org_id !== row.task_org_id)
185
+ return null;
186
+ if (row.status !== "completed" && row.status !== "failed")
187
+ return null;
188
+ const orgId = row.org_id;
189
+ if (!(await orgLive(db, orgId)))
190
+ return null;
191
+ const accountIds = await activeMembers(db, orgId, [row.account_id]);
192
+ if (accountIds.length === 0)
193
+ return null;
194
+ const conv = row.conversation_id === null
195
+ ? undefined
196
+ : await db
197
+ .selectFrom("conversations")
198
+ .select(["title"])
199
+ .where("id", "=", row.conversation_id)
200
+ .where("org_id", "=", orgId)
201
+ .where("deleted_at", "is", null)
202
+ .executeTakeFirst();
203
+ const org = encodeURIComponent(orgId);
204
+ return {
205
+ orgId,
206
+ accountIds,
207
+ category: "schedules",
208
+ path: conv === undefined ? `/inbox?org=${org}` : `/chat/${row.conversation_id}?org=${org}`,
209
+ threadId: `schedule-${row.task_id}`,
210
+ title: row.name,
211
+ conversationTitle: conv?.title ?? null,
212
+ text: row.status === "completed" ? "scheduleRan" : "scheduleFailed",
213
+ };
214
+ }
215
+ const optional = (id) => (id === null ? [] : [id]);
216
+ /** Whether the org exists and is not deleted. */
217
+ async function orgLive(db, orgId) {
218
+ const org = await db
219
+ .selectFrom("orgs")
220
+ .select("id")
221
+ .where("id", "=", orgId)
222
+ .where("deleted_at", "is", null)
223
+ .executeTakeFirst();
224
+ return org !== undefined;
225
+ }
226
+ /** The trigger account of a run, or null when the run is gone. */
227
+ async function triggerAccountOf(db, runId) {
228
+ const run = await db
229
+ .selectFrom("runs")
230
+ .select("trigger_account_id")
231
+ .where("id", "=", runId)
232
+ .executeTakeFirst();
233
+ return run?.trigger_account_id ?? null;
234
+ }
235
+ /** The accounts among `ids` that are active and members of `orgId`, sorted. */
236
+ async function activeMembers(db, orgId, ids) {
237
+ const unique = [...new Set(ids)];
238
+ if (unique.length === 0)
239
+ return [];
240
+ const rows = await db
241
+ .selectFrom("memberships")
242
+ .innerJoin("accounts", "accounts.id", "memberships.account_id")
243
+ .select("accounts.id")
244
+ .where("memberships.org_id", "=", orgId)
245
+ .where("memberships.account_id", "in", unique)
246
+ .where("accounts.status", "=", "active")
247
+ .orderBy("accounts.id")
248
+ .execute();
249
+ return rows.map((r) => r.id);
250
+ }
251
+ /** The agent's name in its current version (empty when it has none). */
252
+ async function agentName(db, agentId) {
253
+ const row = await db
254
+ .selectFrom("agents")
255
+ .innerJoin("agent_versions", (j) => j
256
+ .onRef("agent_versions.agent_id", "=", "agents.id")
257
+ .onRef("agent_versions.version", "=", "agents.current_version"))
258
+ .select("agent_versions.definition")
259
+ .where("agents.id", "=", agentId)
260
+ .executeTakeFirst();
261
+ const name = row?.definition?.name;
262
+ return typeof name === "string" ? name : "";
263
+ }
@@ -0,0 +1,9 @@
1
+ import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
+ /**
3
+ * Deletes the push registrations the given sessions posted (mobile app plan decision 3: a
4
+ * registration follows its session). Session revocation calls it in the transaction that sets
5
+ * `revoked_at`: the foreign key is `ON DELETE SET NULL` and revocation keeps the session row, so
6
+ * nothing else removes them. No person audit entry is written (`session_revoked` is implied by the
7
+ * revocation). Infra dependencies only, so `identity/sessions.ts` imports it without a cycle.
8
+ */
9
+ export declare function deletePushRegistrationsForSessions(db: KernelSchemaDb, sessionIds: readonly string[]): Promise<number>;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Deletes the push registrations the given sessions posted (mobile app plan decision 3: a
3
+ * registration follows its session). Session revocation calls it in the transaction that sets
4
+ * `revoked_at`: the foreign key is `ON DELETE SET NULL` and revocation keeps the session row, so
5
+ * nothing else removes them. No person audit entry is written (`session_revoked` is implied by the
6
+ * revocation). Infra dependencies only, so `identity/sessions.ts` imports it without a cycle.
7
+ */
8
+ export async function deletePushRegistrationsForSessions(db, sessionIds) {
9
+ if (sessionIds.length === 0)
10
+ return 0;
11
+ const r = await db
12
+ .deleteFrom("push_registrations")
13
+ .where("session_id", "in", [...sessionIds])
14
+ .executeTakeFirst();
15
+ return Number(r.numDeletedRows);
16
+ }
@@ -0,0 +1,55 @@
1
+ import { type Selectable } from "kysely";
2
+ import type { PushRegistrationsTable } from "../db/kernel-schema.js";
3
+ import { KernelDb } from "../infra/database/kernel-db.js";
4
+ import { TransactionHost } from "../infra/database/transaction-host.js";
5
+ import { PushProviderHost } from "./provider-host.js";
6
+ import type { PushRegistrationBody, PushRegistrationView } from "./push.schemas.js";
7
+ import { PushTokenStore } from "./token-store.js";
8
+ /** A stored registration, its token still sealed. */
9
+ export type PushRegistrationRow = Selectable<PushRegistrationsTable>;
10
+ /**
11
+ * A person's app installs that receive push (mobile app spec §9.3). A registration belongs to the
12
+ * account, not an org, and follows the session that posted it (plan decision 3). A token posted
13
+ * again, by anyone, updates the one row of `(provider, app_id, token_hash)` and keeps its id, so
14
+ * the sealed token (AAD bound to the id) still opens; a phone that changes hands stops reaching its
15
+ * previous account (decision 5). The token is never logged, audited or answered.
16
+ */
17
+ export declare class PushRegistrationsService {
18
+ private readonly db;
19
+ readonly txHost: TransactionHost;
20
+ private readonly tokens;
21
+ private readonly providers;
22
+ constructor(db: KernelDb, txHost: TransactionHost, tokens: PushTokenStore, providers: PushProviderHost);
23
+ /**
24
+ * Registers (or refreshes) an install for `accountId` from `sessionId`. A provider that is not
25
+ * loaded or does not cover the app id → 422 `push.provider_unavailable`; a session revoked
26
+ * since the request was authenticated → 401 `auth.session_revoked`. Beyond
27
+ * `PUSH_LIMITS.registrationsPerAccount` the least recently seen of the account are deleted.
28
+ * Audited (`push.registered`) for a new row or a row taken from another account.
29
+ */
30
+ register(accountId: string, sessionId: string, body: PushRegistrationBody): Promise<{
31
+ id: string;
32
+ }>;
33
+ /** Removes one of the person's registrations; another account's id → 404. Audited. */
34
+ remove(accountId: string, id: string): Promise<void>;
35
+ /** The person's registrations, newest `last_seen_at` first; `current` = posted by `sessionId`. */
36
+ list(accountId: string, sessionId: string): Promise<PushRegistrationView[]>;
37
+ /** The registrations of these accounts, tokens still sealed (the fanout opens them per send). */
38
+ forAccounts(accountIds: readonly string[]): Promise<PushRegistrationRow[]>;
39
+ /**
40
+ * Updates the row of this token in place (keeping its id) or inserts a sealed new one; null
41
+ * when the insert lost a unique conflict to a row that is already gone again.
42
+ */
43
+ private place;
44
+ private lockExisting;
45
+ /** Points an existing row at the caller and its session; the id and the sealed token stay. */
46
+ private refresh;
47
+ /**
48
+ * Deletes the account's registrations beyond the cap, least recently seen first. Rows locked by
49
+ * another transaction are skipped (`FOR UPDATE SKIP LOCKED`), never waited for: a concurrent
50
+ * revoke of another session deleting its rows would otherwise deadlock with this (40P01). A
51
+ * skipped row is on its way out (a revoke) or to another account (a reassignment), so it does
52
+ * not count toward the 20 kept; the cap stays exact once those commit.
53
+ */
54
+ private evictBeyondCap;
55
+ }