@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
@@ -8,10 +8,15 @@ import { SETUP_GUIDE_PLACE_INFO, } from "@capybara-hq/plugin-sdk";
8
8
  import { webhookBase, webhookUrlOf } from "../channels/webhook-url.js";
9
9
  import { ApiError } from "../errors.js";
10
10
  import { OAUTH_CALLBACK_PATH } from "../tools/oauth/flow-paths.js";
11
- /** The org action each audience of a place needs besides `catalog.read` (spec §9.1). */
11
+ /**
12
+ * The org action each audience of a place needs besides `catalog.read` (spec §9.1).
13
+ * `extension-deployment` has none: its guides are the super admin's (the admin extension routes),
14
+ * so an org route refuses them (`forbidden`).
15
+ */
12
16
  export const PLACE_ACTIONS = {
13
17
  "channel-connection": { admin: "channels.manage" },
14
18
  "connector-template": { admin: "connectors.manage", member: "connectors.use" },
19
+ "extension-deployment": {},
15
20
  };
16
21
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
22
  const invalidQuery = (path, message) => new ApiError("validation_failed", "Request validation failed", [{ path, message }]);
@@ -19,6 +24,7 @@ const invalidQuery = (path, message) => new ApiError("validation_failed", "Reque
19
24
  const TARGET_PARAMS = {
20
25
  "channel-connection": ["connectionId", "name"],
21
26
  "connector-template": ["connectorId"],
27
+ "extension-deployment": [],
22
28
  };
23
29
  /**
24
30
  * The variable values of a place for one rendering (spec §6.3): the common ones, then the place's
@@ -64,7 +70,7 @@ export async function resolvePlace(ctx) {
64
70
  storedMode = connection.inbound_mode;
65
71
  }
66
72
  }
67
- else {
73
+ else if (place === "connector-template") {
68
74
  const connector = ctx.query.connectorId === undefined
69
75
  ? undefined
70
76
  : await liveConnector(ctx, ctx.query.connectorId);
@@ -77,6 +83,7 @@ export async function resolvePlace(ctx) {
77
83
  if (connector !== undefined)
78
84
  target = { kind: "connector", id: connector.id };
79
85
  }
86
+ // `extension-deployment`: the common variables only, no org and no target (the deployment)
80
87
  reasons.publicUrl = "public_url";
81
88
  reasons.signInCallbackUrl = "public_url";
82
89
  reasons.oauthCallbackUrl = "public_url";
@@ -30,7 +30,7 @@ export interface PermissionGroup {
30
30
  * ({@link SENSITIVE_EXTENSION_POINTS}; the code is the extension point name without `@<major>`, with
31
31
  * `-` replaced by `_`).
32
32
  */
33
- export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "sandbox" | "object_store" | "context" | "migration_warnings";
33
+ export type SensitiveReason = "secrets" | "public_routes" | "embed_routes" | "tools" | "hooks" | "ui_embed" | "client_code" | "ui_component" | "channel" | "directory" | "identity_source" | "sandbox" | "object_store" | "context" | "push_provider" | "migration_warnings";
34
34
  /** 权限清单里的一项(分组里的一项,或 `added` 里的一个权限键)。 */
35
35
  export interface PermissionItem {
36
36
  value: string;
@@ -44,9 +44,11 @@ export interface PermissionItem {
44
44
  * receives the org's IM conversations (Ruling A33), `directory@1` can add people to orgs (creating
45
45
  * their accounts and identities), `identity-source@1` decides who can sign in as which account;
46
46
  * `context@1` adds text to the model's context in conversations of orgs that enable it (memory
47
- * plugin spec §6.1). A plugin providing any of them has its "provides" group marked sensitive and
48
- * `sensitive` true in the admin plugin list, for the super admin to approve. Display only: the keys
49
- * of the permission snapshot do not change.
47
+ * plugin spec §6.1); `push-provider@1` receives the title and in-app path of every push
48
+ * notification and the device tokens it delivers to (mobile app spec §9). A plugin providing any
49
+ * of them has its "provides" group marked sensitive and `sensitive` true in the admin plugin
50
+ * list, for the super admin to approve. Display only: the keys of the permission snapshot do not
51
+ * change.
50
52
  */
