@myrialabs/clopen 0.4.39 → 0.4.41

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 (173) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +29 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -15,6 +15,7 @@ export default defineProvider({
15
15
  description:
16
16
  'Crawls and converts live sites into clean markdown. Pairs with the browser automation tools rather than replacing them — this is for reading a site at scale, not driving one.',
17
17
  docsUrl: 'https://firecrawl.dev',
18
+ consoleUrl: 'https://firecrawl.dev',
18
19
  authMethod: 'api-key',
19
20
  capabilities: ['agent-tools'],
20
21
  credentialFields: [
@@ -39,6 +39,7 @@ export default defineProvider({
39
39
  description:
40
40
  'Issues, pull requests and Actions for the repository this project pushes to. Start work on an issue in its own worktree, open and merge pull requests, and send a failing CI run into the chat.',
41
41
  docsUrl: 'https://github.com/settings/tokens/new?scopes=repo,read:org&description=Clopen',
42
+ consoleUrl: 'https://github.com',
42
43
  authMethod: 'api-key',
43
44
  capabilities: ['work', 'agent-tools'],
44
45
  // Connecting GitHub means "show me my work", not "give every agent GitHub
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Neon — the first provider behind the `worktree-branching` capability, and the
3
+ * second behind `database`.
4
+ *
5
+ * ONE CREDENTIAL, TWO CAPABILITIES, which is the shape this provider was picked
6
+ * to prove. The same API key both lists projects for DB Client and cuts a
7
+ * branch for a worktree, so making it two accounts would mean pasting one key
8
+ * twice and rotating it in two places — the mistake `Task 3` refused for Vercel
9
+ * teams and `Task 4` refused for Supabase projects.
10
+ *
11
+ * Worth knowing about Neon's keys: they come in two scopes. A PERSONAL key
12
+ * reaches the projects its user owns; an ORGANISATION key reaches that
13
+ * organisation's and nothing else. Neither is wrong and the difference is
14
+ * invisible until a project the user can plainly see in the console is missing
15
+ * from the list, so the credential help names it rather than leaving it to be
16
+ * discovered.
17
+ *
18
+ * NO `agent-tools`, even though Neon ships an MCP server. That server uses its
19
+ * own OAuth — a different audience from this REST key — so declaring it would
20
+ * mean projecting a row this credential cannot fill, which is the same reason
21
+ * `Task 3` left Vercel's MCP alone.
22
+ *
23
+ * NO `inbound-events`. Neon's webhooks are an organisation-level billing and
24
+ * usage feed, not something any surface here subscribes to yet.
25
+ */
26
+
27
+ import { defineProvider } from '../define';
28
+
29
+ export default defineProvider({
30
+ id: 'neon',
31
+ name: 'Neon',
32
+ category: 'database',
33
+ description:
34
+ 'Serverless Postgres in DB Client, plus a database branch per worktree: creating a worktree cuts a copy-on-write branch and points its connection string at it, and deleting the worktree deletes the branch.',
35
+ docsUrl: 'https://console.neon.tech/app/settings/api-keys',
36
+ consoleUrl: 'https://console.neon.tech',
37
+ authMethod: 'api-key',
38
+ capabilities: ['database', 'worktree-branching'],
39
+ // Both ON by default. Unlike GitHub's `agent-tools` — which hands an agent
40
+ // write access to every repository and therefore has to be asked for —
41
+ // neither of these does anything until the user points a project at a
42
+ // database, so defaulting them off would only add a step before the feature
43
+ // they connected the account for.
44
+ credentialFields: [
45
+ {
46
+ name: 'apiKey',
47
+ label: 'API key',
48
+ placeholder: 'napi_…',
49
+ help:
50
+ 'Neon console → Account settings → API keys. A PERSONAL key reaches the projects you own; an ORGANISATION key reaches only that organisation\'s. Pick the one that owns the database you want to branch.',
51
+ isSecret: true,
52
+ isRequired: true
53
+ }
54
+ ]
55
+ });
@@ -40,6 +40,7 @@ export default defineProvider({
40
40
  description:
41
41
  'Postgres projects as connections in DB Client, with the Supabase surface on top: migrations and what is still pending, RLS policies and the security advisor, edge functions, storage buckets, auth users, and generated TypeScript types written into the project.',
42
42
  docsUrl: 'https://supabase.com/dashboard/account/tokens',
43
+ consoleUrl: 'https://supabase.com/dashboard',
43
44
  authMethod: 'api-key',
44
45
  capabilities: ['database'],
45
46
  credentialFields: [
@@ -28,6 +28,7 @@ export default defineProvider({
28
28
  description:
29
29
  'Deployments for the project this repository builds to. Watch a build as it runs, send a failed build log into the chat, open a preview build in the browser panel, and redeploy, cancel, roll back or promote from here.',
30
30
  docsUrl: 'https://vercel.com/account/tokens',
31
+ consoleUrl: 'https://vercel.com/dashboard',
31
32
  authMethod: 'api-key',
32
33
  capabilities: ['deployments'],
33
34
  credentialFields: [
@@ -83,6 +83,8 @@ export interface IntegrationProvider {
83
83
  category: IntegrationCategory;
84
84
  description: string;
85
85
  docsUrl?: string;
86
+ /** The provider's own dashboard, for what Clopen cannot do — see `IntegrationProviderInfo`. */
87
+ consoleUrl?: string;
86
88
  authMethod: IntegrationAuthMethod;
87
89
  credentialFields: IntegrationCredentialField[];
88
90
  /** Everything this provider is able to offer. */
@@ -27,7 +27,7 @@
27
27
 
28
28
  import { graphQueries } from '$backend/database/queries/graph-queries';
29
29
  import { initializeEngine } from '$backend/engine';
30
- import { resolveGenerationTarget } from '$backend/engine/resolve-model';
30
+ import { resolveGenerationTarget, GENERATION_SETTINGS } from '$backend/engine/resolve-model';
31
31
  import { debug } from '$shared/utils/logger';
32
32
  import type { EpisodicSubkind, GraphNode, MemoryDraft } from '$shared/types/memory';
33
33
  import { getMemoryConfig, type MemoryModelConfig } from './config';
@@ -299,7 +299,7 @@ ${text}`;
299
299
  const engine = await initializeEngine(model.engine);
300
300
  if (!engine.generateStructured) return null;
301
301
 
302
- const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
302
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug, GENERATION_SETTINGS.memory);
303
303
  const accountId = model.accountId ?? target.accountId;
304
304
 
305
305
  const result = await engine.generateStructured<{
@@ -28,7 +28,7 @@ import Graph from 'graphology';
28
28
  import louvain from 'graphology-communities-louvain';
29
29
  import { graphQueries } from '$backend/database/queries/graph-queries';
30
30
  import { initializeEngine } from '$backend/engine';
31
- import { resolveGenerationTarget } from '$backend/engine/resolve-model';
31
+ import { resolveGenerationTarget, GENERATION_SETTINGS } from '$backend/engine/resolve-model';
32
32
  import { debug } from '$shared/utils/logger';
33
33
  import { getMemoryConfig, type MemoryModelConfig } from './config';
34
34
  import { notifyGraphChanged } from './notify';
@@ -261,7 +261,7 @@ ${listing}`).text;
261
261
  const engine = await initializeEngine(model.engine);
262
262
  if (!engine.generateStructured) return null;
263
263
 
264
- const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
264
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug, GENERATION_SETTINGS.memory);
265
265
  const accountId = model.accountId ?? target.accountId;
266
266
 
267
267
  return await engine.generateStructured<Summary>({
@@ -36,7 +36,7 @@ import { join } from 'node:path';
36
36
  import { messageQueries } from '$backend/database/queries/message-queries';
37
37
  import { graphQueries } from '$backend/database/queries/graph-queries';
38
38
  import { initializeEngine } from '$backend/engine';
39
- import { resolveGenerationTarget } from '$backend/engine/resolve-model';
39
+ import { resolveGenerationTarget, GENERATION_SETTINGS } from '$backend/engine/resolve-model';
40
40
  import { getClopenDir } from '$backend/utils/paths';
41
41
  import { debug } from '$shared/utils/logger';
42
42
  import type {
@@ -679,7 +679,7 @@ async function requestExtraction(model: MemoryModelConfig, prompt: string): Prom
679
679
 
680
680
  // The stored providerSlug/accountId can be stale — a model may have moved
681
681
  // provider or the account may be gone (see resolve-model.ts).
682
- const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
682
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug, GENERATION_SETTINGS.memory);
683
683
  const accountId = model.accountId ?? target.accountId;
684
684
 
685
685
  const abortController = new AbortController();
@@ -25,7 +25,7 @@
25
25
  */
26
26
 
27
27
  import { initializeEngine } from '$backend/engine';
28
- import { resolveGenerationTarget } from '$backend/engine/resolve-model';
28
+ import { resolveGenerationTarget, GENERATION_SETTINGS } from '$backend/engine/resolve-model';
29
29
  import { getDatabase } from '$backend/database';
30
30
  import { graphQueries } from '$backend/database/queries/graph-queries';
31
31
  import { debug } from '$shared/utils/logger';
@@ -62,7 +62,7 @@ async function generate<T>(model: MemoryModelConfig, prompt: string, schema: Rec
62
62
  try {
63
63
  const engine = await initializeEngine(model.engine);
64
64
  if (!engine.generateStructured) return null;
65
- const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
65
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug, GENERATION_SETTINGS.memory);
66
66
  const accountId = model.accountId ?? target.accountId;
67
67
  return await engine.generateStructured<T>({
68
68
  prompt,
@@ -3,7 +3,7 @@
3
3
  * resolution consumed by the artifact/MCP sync path.
4
4
  *
5
5
  * A Profile is a reusable, named set of references to existing artifacts
6
- * (Skills, Commands, Subagents, Integrations). It NARROWS which of the
6
+ * (Skills, Subagents, Integrations). It NARROWS which of the
7
7
  * instance-global artifacts are active for a session, without duplicating any
8
8
  * artifact data — `profile_items` only stores slugs.
9
9
  *
@@ -20,14 +20,14 @@
20
20
  * also when there is no active profile at all;
21
21
  * - a `Set<slug>` when the profile references ≥1 item → the sync intersects its
22
22
  * enabled set with these slugs.
23
- * This means a profile that only curates Commands never silently disables every
23
+ * This means a profile that only curates Subagents never silently disables every
24
24
  * Skill, and a NULL/absent profile behaves exactly like today.
25
25
  */
26
26
 
27
27
  import { profileQueries, projectQueries, mcpServerQueries } from '$backend/database/queries';
28
28
  import type { ProfileItemType, ProfileItemInput } from '$backend/database/queries';
29
29
  import { PROFILE_ITEM_TYPES } from '$backend/database/queries';
30
- import { skillQueries, commandQueries, subagentQueries } from '$backend/database/queries';
30
+ import { skillQueries, subagentQueries } from '$backend/database/queries';
31
31
  import { debug } from '$shared/utils/logger';
32
32
 
33
33
  /** A profile with its items grouped by type, for the Settings UI. */
@@ -53,7 +53,7 @@ export interface ProfileInventoryEntry {
53
53
  export type ProfileInventory = Record<ProfileItemType, ProfileInventoryEntry[]>;
54
54
 
55
55
  function emptyItems(): Record<ProfileItemType, string[]> {
56
- return { skill: [], command: [], subagent: [], mcp: [] };
56
+ return { skill: [], subagent: [], mcp: [] };
57
57
  }
58
58
 
59
59
  function toDTO(id: number): ProfileDTO | null {
@@ -133,9 +133,10 @@ export const profileService = {
133
133
 
134
134
  /** Artifacts selectable in the profile editor, grouped by type. */
135
135
  inventory(): ProfileInventory {
136
- const inv: ProfileInventory = { skill: [], command: [], subagent: [], mcp: [] };
136
+ const inv: ProfileInventory = { skill: [], subagent: [], mcp: [] };
137
+ // Skills cover both model-invoked skills and `/slash` prompts since the
138
+ // merge, so one entry per skill is the whole artifact surface here.
137
139
  for (const s of skillQueries.getAll()) inv.skill.push({ slug: s.slug, name: s.name, enabled: s.is_enabled === 1 });
138
- for (const c of commandQueries.getAll()) inv.command.push({ slug: c.slug, name: c.name, enabled: c.is_enabled === 1 });
139
140
  for (const a of subagentQueries.getAll()) inv.subagent.push({ slug: a.slug, name: a.name, enabled: a.is_enabled === 1 });
140
141
  // Both external AND built-in (internal) connectors are selectable — a profile
141
142
  // can scope Clopen's own tools (e.g. browser-automation) too.
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Web Push fan-out.
3
+ *
4
+ * `sendPushToUser()` is the only entry point the chat layer needs: it loads
5
+ * every subscription the user registered (one per mobile device), encrypts
6
+ * the payload per subscription, and POSTs to each push service. It never
7
+ * throws — a dead endpoint or a down push service must not fail a chat turn.
8
+ *
9
+ * Dead subscriptions prune themselves: push services answer 404/410 for an
10
+ * expired endpoint, and those rows are deleted on sight.
11
+ */
12
+
13
+ import { debug } from '$shared/utils/logger';
14
+ import { pushSubscriptionQueries, type PushSubscription } from '../database/queries/push-subscription-queries';
15
+ import {
16
+ base64UrlDecode,
17
+ createVapidAuthorizationHeader,
18
+ encryptPushPayload
19
+ } from './webpush-crypto';
20
+ import { getVapidKeys, getVapidSubject } from './vapid-keys';
21
+ import { PUSH_TTL_SECONDS } from '$shared/constants/notification-messages';
22
+
23
+ export interface PushPayload {
24
+ title: string;
25
+ body: string;
26
+ /** Deterministic per event so a server copy replaces (not stacks with) the local one. */
27
+ tag: string;
28
+ /** Where tapping the notification lands. Defaults to `/`. */
29
+ url?: string;
30
+ }
31
+
32
+ /**
33
+ * Push services cap a record at 4096 bytes, and that budget covers the
34
+ * ciphertext, not the JSON. Project names are user-supplied and unbounded, so
35
+ * a long one would otherwise turn a chat completion into a 413 from the push
36
+ * service. Clamping here keeps the failure impossible rather than rare.
37
+ */
38
+ const MAX_TITLE_CHARS = 120;
39
+ const MAX_BODY_CHARS = 400;
40
+ const MAX_URL_CHARS = 512;
41
+
42
+ function clamp(value: string, max: number): string {
43
+ return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
44
+ }
45
+
46
+ function encodePayload(payload: PushPayload): Uint8Array {
47
+ return new TextEncoder().encode(
48
+ JSON.stringify({
49
+ title: clamp(payload.title, MAX_TITLE_CHARS),
50
+ body: clamp(payload.body, MAX_BODY_CHARS),
51
+ tag: payload.tag,
52
+ url: clamp(payload.url ?? '/', MAX_URL_CHARS)
53
+ })
54
+ );
55
+ }
56
+
57
+ /**
58
+ * POST one encrypted push. Returns `'sent'`, `'stale'` (endpoint expired —
59
+ * caller deletes the row), or `'failed'` (transient; keep the row).
60
+ */
61
+ async function postPush(
62
+ subscription: PushSubscription,
63
+ payload: PushPayload
64
+ ): Promise<'sent' | 'stale' | 'failed'> {
65
+ let audience: string;
66
+ try {
67
+ audience = new URL(subscription.endpoint).origin;
68
+ } catch {
69
+ return 'stale';
70
+ }
71
+
72
+ let body: Uint8Array<ArrayBuffer>;
73
+ try {
74
+ ({ body } = await encryptPushPayload(
75
+ subscription.p256dh,
76
+ subscription.auth,
77
+ encodePayload(payload)
78
+ ));
79
+ } catch (error) {
80
+ debug.warn(
81
+ 'notification',
82
+ `Dropping subscription with undecryptable keys for user ${subscription.user_id}:`,
83
+ error
84
+ );
85
+ return 'stale';
86
+ }
87
+
88
+ let authorization: string;
89
+ try {
90
+ authorization = await createVapidAuthorizationHeader(
91
+ audience,
92
+ getVapidSubject(),
93
+ await getVapidKeys()
94
+ );
95
+ } catch (error) {
96
+ debug.warn('notification', 'Failed to sign VAPID JWT:', error);
97
+ return 'failed';
98
+ }
99
+
100
+ let response: Response;
101
+ try {
102
+ response = await fetch(subscription.endpoint, {
103
+ method: 'POST',
104
+ headers: {
105
+ 'Content-Type': 'application/octet-stream',
106
+ 'Content-Encoding': 'aes128gcm',
107
+ Authorization: authorization,
108
+ TTL: String(PUSH_TTL_SECONDS),
109
+ Urgency: 'normal'
110
+ },
111
+ body
112
+ });
113
+ } catch (error) {
114
+ debug.warn('notification', `Push service unreachable for user ${subscription.user_id}:`, error);
115
+ return 'failed';
116
+ }
117
+
118
+ if (response.status === 404 || response.status === 410) return 'stale';
119
+ if (response.status === 413) {
120
+ debug.warn('notification', `Push payload too large for user ${subscription.user_id}`);
121
+ return 'failed';
122
+ }
123
+ if (!response.ok) {
124
+ debug.warn('notification', `Push service answered ${response.status} for user ${subscription.user_id}`);
125
+ return 'failed';
126
+ }
127
+ return 'sent';
128
+ }
129
+
130
+ /**
131
+ * Notify every device a user registered. Resolves to how many pushes the
132
+ * services accepted. Never rejects.
133
+ */
134
+ export async function sendPushToUser(userId: string, payload: PushPayload): Promise<number> {
135
+ let subscriptions: PushSubscription[];
136
+ try {
137
+ subscriptions = pushSubscriptionQueries.listByUser(userId);
138
+ } catch (error) {
139
+ debug.warn('notification', `Failed to load subscriptions for user ${userId}:`, error);
140
+ return 0;
141
+ }
142
+ if (subscriptions.length === 0) return 0;
143
+
144
+ let sent = 0;
145
+ for (const subscription of subscriptions) {
146
+ try {
147
+ const outcome = await postPush(subscription, payload);
148
+ if (outcome === 'sent') {
149
+ sent += 1;
150
+ } else if (outcome === 'stale') {
151
+ try {
152
+ pushSubscriptionQueries.deleteStaleByEndpoint(subscription.endpoint);
153
+ } catch (error) {
154
+ debug.warn('notification', 'Failed to prune stale subscription:', error);
155
+ }
156
+ }
157
+ } catch (error) {
158
+ debug.warn('notification', 'Unexpected push failure:', error);
159
+ }
160
+ }
161
+ return sent;
162
+ }
163
+
164
+ /** Validate the two key fields of an incoming subscription before storing. */
165
+ export function isValidSubscriptionKeys(p256dh: unknown, auth: unknown): boolean {
166
+ if (typeof p256dh !== 'string' || typeof auth !== 'string') return false;
167
+ try {
168
+ return base64UrlDecode(p256dh).length === 65 && base64UrlDecode(auth).length >= 16;
169
+ } catch {
170
+ return false;
171
+ }
172
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Server-side notification tags.
3
+ *
4
+ * A tag is identity, not a label: a push whose tag matches the on-screen
5
+ * toast replaces it. Chat events therefore carry deterministic tags —
6
+ * `chat-<streamId>`, `waiting-<toolUseId>` — so the server copy replaces the
7
+ * local copy the open tab already showed (or appears alone when Chrome is
8
+ * closed), instead of stacking a duplicate. Test pushes get a unique tag per
9
+ * attempt so rapid retests never swallow each other.
10
+ */
11
+
12
+ let tagCounter = 0;
13
+
14
+ export function uniquePushTag(prefix: string): string {
15
+ tagCounter += 1;
16
+ return `${prefix}-${Date.now()}-${tagCounter}`;
17
+ }
18
+
19
+ export function chatStreamPushTag(streamId: string): string {
20
+ return `chat-${streamId}`;
21
+ }
22
+
23
+ export function waitingInputPushTag(toolUseId: string): string {
24
+ return `waiting-${toolUseId}`;
25
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * VAPID identity for this server.
3
+ *
4
+ * VAPID is not optional decoration: every push request must carry an
5
+ * ES256-signed JWT proving which server sent it, or the push service answers
6
+ * 401, and the same public key is what binds a browser's subscription to
7
+ * this server so nobody else can push to that device. What IS optional is
8
+ * the operator's involvement — a keypair is generated on first use and
9
+ * persisted in the `settings` table, so push needs no configuration at all.
10
+ *
11
+ * There is deliberately no env-var override. Keys and subscriptions live in
12
+ * the same database, so they are created and wiped together and a key can
13
+ * never go stale against rows that outlived it — which is the only thing an
14
+ * externally-provisioned key would have bought.
15
+ *
16
+ * Auto-generation (rather than failing closed) is likewise deliberate: push
17
+ * is an opt-in per-device feature, and a missing key must never break boot.
18
+ */
19
+
20
+ import { debug } from '$shared/utils/logger';
21
+ import { settingsQueries } from '../database/queries/settings-queries';
22
+ import { base64UrlDecode, generateVapidKeypair, type VapidKeypair } from './webpush-crypto';
23
+
24
+ const SETTINGS_KEY = 'push:vapid_keys';
25
+
26
+ function readStoredKeys(): VapidKeypair | null {
27
+ try {
28
+ const row = settingsQueries.get(SETTINGS_KEY);
29
+ if (!row) return null;
30
+ const parsed = JSON.parse(row.value) as Partial<VapidKeypair>;
31
+ if (typeof parsed.publicKey !== 'string' || typeof parsed.privateKey !== 'string') {
32
+ return null;
33
+ }
34
+ if (base64UrlDecode(parsed.publicKey).length !== 65) return null;
35
+ if (base64UrlDecode(parsed.privateKey).length !== 32) return null;
36
+ return { publicKey: parsed.publicKey, privateKey: parsed.privateKey };
37
+ } catch (error) {
38
+ debug.warn('notification', 'Ignoring unreadable stored VAPID keys:', error);
39
+ return null;
40
+ }
41
+ }
42
+
43
+ let cached: VapidKeypair | null = null;
44
+
45
+ /** Server VAPID identity, generating + persisting one on first use. */
46
+ export async function getVapidKeys(): Promise<VapidKeypair> {
47
+ if (cached) return cached;
48
+
49
+ cached = readStoredKeys();
50
+ if (cached) return cached;
51
+
52
+ const fresh = await generateVapidKeypair();
53
+ try {
54
+ settingsQueries.set(SETTINGS_KEY, JSON.stringify(fresh));
55
+ } catch (error) {
56
+ // The keys still work for this process lifetime; persistence is retry
57
+ // -able on the next call rather than fatal now.
58
+ debug.warn('notification', 'Failed to persist generated VAPID keys:', error);
59
+ }
60
+ cached = fresh;
61
+ return cached;
62
+ }
63
+
64
+ /**
65
+ * Contact for the VAPID JWT `sub` claim.
66
+ *
67
+ * RFC 8292 wants a `mailto:` or `https:` URI a push service operator could
68
+ * use to reach whoever is sending. A self-hosted instance has no such
69
+ * address, so this points at the project rather than inventing an
70
+ * undeliverable mailbox — and it is a constant precisely so that nobody has
71
+ * to configure it.
72
+ */
73
+ const VAPID_SUBJECT = 'https://github.com/myrialabs/clopen';
74
+
75
+ export function getVapidSubject(): string {
76
+ return VAPID_SUBJECT;
77
+ }