@myrialabs/clopen 0.4.40 → 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.
- package/.env.example +1 -1
- package/backend/artifacts/detect.ts +15 -3
- package/backend/artifacts/generate.ts +2 -2
- package/backend/artifacts/index.ts +12 -4
- package/backend/artifacts/markers.ts +24 -1
- package/backend/artifacts/matrix.ts +47 -3
- package/backend/artifacts/sync.test.ts +3 -3
- package/backend/artifacts/sync.ts +8 -20
- package/backend/artifacts/types.ts +9 -3
- package/backend/auth/permissions.ts +6 -11
- package/backend/auth/session-cleanup.ts +10 -1
- package/backend/auth/tokens.ts +9 -1
- package/backend/chat/stream-manager.ts +42 -0
- package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
- package/backend/database/migrations/080_create_file_shares.ts +111 -0
- package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/database/queries/file-share-queries.ts +163 -0
- package/backend/database/queries/index.ts +6 -4
- package/backend/database/queries/profile-queries.ts +5 -3
- package/backend/database/queries/push-subscription-queries.test.ts +90 -0
- package/backend/database/queries/push-subscription-queries.ts +99 -0
- package/backend/database/queries/skill-queries.ts +96 -18
- package/backend/engine/adapters/claude/stream.ts +2 -1
- package/backend/engine/adapters/cline/stream.ts +3 -3
- package/backend/engine/adapters/codex/stream.ts +3 -3
- package/backend/engine/adapters/copilot/stream.ts +3 -3
- package/backend/engine/adapters/cursor/stream.ts +25 -3
- package/backend/engine/adapters/opencode/stream.ts +4 -6
- package/backend/engine/adapters/pi/stream.ts +2 -2
- package/backend/engine/adapters/qwen/stream.ts +2 -2
- package/backend/engine/artifact-sync.ts +26 -20
- package/backend/engine/docs/artifacts.md +81 -22
- package/backend/engine/docs/quick-reference.md +2 -1
- package/backend/engine/resolve-model.test.ts +108 -0
- package/backend/engine/resolve-model.ts +53 -10
- package/backend/engine/structured-helpers.ts +22 -0
- package/backend/files/file-shares.ts +369 -0
- package/backend/files/path-browsing.ts +27 -21
- package/backend/http/files-shared.test.ts +505 -0
- package/backend/http/files-shared.ts +351 -0
- package/backend/http/push.ts +150 -0
- package/backend/index.ts +8 -0
- package/backend/instructions/index.ts +1 -1
- package/backend/instructions/sync.ts +30 -6
- package/backend/memory/compose.ts +2 -2
- package/backend/memory/consolidate.ts +2 -2
- package/backend/memory/extract/episodic.ts +2 -2
- package/backend/memory/judge.ts +2 -2
- package/backend/profiles/service.ts +7 -6
- package/backend/push/sender.ts +172 -0
- package/backend/push/tags.ts +25 -0
- package/backend/push/vapid-keys.ts +77 -0
- package/backend/push/webpush-crypto.test.ts +200 -0
- package/backend/push/webpush-crypto.ts +231 -0
- package/backend/skills/detect.ts +28 -0
- package/backend/skills/index.ts +22 -4
- package/backend/skills/invoke.test.ts +114 -0
- package/backend/skills/invoke.ts +222 -0
- package/backend/skills/service.ts +194 -44
- package/backend/skills/spec.ts +35 -0
- package/backend/skills/sync.ts +85 -55
- package/backend/subagents/detect.ts +2 -3
- package/backend/subagents/sync.ts +15 -8
- package/backend/work/pull-requests.ts +2 -2
- package/backend/ws/chat/stream.ts +100 -8
- package/backend/ws/files/index.ts +4 -0
- package/backend/ws/files/share.ts +95 -0
- package/backend/ws/git/branch-name.ts +2 -2
- package/backend/ws/git/commit-message.ts +2 -2
- package/backend/ws/index.ts +3 -4
- package/backend/ws/profiles/crud.ts +2 -3
- package/backend/ws/skills/catalog.ts +5 -1
- package/backend/ws/skills/crud.ts +128 -22
- package/backend/ws/skills/index.ts +4 -1
- package/backend/ws/user/crud.ts +12 -3
- package/dist/assets/{index-D4igjF6e.js → index-CeNKKSDR.js} +1 -1
- package/dist/assets/{index-DONNwiXm.js → index-DW89566K.js} +1 -1
- package/dist/assets/{main-BrfXH1bL.js → main-Cy5DXWPT.js} +592 -590
- package/dist/assets/main-DJKj_4By.css +1 -0
- package/dist/index.html +7 -2
- package/dist/sw.js +112 -0
- package/package.json +1 -1
- package/shared/constants/engine-tools.ts +31 -6
- package/shared/constants/notification-messages.ts +142 -0
- package/shared/types/unified/stream.ts +7 -0
- package/backend/commands/detect.ts +0 -25
- package/backend/commands/index.ts +0 -9
- package/backend/commands/service.ts +0 -178
- package/backend/commands/store.ts +0 -45
- package/backend/commands/sync.ts +0 -94
- package/backend/database/queries/command-queries.ts +0 -82
- package/backend/ws/commands/crud.ts +0 -157
- package/backend/ws/commands/index.ts +0 -8
- package/dist/assets/main-CT1PygsW.css +0 -1
|
@@ -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,
|
|
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
|
|
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,
|
|
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: [],
|
|
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: [],
|
|
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
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
base64UrlDecode,
|
|
5
|
+
base64UrlEncode,
|
|
6
|
+
createVapidAuthorizationHeader,
|
|
7
|
+
encryptPushPayload,
|
|
8
|
+
generateVapidKeypair
|
|
9
|
+
} from './webpush-crypto';
|
|
10
|
+
|
|
11
|
+
const textEncoder = new TextEncoder();
|
|
12
|
+
const textDecoder = new TextDecoder();
|
|
13
|
+
|
|
14
|
+
function concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
|
|
15
|
+
const total = parts.reduce((sum, part) => sum + part.length, 0);
|
|
16
|
+
const out = new Uint8Array(total);
|
|
17
|
+
let offset = 0;
|
|
18
|
+
for (const part of parts) {
|
|
19
|
+
out.set(part, offset);
|
|
20
|
+
offset += part.length;
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function hmac(
|
|
26
|
+
key: Uint8Array<ArrayBuffer>,
|
|
27
|
+
data: Uint8Array<ArrayBuffer>
|
|
28
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
29
|
+
const hmacKey = await crypto.subtle.importKey(
|
|
30
|
+
'raw',
|
|
31
|
+
key,
|
|
32
|
+
{ name: 'HMAC', hash: 'SHA-256' },
|
|
33
|
+
false,
|
|
34
|
+
['sign']
|
|
35
|
+
);
|
|
36
|
+
return new Uint8Array(await crypto.subtle.sign('HMAC', hmacKey, data));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Independent HKDF (manual HMAC Extract + Expand) — deliberately NOT the
|
|
41
|
+
* module's native-HKDF path, so agreement between the two proves the math
|
|
42
|
+
* rather than repeating the same code.
|
|
43
|
+
*/
|
|
44
|
+
async function hkdfManual(
|
|
45
|
+
salt: Uint8Array<ArrayBuffer>,
|
|
46
|
+
ikm: Uint8Array<ArrayBuffer>,
|
|
47
|
+
info: Uint8Array<ArrayBuffer>,
|
|
48
|
+
length: number
|
|
49
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
50
|
+
const prk = await hmac(salt, ikm);
|
|
51
|
+
return (await hmac(prk, concat(info, new Uint8Array([0x01])))).slice(0, length);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Simulate the browser side: generate a subscription keypair + auth secret. */
|
|
55
|
+
async function makeBrowserSubscription() {
|
|
56
|
+
const keypair = await crypto.subtle.generateKey(
|
|
57
|
+
{ name: 'ECDH', namedCurve: 'P-256' },
|
|
58
|
+
true,
|
|
59
|
+
['deriveBits']
|
|
60
|
+
);
|
|
61
|
+
const publicBytes = new Uint8Array(await crypto.subtle.exportKey('raw', keypair.publicKey));
|
|
62
|
+
const authSecret = crypto.getRandomValues(new Uint8Array(16));
|
|
63
|
+
return {
|
|
64
|
+
privateKey: keypair.privateKey,
|
|
65
|
+
p256dh: base64UrlEncode(publicBytes),
|
|
66
|
+
auth: base64UrlEncode(authSecret),
|
|
67
|
+
authBytes: authSecret
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
describe('base64url', () => {
|
|
72
|
+
test('round-trips arbitrary bytes without padding', () => {
|
|
73
|
+
const bytes = crypto.getRandomValues(new Uint8Array(65));
|
|
74
|
+
expect(base64UrlDecode(base64UrlEncode(bytes))).toEqual(bytes);
|
|
75
|
+
expect(base64UrlEncode(bytes)).not.toContain('=');
|
|
76
|
+
expect(base64UrlEncode(bytes)).not.toMatch(/[+/]/);
|
|
77
|
+
});
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
describe('VAPID', () => {
|
|
81
|
+
test('generates a 65-byte uncompressed public key', async () => {
|
|
82
|
+
const keypair = await generateVapidKeypair();
|
|
83
|
+
const pub = base64UrlDecode(keypair.publicKey);
|
|
84
|
+
expect(pub.length).toBe(65);
|
|
85
|
+
expect(pub[0]).toBe(0x04);
|
|
86
|
+
expect(base64UrlDecode(keypair.privateKey).length).toBe(32);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('produces a verifiable ES256 JWT with aud/exp/sub', async () => {
|
|
90
|
+
const keypair = await generateVapidKeypair();
|
|
91
|
+
const header = await createVapidAuthorizationHeader(
|
|
92
|
+
'https://fcm.googleapis.com',
|
|
93
|
+
'mailto:admin@example.com',
|
|
94
|
+
keypair
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
expect(header).toStartWith('vapid t=');
|
|
98
|
+
const token = header.slice('vapid t='.length).split(', k=')[0];
|
|
99
|
+
const [headerB64, claimsB64, signatureB64] = token.split('.');
|
|
100
|
+
expect(JSON.parse(textDecoder.decode(base64UrlDecode(headerB64)))).toEqual({
|
|
101
|
+
typ: 'JWT',
|
|
102
|
+
alg: 'ES256'
|
|
103
|
+
});
|
|
104
|
+
const claims = JSON.parse(textDecoder.decode(base64UrlDecode(claimsB64)));
|
|
105
|
+
expect(claims.aud).toBe('https://fcm.googleapis.com');
|
|
106
|
+
expect(claims.sub).toBe('mailto:admin@example.com');
|
|
107
|
+
expect(claims.exp).toBeGreaterThan(Math.floor(Date.now() / 1000));
|
|
108
|
+
|
|
109
|
+
const pubBytes = base64UrlDecode(keypair.publicKey);
|
|
110
|
+
const publicKey = await crypto.subtle.importKey(
|
|
111
|
+
'jwk',
|
|
112
|
+
{
|
|
113
|
+
kty: 'EC',
|
|
114
|
+
crv: 'P-256',
|
|
115
|
+
x: base64UrlEncode(pubBytes.slice(1, 33)),
|
|
116
|
+
y: base64UrlEncode(pubBytes.slice(33, 65))
|
|
117
|
+
},
|
|
118
|
+
{ name: 'ECDSA', namedCurve: 'P-256' },
|
|
119
|
+
false,
|
|
120
|
+
['verify']
|
|
121
|
+
);
|
|
122
|
+
const valid = await crypto.subtle.verify(
|
|
123
|
+
{ name: 'ECDSA', hash: 'SHA-256' },
|
|
124
|
+
publicKey,
|
|
125
|
+
base64UrlDecode(signatureB64),
|
|
126
|
+
textEncoder.encode(`${headerB64}.${claimsB64}`)
|
|
127
|
+
);
|
|
128
|
+
expect(valid).toBe(true);
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
describe('encryptPushPayload', () => {
|
|
133
|
+
test('encrypts so the subscription owner can decrypt (full round-trip)', async () => {
|
|
134
|
+
const sub = await makeBrowserSubscription();
|
|
135
|
+
const payload = textEncoder.encode(
|
|
136
|
+
JSON.stringify({ title: 'Response ready', body: 'MyApp — "Fix login bug"', tag: 't-1' })
|
|
137
|
+
);
|
|
138
|
+
|
|
139
|
+
const { body } = await encryptPushPayload(sub.p256dh, sub.auth, payload);
|
|
140
|
+
|
|
141
|
+
// Header + ciphertext overhead: 86-byte header, payload + 1 delimiter + 16 tag.
|
|
142
|
+
expect(body.length).toBe(86 + payload.length + 1 + 16);
|
|
143
|
+
|
|
144
|
+
// --- browser side, independent code path ---
|
|
145
|
+
const salt = body.slice(0, 16);
|
|
146
|
+
const serverPublicBytes = body.slice(21, 86);
|
|
147
|
+
const ciphertext = body.slice(86);
|
|
148
|
+
const clientPublicBytes = base64UrlDecode(sub.p256dh);
|
|
149
|
+
|
|
150
|
+
const serverPublicKey = await crypto.subtle.importKey(
|
|
151
|
+
'raw',
|
|
152
|
+
serverPublicBytes,
|
|
153
|
+
{ name: 'ECDH', namedCurve: 'P-256' },
|
|
154
|
+
false,
|
|
155
|
+
[]
|
|
156
|
+
);
|
|
157
|
+
const sharedSecret = new Uint8Array(
|
|
158
|
+
await crypto.subtle.deriveBits(
|
|
159
|
+
{ name: 'ECDH', public: serverPublicKey },
|
|
160
|
+
sub.privateKey,
|
|
161
|
+
256
|
|
162
|
+
)
|
|
163
|
+
);
|
|
164
|
+
const keyInfo = concat(
|
|
165
|
+
textEncoder.encode('WebPush: info\0'),
|
|
166
|
+
clientPublicBytes,
|
|
167
|
+
serverPublicBytes
|
|
168
|
+
);
|
|
169
|
+
const secret = await hkdfManual(sub.authBytes, sharedSecret, keyInfo, 32);
|
|
170
|
+
const cek = await hkdfManual(
|
|
171
|
+
salt,
|
|
172
|
+
secret,
|
|
173
|
+
textEncoder.encode('Content-Encoding: aes128gcm\0'),
|
|
174
|
+
16
|
|
175
|
+
);
|
|
176
|
+
const nonce = await hkdfManual(
|
|
177
|
+
salt,
|
|
178
|
+
secret,
|
|
179
|
+
textEncoder.encode('Content-Encoding: nonce\0'),
|
|
180
|
+
12
|
|
181
|
+
);
|
|
182
|
+
const aesKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']);
|
|
183
|
+
const plaintext = new Uint8Array(
|
|
184
|
+
await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, aesKey, ciphertext)
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
expect(plaintext[plaintext.length - 1]).toBe(0x02);
|
|
188
|
+
expect(textDecoder.decode(plaintext.slice(0, -1))).toBe(textDecoder.decode(payload));
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test('rejects malformed subscription keys', async () => {
|
|
192
|
+
const sub = await makeBrowserSubscription();
|
|
193
|
+
await expect(
|
|
194
|
+
encryptPushPayload('not-a-key', sub.auth, new Uint8Array([1]))
|
|
195
|
+
).rejects.toThrow();
|
|
196
|
+
await expect(
|
|
197
|
+
encryptPushPayload(sub.p256dh, base64UrlEncode(new Uint8Array([1, 2])), new Uint8Array([1]))
|
|
198
|
+
).rejects.toThrow();
|
|
199
|
+
});
|
|
200
|
+
});
|