51
53
  export declare const SENSITIVE_EXTENSION_POINTS: readonly string[];
52
54
  /**
@@ -23,9 +23,11 @@ export function reviewHash(set, warnings = []) {
23
23
  * receives the org's IM conversations (Ruling A33), `directory@1` can add people to orgs (creating
24
24
  * their accounts and identities), `identity-source@1` decides who can sign in as which account;
25
25
  * `context@1` adds text to the model's context in conversations of orgs that enable it (memory
26
- * plugin spec §6.1). A plugin providing any of them has its "provides" group marked sensitive and
27
- * `sensitive` true in the admin plugin list, for the super admin to approve. Display only: the keys
28
- * of the permission snapshot do not change.
26
+ * plugin spec §6.1); `push-provider@1` receives the title and in-app path of every push
27
+ * notification and the device tokens it delivers to (mobile app spec §9). A plugin providing any
28
+ * of them has its "provides" group marked sensitive and `sensitive` true in the admin plugin
29
+ * list, for the super admin to approve. Display only: the keys of the permission snapshot do not
30
+ * change.
29
31
  */
30
32
  export const SENSITIVE_EXTENSION_POINTS = [
31
33
  "channel@1",
@@ -34,6 +36,7 @@ export const SENSITIVE_EXTENSION_POINTS = [
34
36
  "sandbox@2",
35
37
  "object-store@1",
36
38
  "context@1",
39
+ "push-provider@1",
37
40
  ];
38
41
  /** The one item of the "client" group (client extensions spec §5.4). */
39
42
  const CLIENT_ITEM = "client code";
@@ -275,6 +275,26 @@ export declare class PluginGuides {
275
275
  renderForPlatform(itemId: string, guideId: string, q: {
276
276
  locale?: "en" | "zh" | undefined;
277
277
  }): Promise<RenderedSetupGuide>;
278
+ /**
279
+ * The `extension-deployment` guides of an extension, rendered for the platform (the super
280
+ * admin's extension page, `GET /admin/extensions/:name/guides`): the guides of that place in the
281
+ * latest version of the catalog item of the same name, admin audience, no org and no target.
282
+ * None when the extension has no catalog item; a guide that cannot be rendered is left out and
283
+ * logged.
284
+ */
285
+ deploymentGuides(plugin: string, q: {
286
+ locale?: "en" | "zh" | undefined;
287
+ }): Promise<RenderedSetupGuide[]>;
288
+ /**
289
+ * One `extension-deployment` guide of an extension rendered for the platform (the deployment
290
+ * checks' guide). 404 `catalog.guide_not_found` when the extension's catalog item has no guide
291
+ * of that place with that id.
292
+ */
293
+ renderForDeployment(plugin: string, guideId: string, q: {
294
+ locale?: "en" | "zh" | undefined;
295
+ }): Promise<RenderedSetupGuide>;
296
+ /** A guide rendered without an org: the admin audience, no target, `orgName` unresolved. */
297
+ private renderPlatformDoc;
278
298
  /** The audience asked for, after checking `mode` and `audience` against the place. */
279
299
  private checkQuery;
280
300
  /** The rendered guide: the mode picked, the document rendered, the hash and the reasons. */
@@ -478,7 +478,55 @@ let PluginGuides = PluginGuides_1 = class PluginGuides {
478
478
  const guide = guidesOf(row.manifest).guides.find((g) => g.id === guideId);
479
479
  if (!guide)
480
480
  throw guideNotFound();
481
- const docs = await this.documents(row, guide, q.locale ?? "en");
481
+ return this.renderPlatformDoc(row, guide, q.locale ?? "en");
482
+ }
483
+ /**
484
+ * The `extension-deployment` guides of an extension, rendered for the platform (the super
485
+ * admin's extension page, `GET /admin/extensions/:name/guides`): the guides of that place in the
486
+ * latest version of the catalog item of the same name, admin audience, no org and no target.
487
+ * None when the extension has no catalog item; a guide that cannot be rendered is left out and
488
+ * logged.
489
+ */
490
+ async deploymentGuides(plugin, q) {
491
+ const [row] = await this.latest("name", [plugin]);
492
+ if (!row)
493
+ return [];
494
+ this.warnSkipped(row);
495
+ const out = [];
496
+ for (const guide of guidesOf(row.manifest).guides) {
497
+ if (guide.place !== "extension-deployment")
498
+ continue;
499
+ try {
500
+ out.push(await this.renderPlatformDoc(row, guide, q.locale ?? "en"));
501
+ }
502
+ catch (err) {
503
+ if (!(err instanceof ApiError))
504
+ throw err;
505
+ this.log.warn("setup guide left out of the list", {
506
+ plugin,
507
+ guideId: guide.id,
508
+ code: err.code,
509
+ });
510
+ }
511
+ }
512
+ return out;
513
+ }
514
+ /**
515
+ * One `extension-deployment` guide of an extension rendered for the platform (the deployment
516
+ * checks' guide). 404 `catalog.guide_not_found` when the extension's catalog item has no guide
517
+ * of that place with that id.
518
+ */
519
+ async renderForDeployment(plugin, guideId, q) {
520
+ const [row] = await this.latest("name", [plugin]);
521
+ const guide = row &&
522
+ guidesOf(row.manifest).guides.find((g) => g.id === guideId && g.place === "extension-deployment");
523
+ if (!row || !guide)
524
+ throw guideNotFound();
525
+ return this.renderPlatformDoc(row, guide, q.locale ?? "en");
526
+ }
527
+ /** A guide rendered without an org: the admin audience, no target, `orgName` unresolved. */
528
+ async renderPlatformDoc(row, guide, locale) {
529
+ const docs = await this.documents(row, guide, locale);
482
530
  const resolution = await resolvePlace({
483
531
  db: this.db,
484
532
  config: this.config.get(),
@@ -14,6 +14,7 @@ const TRACKED_EXTENSION_POINTS = {
14
14
  "model-provider": {},
15
15
  "web-search": {},
16
16
  "web-fetch": {},
17
+ "push-provider": {},
17
18
  };
18
19
  /**
19
20
  * The extension instances in effect in this process (by extension name, one each). One provider
@@ -76,6 +76,9 @@ import { OrgsModule } from "../orgs/orgs.module.js";
76
76
  import { OrgSettingsController } from "../orgs/settings.controller.js";
77
77
  import { PlatformModule } from "../platform/platform.module.js";
78
78
  import { SealedRevealsController } from "../platform/sealed-reveals.controller.js";
79
+ import { PushHostModule } from "../push/provider-host.js";
80
+ import { PushController } from "../push/push.controller.js";
81
+ import { PushModule } from "../push/push.module.js";
79
82
  import { RuntimeModule } from "../runtime/runtime.module.js";
80
83
  import { ConversationStreamController } from "../runtime/stream.controller.js";
81
84
  import { SchedulesController } from "../schedules/schedules.controller.js";
@@ -117,6 +120,7 @@ const CONTROLLERS = [
117
120
  MetaController,
118
121
  MeController,
119
122
  AccountAvatarController,
123
+ PushController,
120
124
  InitialPasswordsController,
121
125
  // the invitation link an org admin's agent created, read once by its approver (web parity §7.2)
122
126
  SealedRevealsController,
@@ -223,6 +227,9 @@ ApiModule = __decorate([
223
227
  PlatformModule,
224
228
  AdminModule,
225
229
  ExtensionsModule,
230
+ PushHostModule,
231
+ // push registrations and preferences under /api/v1/me
232
+ PushModule,
226
233
  CatalogModule,
227
234
  // a plugin's suggested appearance (its own module: it writes through the org settings)
228
235
  AppearanceModule,
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
3
+ import { PushProviderHost } from "../push/provider-host.js";
3
4
  import { PlatformIconService } from "../themes/platform-icon.service.js";
4
5
  /** Pre-sign-in discovery document native clients and the PWA manifest read. */
5
6
  export declare const MetaResponseSchema: z.ZodObject<{
@@ -19,6 +20,10 @@ export declare const MetaResponseSchema: z.ZodObject<{
19
20
  features: z.ZodObject<{
20
21
  localDevices: z.ZodBoolean;
21
22
  appSignIn: z.ZodBoolean;
23
+ push: z.ZodArray<z.ZodObject<{
24
+ appId: z.ZodString;
25
+ providers: z.ZodArray<z.ZodString>;
26
+ }, z.core.$strip>>;
22
27
  }, z.core.$strip>;
23
28
  appRedirectUris: z.ZodArray<z.ZodString>;
24
29
  }, z.core.$strip>;
@@ -27,7 +32,8 @@ export type MetaResponse = z.infer<typeof MetaResponseSchema>;
27
32
  export declare class MetaController {
28
33
  private readonly config;
29
34
  private readonly icons;
30
- constructor(config: KernelConfigService, icons: PlatformIconService);
35
+ private readonly push;
36
+ constructor(config: KernelConfigService, icons: PlatformIconService, push: PushProviderHost);
31
37
  meta(): Promise<MetaResponse>;
32
38
  /** A customised platform icon's versioned URL (the one the manifest uses); null for the default. */
33
39
  private iconUrl;
@@ -12,6 +12,7 @@ import { Controller, Get, Header, Inject } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { Public } from "../identity/principal.js";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
+ import { PushProviderHost } from "../push/provider-host.js";
15
16
  import { PlatformIconService } from "../themes/platform-icon.service.js";
16
17
  /** Pre-sign-in discovery document native clients and the PWA manifest read. */
17
18
  export const MetaResponseSchema = z.object({
@@ -25,7 +26,12 @@ export const MetaResponseSchema = z.object({
25
26
  protocols: z.object({
26
27
  device: z.object({ min: z.number().int(), max: z.number().int() }),
27
28
  }),
28
- features: z.object({ localDevices: z.boolean(), appSignIn: z.boolean() }),
29
+ features: z.object({
30
+ localDevices: z.boolean(),
31
+ appSignIn: z.boolean(),
32
+ /** App ids a push provider covers with the providers that do; `[]` without `http.publicUrl`. */
33
+ push: z.array(z.object({ appId: z.string(), providers: z.array(z.string()) })),
34
+ }),
29
35
  /** The redirect URIs app sign-in accepts (`auth.appRedirectUris`); [] while appSignIn is off. */
30
36
  appRedirectUris: z.array(z.string()),
31
37
  });
@@ -33,9 +39,11 @@ export const MetaResponseSchema = z.object({
33
39
  let MetaController = class MetaController {
34
40
  config;
35
41
  icons;
36
- constructor(config, icons) {
42
+ push;
43
+ constructor(config, icons, push) {
37
44
  this.config = config;
38
45
  this.icons = icons;
46
+ this.push = push;
39
47
  }
40
48
  async meta() {
41
49
  const config = this.config.get();
@@ -54,6 +62,8 @@ let MetaController = class MetaController {
54
62
  localDevices: true,
55
63
  // The authorize route answers app_auth.unavailable without http.publicUrl.
56
64
  appSignIn,
65
+ // A push message carries the deployment origin, which needs http.publicUrl.
66
+ push: config.http.publicUrl ? this.push.coverage() : [],
57
67
  },
58
68
  // Not secret: an app that finds its own URI missing says so before opening the browser.
59
69
  appRedirectUris: appSignIn ? [...config.auth.appRedirectUris] : [],
@@ -72,6 +82,7 @@ __decorate([
72
82
  MetaController = __decorate([
73
83
  Controller("api/v1/meta"),
74
84
  __param(0, Inject(KernelConfigService)),
75
- __param(1, Inject(PlatformIconService))
85
+ __param(1, Inject(PlatformIconService)),
86
+ __param(2, Inject(PushProviderHost))
76
87
  ], MetaController);
77
88
  export { MetaController };
@@ -15,6 +15,7 @@ import { ApiError } from "../errors.js";
15
15
  import { KernelDb } from "../infra/database/kernel-db.js";
16
16
  import { TransactionHost, withOrderedLocks } from "../infra/database/transaction-host.js";
17
17
  import { Transactional } from "../infra/database/transactional.decorator.js";
18
+ import { deletePushRegistrationsForSessions } from "../push/registration-cleanup.js";
18
19
  import { PermissionCeilingWritesModule } from "../sandbox/permission-authority.module.js";
19
20
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
20
21
  import { assertThemeOnForAccount } from "../themes/theme-state.js";
@@ -331,6 +332,8 @@ let AccountsService = class AccountsService {
331
332
  .where("id", "!=", exceptSessionId)
332
333
  .returning("id")
333
334
  .execute();
335
+ // the other devices stop receiving push; the current session's registrations stay
336
+ await deletePushRegistrationsForSessions(this.db.db, sessions.map((r) => r.id));
334
337
  await this.db
335
338
  .updateTable("api_tokens")
336
339
  .set({ revoked_at: sql `now()` })
@@ -628,6 +631,8 @@ let AccountsService = class AccountsService {
628
631
  .where("revoked_at", "is", null)
629
632
  .execute();
630
633
  revokedSessionIds = sessions.map((r) => r.id);
634
+ // a registration follows its session (push plan decision 3): a disabled account loses all
635
+ await deletePushRegistrationsForSessions(this.db.db, revokedSessionIds);
631
636
  }
632
637
  return { account: toAccount(row), revokedSessionIds };
633
638
  }
@@ -65,8 +65,15 @@ export declare class SessionService {
65
65
  sessionIdFromAccess(accessToken: string): Promise<string | undefined>;
66
66
  /** 按 refresh token 吊销其当前会话(供登出使用);无匹配则什么都不做。 */
67
67
  revokeByRefresh(refreshToken: string): Promise<void>;
68
+ /** Revokes one session and deletes the push registrations it posted, then writes the marker. */
68
69
  revoke(sessionId: string): Promise<void>;
70
+ private revokeIn;
71
+ /**
72
+ * Revokes the account's sessions (but `exceptSessionId`) and deletes their push registrations
73
+ * in one transaction, then writes the markers.
74
+ */
69
75
  revokeAllForAccount(accountId: string, exceptSessionId?: string): Promise<number>;
76
+ private revokeAllIn;
70
77
  /**
71
78
  * 给已在 PG 中吊销的会话写 Redis 吊销标记(快速路径);任一写入失败即抛出。
72
79
  * 鉴权以 PG `revoked_at` 为准,调用方可以把这一步当作尽力而为。
@@ -18,6 +18,7 @@ import { KernelDb } from "../infra/database/kernel-db.js";
18
18
  import { TransactionHost } from "../infra/database/transaction-host.js";
19
19
  import { Transactional } from "../infra/database/transactional.decorator.js";
20
20
  import { KEYRING, REDIS } from "../infra/tokens.js";
21
+ import { deletePushRegistrationsForSessions } from "../push/registration-cleanup.js";
21
22
  import { ACCOUNT_COLUMNS, toAccount } from "./accounts.js";
22
23
  import { sha256Hex } from "./hash.js";
23
24
  /** 旧 refresh token 在被轮换后多久内重放视为并发刷新(不吊销会话)。 */
@@ -218,16 +219,31 @@ let SessionService = class SessionService {
218
219
  if (row)
219
220
  await this.revoke(row.id);
220
221
  }
222
+ /** Revokes one session and deletes the push registrations it posted, then writes the marker. */
221
223
  async revoke(sessionId) {
224
+ await this.revokeIn(sessionId);
225
+ await this.redis.set(revokedKey(sessionId), "1", "EX", REVOKED_MARKER_TTL_SECONDS);
226
+ }
227
+ async revokeIn(sessionId) {
222
228
  await this.db
223
229
  .updateTable("sessions")
224
230
  .set({ revoked_at: sql `now()` })
225
231
  .where("id", "=", sessionId)
226
232
  .where("revoked_at", "is", null)
227
233
  .execute();
228
- await this.redis.set(revokedKey(sessionId), "1", "EX", REVOKED_MARKER_TTL_SECONDS);
234
+ // a registration follows its session (push plan decision 3); the row is kept, so delete them
235
+ await deletePushRegistrationsForSessions(this.db.db, [sessionId]);
229
236
  }
237
+ /**
238
+ * Revokes the account's sessions (but `exceptSessionId`) and deletes their push registrations
239
+ * in one transaction, then writes the markers.
240
+ */
230
241
  async revokeAllForAccount(accountId, exceptSessionId) {
242
+ const ids = await this.revokeAllIn(accountId, exceptSessionId);
243
+ await this.markRevoked(ids);
244
+ return ids.length;
245
+ }
246
+ async revokeAllIn(accountId, exceptSessionId) {
231
247
  let q = this.db
232
248
  .updateTable("sessions")
233
249
  .set({ revoked_at: sql `now()` })
@@ -235,9 +251,9 @@ let SessionService = class SessionService {
235
251
  .where("revoked_at", "is", null);
236
252
  if (exceptSessionId !== undefined)
237
253
  q = q.where("id", "!=", exceptSessionId);
238
- const rows = await q.returning("id").execute();
239
- await this.markRevoked(rows.map((r) => r.id));
240
- return rows.length;
254
+ const ids = (await q.returning("id").execute()).map((r) => r.id);
255
+ await deletePushRegistrationsForSessions(this.db.db, ids);
256
+ return ids;
241
257
  }
242
258
  /**
243
259
  * 给已在 PG 中吊销的会话写 Redis 吊销标记(快速路径);任一写入失败即抛出。
@@ -351,6 +367,12 @@ let SessionService = class SessionService {
351
367
  };
352
368
  }
353
369
  };
370
+ __decorate([
371
+ Transactional()
372
+ ], SessionService.prototype, "revokeIn", null);
373
+ __decorate([
374
+ Transactional()
375
+ ], SessionService.prototype, "revokeAllIn", null);
354
376
  __decorate([
355
377
  Transactional()
356
378
  ], SessionService.prototype, "switchIn", null);
@@ -3,7 +3,7 @@ import { type CatalogItemView, CatalogService } from "../catalog/catalog.service
3
3
  import { CatalogRequestsService, type CatalogRequestView } from "../catalog/requests.service.js";
4
4
  import type { ScopeSyncOp } from "../db/kernel-schema.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
- import type { PlatformNoticeDetails } from "./platform-notices.js";
6
+ import type { PlatformNoticeDetails, PlatformNoticeKind } from "./platform-notices.js";
7
7
  /** The most items one platform inbox read returns. */
8
8
  export declare const PLATFORM_INBOX_MAX_ITEMS = 100;
9
9
  /** The most open scope sync failures one read takes. */
@@ -64,7 +64,9 @@ export interface ExtensionDisabledView {
64
64
  * ({@link ExtensionDisabledView}), `id` = the item's; gone once the extension is enabled (or the
65
65
  * scope no longer turns it on);
66
66
  * - `ownership_transferred`: a deleted org's shared item now belongs to the platform, until a
67
- * super admin dismisses it (`POST admin/inbox/notices/:id/dismiss`).
67
+ * super admin dismisses it (`POST admin/inbox/notices/:id/dismiss`);
68
+ * - `push_auth_failed`: a push provider's credentials were refused on a delivery (at most one
69
+ * open per plugin), until a super admin dismisses it (same route).
68
70
  */
69
71
  export type PlatformInboxItem = {
70
72
  type: "catalog_request";
@@ -95,19 +97,26 @@ export type PlatformInboxItem = {
95
97
  type: "ownership_transferred";
96
98
  id: string;
97
99
  createdAt: string;
98
- notice: PlatformNoticeView;
100
+ notice: PlatformNoticeView<"ownership_transferred">;
101
+ } | {
102
+ type: "push_auth_failed";
103
+ id: string;
104
+ createdAt: string;
105
+ notice: PlatformNoticeView<"push_auth_failed">;
99
106
  };
100
107
  /** Every {@link PlatformInboxItem} type, in the order the admin overview lists them. */
101
- export declare const PLATFORM_INBOX_TYPES: readonly ["catalog_request", "permission_confirmation", "org_upload_pending", "scope_sync_failed", "extension_disabled", "ownership_transferred"];
108
+ export declare const PLATFORM_INBOX_TYPES: readonly ["catalog_request", "permission_confirmation", "org_upload_pending", "scope_sync_failed", "extension_disabled", "ownership_transferred", "push_auth_failed"];
102
109
  /** How many items of each type wait: every type, zeros included. */
103
110
  export type PlatformInboxCounts = Record<PlatformInboxItem["type"], number>;
104
- /** An open platform notice (`platform_notices`, kind `ownership_transferred`). */
105
- export interface PlatformNoticeView {
106
- id: string;
107
- kind: "ownership_transferred";
108
- createdAt: string;
109
- detail: PlatformNoticeDetails["ownership_transferred"];
110
- }
111
+ /** An open platform notice (`platform_notices`) of one kind. */
112
+ export type PlatformNoticeView<K extends PlatformNoticeKind = PlatformNoticeKind> = {
113
+ [P in K]: {
114
+ id: string;
115
+ kind: P;
116
+ createdAt: string;
117
+ detail: PlatformNoticeDetails[P];
118
+ };
119
+ }[K];
111
120
  /**
112
121
  * `GET /admin/inbox`: newest first, at most {@link PLATFORM_INBOX_MAX_ITEMS}; `truncated`: more;
113
122
  * `total`: how many items wait in all (also `GET /admin/inbox/count`); `byType`: `total` per
@@ -136,6 +145,7 @@ export declare class PlatformInboxService {
136
145
  * requests and the failures; the permission confirmations are the catalog's pending list).
137
146
  */
138
147
  count(): Promise<number>;
148
+ /** The open platform notices of each kind. */
139
149
  private countNotices;
140
150
  /** The open platform notices, newest first, at most {@link PLATFORM_INBOX_MAX_ITEMS}. */
141
151
  private notices;
@@ -26,6 +26,7 @@ export const PLATFORM_INBOX_TYPES = [
26
26
  "scope_sync_failed",
27
27
  "extension_disabled",
28
28
  "ownership_transferred",
29
+ "push_auth_failed",
29
30
  ];
30
31
  /**
31
32
  * The super admin's inbox (plugin scope spec §5.1 rule 5, §13.5): what waits on the platform,
@@ -79,12 +80,12 @@ let PlatformInboxService = class PlatformInboxService {
79
80
  createdAt: d.since,
80
81
  disabled: d,
81
82
  })),
82
- ...notices.map((n) => ({
83
- type: "ownership_transferred",
84
- id: n.id,
85
- createdAt: n.createdAt,
86
- notice: n,
87
- })),
83
+ ...notices.map((n) =>
84
+ // the same object either way; the branches only narrow `n` so each item type pairs with
85
+ // its own notice kind (TypeScript does not distribute the union through one literal)
86
+ n.kind === "push_auth_failed"
87
+ ? { type: n.kind, id: n.id, createdAt: n.createdAt, notice: n }
88
+ : { type: n.kind, id: n.id, createdAt: n.createdAt, notice: n }),
88
89
  ];
89
90
  // newest first; equal times by id (a stable order)
90
91
  all.sort((a, b) => a.createdAt !== b.createdAt
@@ -103,7 +104,8 @@ let PlatformInboxService = class PlatformInboxService {
103
104
  org_upload_pending: orgUploads,
104
105
  scope_sync_failed: failureCount,
105
106
  extension_disabled: disabledCount,
106
- ownership_transferred: noticeCount,
107
+ ownership_transferred: noticeCount.ownership_transferred,
108
+ push_auth_failed: noticeCount.push_auth_failed,
107
109
  };
108
110
  const total = Object.values(byType).reduce((a, b) => a + b, 0);
109
111
  const items = all.slice(0, PLATFORM_INBOX_MAX_ITEMS);
@@ -121,15 +123,28 @@ let PlatformInboxService = class PlatformInboxService {
121
123
  this.countDisabledExtensions(),
122
124
  this.countNotices(),
123
125
  ]);
124
- return requests + pending.length + failures + disabled + notices;
126
+ return (requests +
127
+ pending.length +
128
+ failures +
129
+ disabled +
130
+ notices.ownership_transferred +
131
+ notices.push_auth_failed);
125
132
  }
133
+ /** The open platform notices of each kind. */
126
134
  async countNotices() {
127
- const r = await this.kdb.db
135
+ const rows = await this.kdb.db
128
136
  .selectFrom("platform_notices")
129
- .select(sql `count(*)`.as("n"))
137
+ .select(["kind", sql `count(*)`.as("n")])
130
138
  .where("dismissed_at", "is", null)
131
- .executeTakeFirstOrThrow();
132
- return Number(r.n);
139
+ .groupBy("kind")
140
+ .execute();
141
+ const counts = {
142
+ ownership_transferred: 0,
143
+ push_auth_failed: 0,
144
+ };
145
+ for (const r of rows)
146
+ counts[r.kind] = Number(r.n);
147
+ return counts;
133
148
  }
134
149
  /** The open platform notices, newest first, at most {@link PLATFORM_INBOX_MAX_ITEMS}. */
135
150
  async notices() {
@@ -1,6 +1,6 @@
1
1
  import type { OwnedRef } from "../catalog/ownership.js";
2
2
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
3
- export type PlatformNoticeKind = "ownership_transferred";
3
+ export type PlatformNoticeKind = "ownership_transferred" | "push_auth_failed";
4
4
  /** The `detail` of each platform notice kind. */
5
5
  export interface PlatformNoticeDetails {
6
6
  /** A deleted org's (or owner's) shared item now belongs to the platform. */
@@ -15,5 +15,19 @@ export interface PlatformNoticeDetails {
15
15
  /** How many other orgs use it. */
16
16
  usedBy: number;
17
17
  };
18
+ /**
19
+ * A push provider's credentials were refused on a delivery (mobile app spec §9.2); at most one
20
+ * open notice per plugin ({@link addPushAuthNotice}).
21
+ */
22
+ push_auth_failed: {
23
+ plugin: string;
24
+ };
18
25
  }
19
26
  export declare function addPlatformNotice<K extends PlatformNoticeKind>(db: KernelSchemaDb, kind: K, detail: PlatformNoticeDetails[K]): Promise<void>;
27
+ /**
28
+ * Tells the super admins that `plugin`'s push credentials were refused, unless a notice of that
29
+ * kind naming the plugin is still open. The partial unique index
30
+ * `platform_notices_push_auth_open_idx` (migration 0173) keeps it at one open notice per plugin
31
+ * even when deliveries on several replicas fail at once.
32
+ */
33
+ export declare function addPushAuthNotice(db: KernelSchemaDb, plugin: string): Promise<void>;
@@ -1,9 +1,29 @@
1
1
  // Platform notices (`platform_notices`, plugin scope phase 3, ruling P3-22): what the super admins
2
2
  // are told, until any one of them dismisses it. Written in the caller's transaction.
3
3
  import { randomUUID } from "node:crypto";
4
+ import { sql } from "kysely";
4
5
  export async function addPlatformNotice(db, kind, detail) {
5
6
  await db
6
7
  .insertInto("platform_notices")
7
8
  .values({ id: randomUUID(), kind, detail: JSON.stringify(detail) })
8
9
  .execute();
9
10
  }
11
+ /**
12
+ * Tells the super admins that `plugin`'s push credentials were refused, unless a notice of that
13
+ * kind naming the plugin is still open. The partial unique index
14
+ * `platform_notices_push_auth_open_idx` (migration 0173) keeps it at one open notice per plugin
15
+ * even when deliveries on several replicas fail at once.
16
+ */
17
+ export async function addPushAuthNotice(db, plugin) {
18
+ const detail = { plugin };
19
+ await db
20
+ .insertInto("platform_notices")
21
+ .values({ id: randomUUID(), kind: "push_auth_failed", detail: JSON.stringify(detail) })
22
+ .onConflict((oc) => oc
23
+ .expression(sql `(detail ->> 'plugin')`)
24
+ // literals, not parameters: PostgreSQL matches the partial index's predicate textually
25
+ .where("kind", "=", sql.lit("push_auth_failed"))
26
+ .where("dismissed_at", "is", null)
27
+ .doNothing())
28
+ .execute();
29
+ }
@@ -74,6 +74,8 @@ const HOT_APPLIERS = {
74
74
  "web.fetch.maxAnswerTokens": () => { },
75
75
  "web.fetch.cacheSeconds": () => { },
76
76
  "web.fetch.timeoutMs": () => { },
77
+ // The push fanout reads the preview setting at every fanout.
78
+ "push.previews": () => { },
77
79
  // Scheduled-task settings are clamped to these bounds on every read.
78
80
  "schedules.minIntervalFloorMinutes": () => { },
79
81
  "schedules.maxTasksPerMemberCap": () => { },