forked from Vero-protocol/vero-guardian-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpush.ts
More file actions
196 lines (171 loc) · 4.44 KB
/
Copy pathpush.ts
File metadata and controls
196 lines (171 loc) · 4.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
type PushSubscription = {
endpoint: string;
keys: {
p256dh: string;
auth: string;
};
};
export type PushNotification = {
title: string;
body: string;
icon?: string;
tag?: string;
data?: Record<string, unknown>;
};
const STORAGE_KEY = 'vero_push_subscriptions';
const ENCRYPTION_KEY = 'vero_push_encryption';
async function encryptData(data: string): Promise<string> {
if (typeof window === 'undefined' || !window.crypto?.subtle) {
return btoa(data);
}
const encoder = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(ENCRYPTION_KEY),
{ name: 'PBKDF2' },
false,
['deriveKey'],
);
const derivedKey = await crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: encoder.encode('vero-salt'),
iterations: 100000,
hash: 'SHA-256',
},
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
derivedKey,
encoder.encode(data),
);
const combined = new Uint8Array(iv.length + encrypted.byteLength);
combined.set(iv);
combined.set(new Uint8Array(encrypted), iv.length);
return btoa(String.fromCharCode(...combined));
}
async function decryptData(encryptedData: string): Promise<string> {
if (typeof window === 'undefined' || !window.crypto?.subtle) {
return atob(encryptedData);
}
const encoder = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(ENCRYPTION_KEY),
{ name: 'PBKDF2' },
false,
['deriveKey'],
);
const derivedKey = await crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: encoder.encode('vero-salt'),
iterations: 100000,
hash: 'SHA-256',
},
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
const combined = Uint8Array.from(atob(encryptedData), (c) => c.charCodeAt(0));
const iv = combined.slice(0, 12);
const dataBuffer = combined.slice(12);
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
derivedKey,
dataBuffer,
);
return new TextDecoder().decode(decrypted);
}
export async function savePushSubscription(subscription: PushSubscription): Promise<void> {
if (typeof window === 'undefined') {
return;
}
const serialized = JSON.stringify(subscription);
const encrypted = await encryptData(serialized);
try {
localStorage.setItem(STORAGE_KEY, encrypted);
} catch {
// Ignore storage failures in private or disabled-storage contexts.
}
}
export async function getPushSubscription(): Promise<PushSubscription | null> {
if (typeof window === 'undefined') {
return null;
}
let encrypted: string | null = null;
try {
encrypted = localStorage.getItem(STORAGE_KEY);
} catch {
return null;
}
if (!encrypted) {
return null;
}
try {
const decrypted = await decryptData(encrypted);
return JSON.parse(decrypted) as PushSubscription;
} catch {
try {
localStorage.removeItem(STORAGE_KEY);
} catch {
// Ignore cleanup failures.
}
return null;
}
}
export async function sendPushNotification(
subscription: PushSubscription,
notification: PushNotification,
): Promise<boolean> {
try {
const response = await fetch('/api/push', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
subscription,
notification,
}),
});
return response.ok;
} catch {
return false;
}
}
export async function showLocalNotification(
notification: PushNotification,
): Promise<void> {
if (typeof window === 'undefined' || !('Notification' in window)) {
return;
}
if (Notification.permission !== 'granted') {
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
return;
}
}
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
await registration.showNotification(notification.title, {
body: notification.body,
icon: notification.icon,
tag: notification.tag,
data: notification.data,
});
} else {
new Notification(notification.title, {
body: notification.body,
icon: notification.icon,
tag: notification.tag,
data: notification.data,
});
}
}