your-attention 0.1.0 → 0.1.1
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/README.md +2 -0
- package/bin/your-attention.js +6 -2
- package/dist/src/adapters/files.js +66 -0
- package/dist/src/adapters/mdns.js +53 -0
- package/dist/src/adapters/mermaid.js +50 -0
- package/dist/src/adapters/openui-body.js +40 -0
- package/dist/src/adapters/openui-library.js +3 -0
- package/dist/src/adapters/sqlite.js +68 -0
- package/dist/src/cli.js +814 -0
- package/dist/src/client.js +459 -0
- package/dist/src/cloudflare/collector.js +53 -0
- package/dist/src/cloudflare/inbox-object.js +338 -0
- package/dist/src/cloudflare/storage.js +151 -0
- package/dist/src/cloudflare/worker.js +189 -0
- package/dist/src/core/crypto.js +23 -0
- package/dist/src/core/diagrams.js +225 -0
- package/dist/src/core/expr.js +125 -0
- package/dist/src/core/file-links.js +48 -0
- package/dist/src/core/hooks.js +74 -0
- package/dist/src/core/http.js +651 -0
- package/dist/src/core/inbox.js +2463 -0
- package/dist/src/core/pin.js +234 -0
- package/dist/src/core/sealed.js +167 -0
- package/dist/src/core/session-link.js +13 -0
- package/dist/src/core/socket.js +88 -0
- package/dist/src/core/storage.js +102 -0
- package/dist/src/core/summary.js +149 -0
- package/dist/src/core/telemetry.js +221 -0
- package/dist/src/core/types.js +470 -0
- package/dist/src/core/version.js +2 -0
- package/dist/src/core/widgets.js +128 -0
- package/dist/src/extensions/triage.js +232 -0
- package/dist/src/integrations/claude/ask-hook.js +84 -0
- package/dist/src/integrations/claude/channel-flag.js +102 -0
- package/dist/src/integrations/claude/channel.js +276 -0
- package/dist/src/integrations/claude/session-name.js +32 -0
- package/dist/src/integrations/claude/turn-end-hook.js +84 -0
- package/dist/src/integrations/herdr/approve.js +71 -0
- package/dist/src/integrations/herdr/blocked.js +210 -0
- package/dist/src/integrations/herdr/dialog.js +64 -0
- package/dist/src/integrations/herdr/focus.js +31 -0
- package/dist/src/integrations/herdr/place.js +22 -0
- package/dist/src/integrations/images.js +43 -0
- package/dist/src/integrations/opencode/install.js +24 -0
- package/dist/src/integrations/opencode/plugin.js +157 -0
- package/dist/src/integrations/pi/extension.js +166 -0
- package/dist/src/integrations/run-tool.js +157 -0
- package/dist/src/integrations/secrets.js +63 -0
- package/dist/src/integrations/tags.js +27 -0
- package/dist/src/integrations/tools.js +147 -0
- package/dist/src/node/home.js +20 -0
- package/dist/src/node/install.js +225 -0
- package/dist/src/node/links.js +249 -0
- package/dist/src/node/pin-prompt.js +125 -0
- package/dist/src/node/server.js +320 -0
- package/dist/src/node/service.js +74 -0
- package/dist/src/node/telemetry.js +127 -0
- package/dist/src/owner-watch.js +49 -0
- package/dist/src/tui/api.js +203 -0
- package/dist/src/tui/app.js +586 -0
- package/dist/src/tui/body.js +727 -0
- package/dist/src/tui/cardview.js +453 -0
- package/dist/src/tui/doc.js +157 -0
- package/dist/src/tui/edit.js +119 -0
- package/dist/src/tui/input.js +192 -0
- package/dist/src/tui/md.js +196 -0
- package/dist/src/tui/screen.js +225 -0
- package/dist/src/tui/terminal.js +130 -0
- package/dist/src/tui/text.js +103 -0
- package/dist/src/tui/theme.js +105 -0
- package/dist/src/tui/view.js +314 -0
- package/dist/src/watch.js +104 -0
- package/dist/web/age.js +16 -0
- package/dist/web/answers.js +485 -0
- package/dist/web/app.js +739 -0
- package/dist/web/body-faults.js +69 -0
- package/dist/web/components.js +923 -0
- package/dist/web/copy.js +118 -0
- package/dist/web/details.js +59 -0
- package/dist/web/env.js +97 -0
- package/dist/web/favicon-waiting.svg +1 -0
- package/dist/web/favicon.svg +1 -0
- package/dist/web/index.html +16 -0
- package/dist/web/library-spec.js +33 -0
- package/dist/web/markdown.js +142 -0
- package/dist/web/paste-images.js +193 -0
- package/dist/web/pin-key.js +125 -0
- package/dist/web/pin.js +126 -0
- package/dist/web/queue.js +97 -0
- package/dist/web/sealed.js +13 -0
- package/dist/web/search.js +70 -0
- package/dist/web/stories/cards.stories.js +144 -0
- package/dist/web/stories/page.stories.js +54 -0
- package/dist/web/stories/render.js +16 -0
- package/dist/web/style.css +417 -0
- package/package.json +4 -2
- package/src/core/version.ts +1 -1
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Images the person pastes into an answer: which clipboard items count, which files the inbox accepts, and the
|
|
2
|
+
// thumbnails under a field. The state is per card, so a draft survives a re-render and a revision of the card.
|
|
3
|
+
export const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
|
|
4
|
+
export const IMAGE_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
5
|
+
// The answer route reads a body of at most 16 MB, and base64 makes an image four thirds of its size, so the images of
|
|
6
|
+
// one answer share a budget well under that. Ten images of 8 MB would be a body of 107 MB, which no route accepts.
|
|
7
|
+
export const IMAGE_TOTAL_BYTES = 10 * 1024 * 1024;
|
|
8
|
+
export const IMAGE_COUNT_LIMIT = 10;
|
|
9
|
+
|
|
10
|
+
/** The files on a clipboard, in order, so checkImage can refuse the ones that aren't images. Text is left for the field. */
|
|
11
|
+
export function imageFiles(clipboard) {
|
|
12
|
+
const out = [];
|
|
13
|
+
for (const item of (clipboard && clipboard.items) || []) {
|
|
14
|
+
if (item.kind !== 'file') continue;
|
|
15
|
+
const file = item.getAsFile();
|
|
16
|
+
if (file) out.push(file);
|
|
17
|
+
}
|
|
18
|
+
return out;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Why the inbox would refuse this file, or null. */
|
|
22
|
+
export function checkImage(file) {
|
|
23
|
+
const name = file.name || 'the pasted file';
|
|
24
|
+
if (!IMAGE_TYPES.includes(file.type)) return `${name} is ${file.type || 'an unknown type'}: an answer takes only PNG, JPEG, GIF or WebP images.`;
|
|
25
|
+
if (file.size > IMAGE_LIMIT_BYTES) return `${name} is over the limit of 8 MB.`;
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Megabytes, as the person reads them, for a message about a size. */
|
|
30
|
+
const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
|
|
31
|
+
|
|
32
|
+
/** The problem with adding `file` to a draft that already holds `have`, or null when it fits. */
|
|
33
|
+
export function draftProblem(have, file) {
|
|
34
|
+
const problem = checkImage(file);
|
|
35
|
+
if (problem) return problem;
|
|
36
|
+
if (have.length >= IMAGE_COUNT_LIMIT) return `An answer takes at most ${IMAGE_COUNT_LIMIT} images.`;
|
|
37
|
+
const total = have.reduce((n, i) => n + (i.size || 0), 0) + file.size;
|
|
38
|
+
if (total > IMAGE_TOTAL_BYTES) return `These images add up to ${mb(total)}, and an answer takes at most ${mb(IMAGE_TOTAL_BYTES)} of images.`;
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const drafts = new Map(); // card id -> [{key, name, field, src, url, size}], where url is the blob address a new tab opens
|
|
43
|
+
let counter = 0;
|
|
44
|
+
|
|
45
|
+
export const pastedImages = {
|
|
46
|
+
list: (cardId) => drafts.get(cardId) || [],
|
|
47
|
+
/** Add a file to a card's draft. Returns the problem, or null. */
|
|
48
|
+
async add(cardId, field, file) {
|
|
49
|
+
const early = draftProblem(drafts.get(cardId) || [], file);
|
|
50
|
+
if (early) return early;
|
|
51
|
+
const src = await new Promise((resolve, reject) => {
|
|
52
|
+
const r = new FileReader();
|
|
53
|
+
r.onload = () => resolve(r.result);
|
|
54
|
+
r.onerror = () => reject(new Error('the browser could not read the image'));
|
|
55
|
+
r.readAsDataURL(file);
|
|
56
|
+
});
|
|
57
|
+
// Read the draft again: a second paste or a drop can land while this one decodes, and the list read before the
|
|
58
|
+
// await would drop that image when this one is written back.
|
|
59
|
+
const have = drafts.get(cardId) || [];
|
|
60
|
+
const late = draftProblem(have, file);
|
|
61
|
+
if (late) return late;
|
|
62
|
+
counter += 1;
|
|
63
|
+
drafts.set(cardId, [...have, { key: `img${counter}`, name: file.name && file.name !== 'image.png' ? file.name : `pasted-${counter}.${file.type.slice(6).replace('jpeg', 'jpg')}`, field, src, url: URL.createObjectURL(file), size: file.size }]);
|
|
64
|
+
return null;
|
|
65
|
+
},
|
|
66
|
+
remove(cardId, key) {
|
|
67
|
+
const have = drafts.get(cardId) || [];
|
|
68
|
+
for (const i of have) if (i.key === key) URL.revokeObjectURL(i.url);
|
|
69
|
+
drafts.set(cardId, have.filter((i) => i.key !== key));
|
|
70
|
+
},
|
|
71
|
+
clear(cardId) {
|
|
72
|
+
for (const i of drafts.get(cardId) || []) URL.revokeObjectURL(i.url);
|
|
73
|
+
drafts.delete(cardId);
|
|
74
|
+
},
|
|
75
|
+
/** What the answer route takes. */
|
|
76
|
+
payload: (cardId) => (drafts.get(cardId) || []).map(({ src, name, field }) => ({ src, name, field })),
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/** The strip under a field's own box, where its thumbnails and any refusal show. */
|
|
80
|
+
function stripAfter(el, field) {
|
|
81
|
+
const box = el.closest('label') || el;
|
|
82
|
+
let strip = box.nextElementSibling;
|
|
83
|
+
if (!(strip && strip.matches('[data-pasted-strip]'))) {
|
|
84
|
+
strip = document.createElement('div');
|
|
85
|
+
strip.setAttribute('data-pasted-strip', field);
|
|
86
|
+
strip.className = 'pasted-strip';
|
|
87
|
+
box.insertAdjacentElement('afterend', strip);
|
|
88
|
+
}
|
|
89
|
+
return strip;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Draw the strips of one card from its draft. A strip with nothing in it is removed. */
|
|
93
|
+
export function drawStrips(cardId) {
|
|
94
|
+
const items = pastedImages.list(cardId);
|
|
95
|
+
for (const strip of document.querySelectorAll('[data-pasted-strip]')) {
|
|
96
|
+
const field = strip.getAttribute('data-pasted-strip');
|
|
97
|
+
const mine = items.filter((i) => i.field === field);
|
|
98
|
+
const note = strip.getAttribute('data-note') || '';
|
|
99
|
+
strip.replaceChildren();
|
|
100
|
+
for (const img of mine) {
|
|
101
|
+
const fig = document.createElement('figure');
|
|
102
|
+
fig.className = 'pasted-thumb';
|
|
103
|
+
const pic = document.createElement('img');
|
|
104
|
+
pic.src = img.src;
|
|
105
|
+
pic.alt = `Pasted image ${img.name}`;
|
|
106
|
+
const drop = document.createElement('button');
|
|
107
|
+
drop.type = 'button';
|
|
108
|
+
drop.className = 'pasted-remove';
|
|
109
|
+
drop.textContent = '×';
|
|
110
|
+
drop.setAttribute('aria-label', `Remove ${img.name}`);
|
|
111
|
+
drop.addEventListener('click', () => { pastedImages.remove(cardId, img.key); drawStrips(cardId); });
|
|
112
|
+
const open = document.createElement('a');
|
|
113
|
+
open.href = img.url;
|
|
114
|
+
open.target = '_blank';
|
|
115
|
+
open.rel = 'noopener';
|
|
116
|
+
open.title = `Open ${img.name} in a new tab`;
|
|
117
|
+
open.append(pic);
|
|
118
|
+
fig.append(open, drop);
|
|
119
|
+
strip.append(fig);
|
|
120
|
+
}
|
|
121
|
+
if (note) {
|
|
122
|
+
const p = document.createElement('div');
|
|
123
|
+
p.className = 'note warn';
|
|
124
|
+
p.setAttribute('role', 'alert');
|
|
125
|
+
p.textContent = note;
|
|
126
|
+
strip.append(p);
|
|
127
|
+
}
|
|
128
|
+
// A strip whose paste is still decoding stays, or its thumbnail would appear nowhere and its refusal note would
|
|
129
|
+
// be written to a node no one shows.
|
|
130
|
+
if (!mine.length && !note && !strip.hasAttribute('data-pending')) strip.remove();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Remove every strip and forget the card's draft, after the answer is sent. */
|
|
135
|
+
export function clearPasted(cardId) {
|
|
136
|
+
pastedImages.clear(cardId);
|
|
137
|
+
for (const strip of document.querySelectorAll('[data-pasted-strip]')) strip.remove();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The text field of the card on screen that an event landed on, or null. */
|
|
141
|
+
function fieldOf(e, currentCard) {
|
|
142
|
+
const el = e.target instanceof Element ? e.target.closest('textarea, input') : null;
|
|
143
|
+
if (!el || !currentCard() || !el.closest('.focus-card') || (el.type && !['text', 'search', 'url', 'email', 'textarea'].includes(el.type))) return null;
|
|
144
|
+
return el;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Add the files to the card's draft under the field they landed on, and show thumbnails or the refusal. */
|
|
148
|
+
async function take(el, cardId, files) {
|
|
149
|
+
const field = el.getAttribute('name') || el.id || 'answer';
|
|
150
|
+
const strip = stripAfter(el, field);
|
|
151
|
+
// A count, not a flag: two pastes on one field decode at once, and the first to finish must not let the strip go
|
|
152
|
+
// while the second is still on its way.
|
|
153
|
+
const decoding = (by) => {
|
|
154
|
+
const n = Math.max(0, Number(strip.getAttribute('data-pending') || 0) + by);
|
|
155
|
+
if (n) strip.setAttribute('data-pending', String(n));
|
|
156
|
+
else strip.removeAttribute('data-pending');
|
|
157
|
+
};
|
|
158
|
+
decoding(1);
|
|
159
|
+
const problems = [];
|
|
160
|
+
try {
|
|
161
|
+
for (const file of files) {
|
|
162
|
+
const problem = await pastedImages.add(cardId, field, file).catch((err) => String(err.message || err));
|
|
163
|
+
if (problem) problems.push(problem);
|
|
164
|
+
}
|
|
165
|
+
strip.setAttribute('data-note', problems.join(' '));
|
|
166
|
+
} finally {
|
|
167
|
+
decoding(-1);
|
|
168
|
+
}
|
|
169
|
+
drawStrips(cardId);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Paste or drop an image on any text field of the card on screen. Text on the clipboard still pastes as text. */
|
|
173
|
+
export function installPaste(currentCard) {
|
|
174
|
+
document.addEventListener('paste', (e) => {
|
|
175
|
+
const el = fieldOf(e, currentCard);
|
|
176
|
+
const files = el ? imageFiles(e.clipboardData) : [];
|
|
177
|
+
if (!files.length) return;
|
|
178
|
+
if (![...e.clipboardData.items].some((i) => i.kind === 'string' && i.type === 'text/plain')) e.preventDefault();
|
|
179
|
+
take(el, currentCard(), files);
|
|
180
|
+
});
|
|
181
|
+
// A field only receives a drop when dragover is cancelled, and the browser would otherwise open the file.
|
|
182
|
+
const dragsFiles = (e) => [...((e.dataTransfer && e.dataTransfer.types) || [])].includes('Files');
|
|
183
|
+
document.addEventListener('dragover', (e) => {
|
|
184
|
+
if (dragsFiles(e) && fieldOf(e, currentCard)) e.preventDefault();
|
|
185
|
+
});
|
|
186
|
+
document.addEventListener('drop', (e) => {
|
|
187
|
+
const el = dragsFiles(e) ? fieldOf(e, currentCard) : null;
|
|
188
|
+
if (!el) return;
|
|
189
|
+
e.preventDefault();
|
|
190
|
+
const files = [...e.dataTransfer.files];
|
|
191
|
+
if (files.length) take(el, currentCard(), files);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// The PIN never leaves the device. The page derives a key from it with PBKDF2-SHA256, using the salt and
|
|
2
|
+
// iterations the inbox hands out at GET /v1/pin, and sends the key. src/core/pin.ts derives the same key.
|
|
3
|
+
const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, '0')).join('');
|
|
4
|
+
const unhex = (s) => new Uint8Array((s.match(/../g) || []).map((b) => parseInt(b, 16)));
|
|
5
|
+
|
|
6
|
+
/** `onProgress(fraction)` runs while a page without Web Crypto derives the key, which takes seconds on a phone. */
|
|
7
|
+
export async function pinKey(pin, salt, iterations, onProgress) {
|
|
8
|
+
// A browser gives Web Crypto to secure origins only. A phone that opens a laptop inbox at http://laptop.local has none.
|
|
9
|
+
if (!globalThis.crypto || !globalThis.crypto.subtle) return pinKeyWithoutWebCrypto(pin, salt, iterations, onProgress);
|
|
10
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(pin), 'PBKDF2', false, ['deriveBits']);
|
|
11
|
+
return hex(await crypto.subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt: unhex(salt), iterations }, key, 256));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** A new PIN's key, with a fresh random 16-byte salt. getRandomValues works on any origin. */
|
|
15
|
+
export async function newPinKey(pin, iterations, onProgress) {
|
|
16
|
+
const salt = hex(crypto.getRandomValues(new Uint8Array(16)));
|
|
17
|
+
return { key: await pinKey(pin, salt, iterations, onProgress), salt, iterations };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// PBKDF2-HMAC-SHA256 for 32 bytes, in plain JavaScript, for a page without Web Crypto. The HMAC pads are hashed once,
|
|
21
|
+
// so each iteration costs two SHA-256 blocks.
|
|
22
|
+
const K = new Uint32Array([
|
|
23
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
|
24
|
+
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
25
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
|
26
|
+
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
27
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
|
28
|
+
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
29
|
+
]);
|
|
30
|
+
const INIT = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
|
31
|
+
const W = new Uint32Array(64);
|
|
32
|
+
|
|
33
|
+
/** One SHA-256 block of 16 words into `h`, in place. */
|
|
34
|
+
function block(h, words) {
|
|
35
|
+
for (let i = 0; i < 16; i++) W[i] = words[i];
|
|
36
|
+
for (let i = 16; i < 64; i++) {
|
|
37
|
+
const a = W[i - 15], b = W[i - 2];
|
|
38
|
+
const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3);
|
|
39
|
+
const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10);
|
|
40
|
+
W[i] = (W[i - 16] + s0 + W[i - 7] + s1) | 0;
|
|
41
|
+
}
|
|
42
|
+
let [a, b, c, d, e, f, g, k] = h;
|
|
43
|
+
for (let i = 0; i < 64; i++) {
|
|
44
|
+
const t1 = (k + (((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))) + ((e & f) ^ (~e & g)) + K[i] + W[i]) | 0;
|
|
45
|
+
const t2 = ((((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
|
|
46
|
+
k = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;
|
|
47
|
+
}
|
|
48
|
+
h[0] = (h[0] + a) | 0; h[1] = (h[1] + b) | 0; h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0;
|
|
49
|
+
h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0; h[6] = (h[6] + g) | 0; h[7] = (h[7] + k) | 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** SHA-256 of `bytes`, carried on from `h` after `done` bytes, as 8 words. */
|
|
53
|
+
function hash(bytes, h = INIT, done = 0) {
|
|
54
|
+
const s = Int32Array.from(h);
|
|
55
|
+
const total = done + bytes.length;
|
|
56
|
+
const padded = new Uint8Array(Math.ceil((bytes.length + 9) / 64) * 64);
|
|
57
|
+
padded.set(bytes);
|
|
58
|
+
padded[bytes.length] = 0x80;
|
|
59
|
+
const view = new DataView(padded.buffer);
|
|
60
|
+
view.setUint32(padded.length - 8, Math.floor((total * 8) / 2 ** 32));
|
|
61
|
+
view.setUint32(padded.length - 4, (total * 8) >>> 0);
|
|
62
|
+
const words = new Int32Array(16);
|
|
63
|
+
for (let o = 0; o < padded.length; o += 64) {
|
|
64
|
+
for (let i = 0; i < 16; i++) words[i] = view.getInt32(o + i * 4);
|
|
65
|
+
block(s, words);
|
|
66
|
+
}
|
|
67
|
+
return s;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Iterations between two yields to the page, about 50 ms on a phone. */
|
|
71
|
+
const CHUNK = 20_000;
|
|
72
|
+
|
|
73
|
+
/** PBKDF2-HMAC-SHA256 with Web Crypto's result, for 32 bytes. It yields to the page between chunks, so the page can draw
|
|
74
|
+
* `onProgress(fraction)`. Exported for the tests. */
|
|
75
|
+
export async function pinKeyWithoutWebCrypto(pin, salt, iterations, onProgress) {
|
|
76
|
+
let key = new TextEncoder().encode(pin);
|
|
77
|
+
if (key.length > 64) key = wordBytes(hash(key));
|
|
78
|
+
const pad = (x) => { const p = new Uint8Array(64).fill(x); key.forEach((b, i) => { p[i] ^= b; }); return p; };
|
|
79
|
+
// The state of SHA-256 after each 64-byte pad, which every HMAC call starts from.
|
|
80
|
+
const inner = afterBlock(pad(0x36));
|
|
81
|
+
const outer = afterBlock(pad(0x5c));
|
|
82
|
+
const s = unhex(salt);
|
|
83
|
+
const first = new Uint8Array(s.length + 4);
|
|
84
|
+
first.set(s);
|
|
85
|
+
first[s.length + 3] = 1;
|
|
86
|
+
// U1 = HMAC(PIN, salt || 1), then each U is the HMAC of the one before, and the key is their XOR.
|
|
87
|
+
let u = hash(wordBytes(hash(first, inner, 64)), outer, 64);
|
|
88
|
+
const out = Int32Array.from(u);
|
|
89
|
+
// A 32-byte message after the 64-byte pad: one block, with its padding and length fixed.
|
|
90
|
+
const msg = new Int32Array(16);
|
|
91
|
+
msg[8] = 0x80000000;
|
|
92
|
+
msg[15] = (64 + 32) * 8;
|
|
93
|
+
for (let n = 1; n < iterations; n++) {
|
|
94
|
+
if (n % CHUNK === 0) {
|
|
95
|
+
if (onProgress) onProgress(n / iterations);
|
|
96
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
97
|
+
}
|
|
98
|
+
const hi = Int32Array.from(inner);
|
|
99
|
+
msg.set(u, 0);
|
|
100
|
+
block(hi, msg);
|
|
101
|
+
const ho = Int32Array.from(outer);
|
|
102
|
+
msg.set(hi, 0);
|
|
103
|
+
block(ho, msg);
|
|
104
|
+
u = ho;
|
|
105
|
+
for (let i = 0; i < 8; i++) out[i] ^= u[i];
|
|
106
|
+
}
|
|
107
|
+
if (onProgress) onProgress(1);
|
|
108
|
+
return hex(wordBytes(out));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function afterBlock(bytes) {
|
|
112
|
+
const s = Int32Array.from(INIT);
|
|
113
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, 64);
|
|
114
|
+
const words = new Int32Array(16);
|
|
115
|
+
for (let i = 0; i < 16; i++) words[i] = view.getInt32(i * 4);
|
|
116
|
+
block(s, words);
|
|
117
|
+
return s;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function wordBytes(words) {
|
|
121
|
+
const out = new Uint8Array(words.length * 4);
|
|
122
|
+
const view = new DataView(out.buffer);
|
|
123
|
+
words.forEach((w, i) => view.setInt32(i * 4, w));
|
|
124
|
+
return out;
|
|
125
|
+
}
|
package/dist/web/pin.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// The PIN of the inbox, on the page: the screen that unlocks a new tab, the
|
|
2
|
+
// prompt that offers to set a PIN, and the controls to change it or lock the tab.
|
|
3
|
+
import { BASE, J, h, unlockToken } from './env.js';
|
|
4
|
+
import { newPinKey, pinKey } from './pin-key.js';
|
|
5
|
+
|
|
6
|
+
const { React } = window.__OpenUI;
|
|
7
|
+
|
|
8
|
+
const send = (method, path, body) => fetch(BASE + path, { method, headers: { 'content-type': 'application/json', 'x-your-attention': '1' }, body: J(body) })
|
|
9
|
+
.then(async (r) => ({ status: r.status, body: await r.json().catch(() => ({})) }));
|
|
10
|
+
// The PIN never leaves the page. It derives a key with the salt and iterations of GET /v1/pin, and sends the key.
|
|
11
|
+
const pinState = () => fetch(`${BASE}v1/pin`).then((r) => (r.ok ? r.json() : Promise.reject(new Error(`the inbox answered ${r.status}`))));
|
|
12
|
+
const currentKey = async (pin, onProgress) => { const s = await pinState(); return pinKey(pin, s.salt, s.iterations, onProgress); };
|
|
13
|
+
// A page without Web Crypto, such as a phone at a plain-HTTP laptop address, derives the key in seconds, and says how far it got.
|
|
14
|
+
const progressText = (fraction) => (fraction === null ? null : `Checking the PIN on this device: ${Math.floor(fraction * 100)}%`);
|
|
15
|
+
|
|
16
|
+
// A loopback, private network or .local address means a computer runs the inbox, and its CLI resets the PIN.
|
|
17
|
+
const LAPTOP = /^(localhost|127(\.\d{1,3}){3}|\[::1\]|10(\.\d{1,3}){3}|192\.168(\.\d{1,3}){2}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|\[f[cd][0-9a-f:]*\]|\[fe80:[0-9a-f:]*\]|[\w-]+\.local)$/i;
|
|
18
|
+
|
|
19
|
+
const wait = (ms) => {
|
|
20
|
+
const s = Math.max(0, Math.ceil(ms / 1000));
|
|
21
|
+
if (s < 90) return `${s} second${s === 1 ? '' : 's'}`;
|
|
22
|
+
if (s < 5400) return `${Math.ceil(s / 60)} minutes`;
|
|
23
|
+
return `${Math.ceil(s / 3600)} hours`;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const pinInput = (props) => h('input', { type: 'password', inputMode: 'numeric', pattern: '[0-9]{4}', maxLength: 4, size: 6, className: 'pin-input', ...props,
|
|
27
|
+
onChange: (e) => props.onChange(e.target.value.replace(/\D/g, '').slice(0, 4)) });
|
|
28
|
+
|
|
29
|
+
/** The screen of a locked tab. The PIN goes to POST /v1/unlock, and the unlock token stays in this tab's session storage. */
|
|
30
|
+
export function PinUnlock({ onUnlocked }) {
|
|
31
|
+
const [pin, setPin] = React.useState('');
|
|
32
|
+
const [error, setError] = React.useState(null);
|
|
33
|
+
const [until, setUntil] = React.useState(null);
|
|
34
|
+
const [now, setNow] = React.useState(Date.now());
|
|
35
|
+
const [busy, setBusy] = React.useState(false);
|
|
36
|
+
const [progress, setProgress] = React.useState(null);
|
|
37
|
+
React.useEffect(() => {
|
|
38
|
+
fetch(`${BASE}v1/pin`).then((r) => (r.ok ? r.json() : null)).then((s) => { if (s && s.lockedUntil) setUntil(s.lockedUntil); }, () => {});
|
|
39
|
+
}, []);
|
|
40
|
+
React.useEffect(() => {
|
|
41
|
+
if (!until) return undefined;
|
|
42
|
+
const timer = setInterval(() => setNow(Date.now()), 1000);
|
|
43
|
+
return () => clearInterval(timer);
|
|
44
|
+
}, [until]);
|
|
45
|
+
const locked = until && until > now;
|
|
46
|
+
const submit = async (e) => {
|
|
47
|
+
e.preventDefault();
|
|
48
|
+
if (pin.length !== 4 || locked || busy) return;
|
|
49
|
+
setBusy(true);
|
|
50
|
+
const r = await currentKey(pin, setProgress).then((key) => send('POST', 'v1/unlock', { key })).catch(() => ({ status: 0, body: { error: 'The inbox did not answer.' } }));
|
|
51
|
+
setBusy(false);
|
|
52
|
+
setProgress(null);
|
|
53
|
+
setPin('');
|
|
54
|
+
if (r.status === 200 && r.body.unlock) { unlockToken.set(r.body.unlock); onUnlocked(); return; }
|
|
55
|
+
if (r.status === 429 && r.body.lockedUntil) { setUntil(r.body.lockedUntil); setNow(Date.now()); setError(null); return; }
|
|
56
|
+
setError(r.status === 401 ? `Wrong PIN. ${r.body.triesLeft} ${r.body.triesLeft === 1 ? 'try' : 'tries'} left before a wait.` : r.body.error || 'The inbox refused the PIN.');
|
|
57
|
+
};
|
|
58
|
+
return h('form', { className: 'signin pin-unlock', onSubmit: submit },
|
|
59
|
+
h('h2', null, 'Unlock your inbox'),
|
|
60
|
+
h('p', null, 'Type the PIN of this inbox. Each new tab asks for it, and closing the tab locks it again.'),
|
|
61
|
+
h('div', { className: 'pin-row' },
|
|
62
|
+
pinInput({ value: pin, onChange: setPin, autoFocus: true, autoComplete: 'current-password', 'aria-label': 'PIN', disabled: !!locked }),
|
|
63
|
+
h('button', { type: 'submit', className: 'btn primary', disabled: pin.length !== 4 || !!locked || busy }, busy ? 'Checking…' : 'Unlock')),
|
|
64
|
+
locked && h('p', { className: 'pin-error', role: 'status' }, `Too many wrong PINs. Try again in ${wait(until - now)}.`),
|
|
65
|
+
!locked && progress !== null && h('p', { className: 'pin-help', role: 'status' }, progressText(progress)),
|
|
66
|
+
!locked && error && h('p', { className: 'pin-error', role: 'alert' }, error),
|
|
67
|
+
h('p', { className: 'pin-help' }, 'Forgot it? ', LAPTOP.test(location.hostname)
|
|
68
|
+
? h(React.Fragment, null, 'On the computer that runs the inbox, run ', h('code', null, 'your-attention pin reset'), '.')
|
|
69
|
+
: h(React.Fragment, null, 'On a computer paired with this inbox as owner, run ', h('code', null, 'your-attention pin reset'), '.')));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Set a PIN, or change it with the current one. `offer` adds Skip and Never ask again, for an inbox that has none. */
|
|
73
|
+
export function PinForm({ set, offer, onDone, onSkip, onNever, onBusy = () => {} }) {
|
|
74
|
+
const [current, setCurrent] = React.useState('');
|
|
75
|
+
const [pin, setPin] = React.useState('');
|
|
76
|
+
const [again, setAgain] = React.useState('');
|
|
77
|
+
const [error, setError] = React.useState(null);
|
|
78
|
+
const [progress, setProgress] = React.useState(null);
|
|
79
|
+
const submit = async (e) => {
|
|
80
|
+
e.preventDefault();
|
|
81
|
+
if (pin.length !== 4) return setError('A PIN is 4 digits.');
|
|
82
|
+
if (pin !== again) return setError('The two PINs differ.');
|
|
83
|
+
onBusy(true);
|
|
84
|
+
const r = await pinState()
|
|
85
|
+
// Changing the PIN derives two keys, so each one reports half of the progress.
|
|
86
|
+
.then(async (s) => ({
|
|
87
|
+
...(await newPinKey(pin, s.newIterations, (f) => setProgress(set ? f / 2 : f))),
|
|
88
|
+
...(set ? { current: await pinKey(current, s.salt, s.iterations, (f) => setProgress(0.5 + f / 2)) } : {}),
|
|
89
|
+
}))
|
|
90
|
+
.then((body) => send('PUT', 'v1/pin', body))
|
|
91
|
+
.catch(() => ({ status: 0, body: { error: 'The inbox did not answer.' } }));
|
|
92
|
+
setProgress(null);
|
|
93
|
+
if (r.status !== 200) { onBusy(false); return setError(r.body.error || 'The inbox refused the PIN.'); }
|
|
94
|
+
if (r.body.unlock) unlockToken.set(r.body.unlock);
|
|
95
|
+
onDone();
|
|
96
|
+
};
|
|
97
|
+
return h('form', { className: 'usage-notice pin-form', 'aria-label': set ? 'Change the PIN' : 'Set a PIN', onSubmit: submit },
|
|
98
|
+
h('p', null, set
|
|
99
|
+
? 'Change the PIN of this inbox. Every other tab types the new PIN.'
|
|
100
|
+
: 'Protect this inbox with a PIN. Anyone who gets its address or a sign-in link can answer your agents\' cards. With a PIN, each new tab asks for it first.'),
|
|
101
|
+
h('div', { className: 'pin-row' },
|
|
102
|
+
set && h('label', null, 'Current PIN ', pinInput({ value: current, onChange: setCurrent, autoComplete: 'current-password' })),
|
|
103
|
+
h('label', null, 'New PIN ', pinInput({ value: pin, onChange: setPin, autoComplete: 'new-password', autoFocus: !set })),
|
|
104
|
+
h('label', null, 'Again ', pinInput({ value: again, onChange: setAgain, autoComplete: 'new-password' }))),
|
|
105
|
+
error && h('p', { className: 'pin-error', role: 'alert' }, error),
|
|
106
|
+
progress !== null && h('p', { role: 'status' }, progressText(progress)),
|
|
107
|
+
h('div', { className: 'usage-actions' },
|
|
108
|
+
h('button', { type: 'submit', className: 'btn primary' }, set ? 'Change PIN' : 'Set PIN'),
|
|
109
|
+
offer && h('button', { type: 'button', className: 'btn', onClick: onSkip }, 'Skip'),
|
|
110
|
+
offer && h('button', { type: 'button', className: 'btn', onClick: onNever }, 'Never ask again'),
|
|
111
|
+
!offer && h('button', { type: 'button', className: 'btn', onClick: onSkip }, 'Cancel')));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** At the foot of the queue: set or change the PIN, and lock this tab. */
|
|
115
|
+
export function PinControls({ pin, onEdit, onLock }) {
|
|
116
|
+
if (!pin) return null;
|
|
117
|
+
return h('div', { className: 'pin-controls' },
|
|
118
|
+
h('button', { type: 'button', className: 'btn', onClick: onEdit }, pin.set ? 'Change PIN' : 'Set a PIN'),
|
|
119
|
+
pin.set && h('button', { type: 'button', className: 'btn', onClick: onLock }, 'Lock this tab'));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** End this tab's unlock token on the inbox, then forget it. */
|
|
123
|
+
export const lockTab = () => send('POST', 'v1/lock', {}).catch(() => null).then(() => unlockToken.del());
|
|
124
|
+
|
|
125
|
+
/** Tell the inbox "never ask again". */
|
|
126
|
+
export const neverAsk = () => send('PUT', 'v1/pin/never-ask', { neverAsk: true });
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// The queue, built from the card summaries of GET /v1/state: each card's state, its priority level, the sections of the list, and the order Skip for now and Send
|
|
2
|
+
// answer move through. The page and the terminal client share this file, so both show the same queue.
|
|
3
|
+
|
|
4
|
+
export const CLOSED_LABEL = { retracted: 'Retracted by agent', 'self-answered': 'Answered by agent', 'answered-in-terminal': 'Answered in the terminal', resolved: 'No longer waiting', expired: 'Expired', returned: 'Sent back to its agent', dismissed: 'Dismissed' };
|
|
5
|
+
export const STATE_LABEL = { open: 'to answer', 'in-triage': 'being checked by triage', held: 'held by an extension', orphaned: 'its agent is gone', answered: 'stored', delivered: 'delivered', read: 'read', closed: 'closed' };
|
|
6
|
+
/** The ids of the sections that every Group by choice shows, so a collapsed one keeps its state across the choices. */
|
|
7
|
+
export const SECTION_ID = { system: 'section: system', checking: 'section: checking', outbox: 'section: outbox', sent: 'section: sent' };
|
|
8
|
+
|
|
9
|
+
// A group's id is its kind and value, such as tag: topic: billing. The ':' and '%' of a part are escaped, because an
|
|
10
|
+
// agent picks tag keys and values: without the escape, a tag named `section: outbox` would take the outbox's id.
|
|
11
|
+
const idPart = (s) => String(s).replace(/[%:]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
|
|
12
|
+
const groupId = (kind, ...parts) => [kind, ...parts.map(idPart)].join(': ');
|
|
13
|
+
|
|
14
|
+
// An agent's name for people: the session name its newest card carries, else its id.
|
|
15
|
+
export function agentName(id, cards) {
|
|
16
|
+
let best = null;
|
|
17
|
+
for (const c of cards) if (c.agent === id && c.origin && c.origin.name && (!best || c.createdAt > best.createdAt)) best = c;
|
|
18
|
+
return best ? best.origin.name : id;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function presenceOf(card, state) {
|
|
22
|
+
if (card.deliver === 'none') return null;
|
|
23
|
+
const p = state.presence[card.agent];
|
|
24
|
+
if (!p || !p.online) return ['off', 'Agent offline: your answer waits until its session resumes'];
|
|
25
|
+
if (p.channelOff) return ['off', 'Channel off: this session started without the development-channels flag, so answers cannot reach it'];
|
|
26
|
+
const unread = state.cards.some((c) => c.agent === card.agent && state.states[c.id] === 'delivered');
|
|
27
|
+
return unread ? ['busy', 'Agent busy: it has an answer it has not read yet'] : ['on', 'Agent listening'];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The queue for GET /v1/state, grouped by nothing, priority, agent or tag:<key>. `pins` lists the pinned tag values as [key, value], oldest first. `collapsed` holds the ids of the groups the person muted, each the group's kind and value. */
|
|
31
|
+
export function buildQueue(state, groupBy, pins = [], collapsed = new Set()) {
|
|
32
|
+
const answers = state.answers;
|
|
33
|
+
const byId = Object.fromEntries(state.cards.map((c) => [c.id, c]));
|
|
34
|
+
const st = (c) => state.states[c.id];
|
|
35
|
+
const visible = state.cards;
|
|
36
|
+
const levels = state.levels || [];
|
|
37
|
+
const levelOf = (c) => (state.priorities || {})[c.id] || c.priority;
|
|
38
|
+
const rank = (c) => { const i = levels.findIndex((l) => l.id === levelOf(c)); return i < 0 ? levels.length : i; };
|
|
39
|
+
const label = (id) => (levels.find((l) => l.id === id) || {}).label || id;
|
|
40
|
+
const waiting = (s) => ['open', 'orphaned', 'held'].includes(s);
|
|
41
|
+
const pending = visible.filter((c) => waiting(st(c)))
|
|
42
|
+
.sort((a, b) => rank(a) - rank(b) || a.createdAt - b.createdAt);
|
|
43
|
+
const checking = visible.filter((c) => st(c) === 'in-triage');
|
|
44
|
+
const tagOf = (c, key) => String((c.tags || {})[key] || '').trim();
|
|
45
|
+
// The inbox's own cards come first, above every pinned group and every Group by choice, so an approval never waits
|
|
46
|
+
// behind a pin. A system card keeps out of the groups, even when it carries the tag a pin matches.
|
|
47
|
+
const systems = pending.filter((c) => c.kind === 'system');
|
|
48
|
+
const others = pending.filter((c) => c.kind !== 'system');
|
|
49
|
+
// Each pinned value is a group below them, and a card that matches two pins goes to the oldest one.
|
|
50
|
+
const pinOf = (c) => pins.findIndex(([key, value]) => tagOf(c, key) === value);
|
|
51
|
+
const pinned = pins.map(([key, value], i) => ({ key, value, id: groupId('pin', key, value), items: others.filter((c) => pinOf(c) === i) }));
|
|
52
|
+
const unpinned = others.filter((c) => pinOf(c) < 0);
|
|
53
|
+
const sentAt = (c) => (c.closed ? c.closed.at : answers[c.id] ? answers[c.id].savedAt : 0);
|
|
54
|
+
const outbox = visible.filter((c) => ['answered', 'delivered'].includes(st(c))).sort((a, b) => sentAt(b) - sentAt(a));
|
|
55
|
+
const sent = visible.filter((c) => ['read', 'closed'].includes(st(c))).sort((a, b) => sentAt(b) - sentAt(a));
|
|
56
|
+
// No grouping by default. The choices follow the properties the cards carry.
|
|
57
|
+
const tagKeys = [...new Set(visible.flatMap((c) => Object.keys(c.tags || {})))].sort();
|
|
58
|
+
const tagKey = groupBy.startsWith('tag:') ? groupBy.slice(4) : null;
|
|
59
|
+
const groupKey = (c) => (groupBy === 'priority' ? label(levelOf(c)) : groupBy === 'agent' ? agentName(c.agent, visible) : tagKey !== null ? tagOf(c, tagKey) || `No ${tagKey}` : 'Waiting for you');
|
|
60
|
+
// The cards the inbox clears: answered or closed. Search still finds them.
|
|
61
|
+
const dealt = visible.filter((c) => ['closed', 'answered', 'delivered', 'read'].includes(st(c)));
|
|
62
|
+
const grouped = groupBy === 'none' ? [['Waiting for you', unpinned]] : [...unpinned.reduce((m, c) => m.set(groupKey(c), [...(m.get(groupKey(c)) || []), c]), new Map())];
|
|
63
|
+
// A group is named by its kind and its value, so another Group by choice has its own collapsed groups and switching
|
|
64
|
+
// back restores them. Under a tag grouping, a group of one value names its tag, so its heading can pin it. A group of
|
|
65
|
+
// cards with no value has no value part, so it can't share the id of a group whose value reads `(none)`.
|
|
66
|
+
const groups = grouped.map(([title, items]) => {
|
|
67
|
+
const value = tagKey !== null ? tagOf(items[0], tagKey) : '';
|
|
68
|
+
const tag = tagKey !== null && value ? [tagKey, value] : undefined;
|
|
69
|
+
const id = tagKey !== null ? groupId('tag', tagKey, ...(value ? [value] : [])) : groupBy === 'priority' ? groupId('priority', label(levelOf(items[0]))) : groupId(groupBy, title);
|
|
70
|
+
return [title, items, tag, id];
|
|
71
|
+
});
|
|
72
|
+
// The group each card sits in, so a card that arrives knows whether its group is collapsed, and the terminal
|
|
73
|
+
// client's key can collapse the group of the card on screen.
|
|
74
|
+
const groupOf = {};
|
|
75
|
+
for (const c of systems) groupOf[c.id] = SECTION_ID.system;
|
|
76
|
+
for (const p of pinned) for (const c of p.items) groupOf[c.id] = p.id;
|
|
77
|
+
for (const [, items, , id] of groups) for (const c of items) groupOf[c.id] = id;
|
|
78
|
+
for (const c of checking) groupOf[c.id] = SECTION_ID.checking;
|
|
79
|
+
for (const c of outbox) groupOf[c.id] = SECTION_ID.outbox;
|
|
80
|
+
for (const c of sent) groupOf[c.id] = SECTION_ID.sent;
|
|
81
|
+
// A collapsed group keeps its heading and its cards, for the count, but its cards leave the queue order: Skip for
|
|
82
|
+
// now and the card after an answer pass over them, while a card opened by a link still opens.
|
|
83
|
+
const hidden = new Set(Object.keys(groupOf).filter((id) => collapsed.has(groupOf[id])));
|
|
84
|
+
const order = [
|
|
85
|
+
...(collapsed.has(SECTION_ID.system) ? [] : systems),
|
|
86
|
+
...pinned.flatMap((p) => (collapsed.has(p.id) ? [] : p.items)),
|
|
87
|
+
...groups.flatMap(([, items, , id]) => (collapsed.has(id) ? [] : items)),
|
|
88
|
+
];
|
|
89
|
+
return { byId, st, levelOf, label, waiting, pending, systems, checking, pinned, outbox, sent, tagKeys, dealt, groups, groupOf, hidden, order };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The card after `id` in queue order, wrapping around at the end. */
|
|
93
|
+
export function after(order, id) {
|
|
94
|
+
const i = order.findIndex((c) => c.id === id);
|
|
95
|
+
const rest = i < 0 ? order : [...order.slice(i + 1), ...order.slice(0, i)];
|
|
96
|
+
return (rest[0] || {}).id || null;
|
|
97
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Seals a secret for one agent: AES-256-GCM for the value, and the AES key
|
|
2
|
+
// wrapped with the agent's RSA-OAEP public key. The inbox stores only the
|
|
3
|
+
// result, and only the agent that asked holds the private key.
|
|
4
|
+
const b64 = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf)));
|
|
5
|
+
|
|
6
|
+
export async function seal(publicJwk, text) {
|
|
7
|
+
const pub = await crypto.subtle.importKey('jwk', publicJwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['wrapKey']);
|
|
8
|
+
const aes = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt']);
|
|
9
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
10
|
+
const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aes, new TextEncoder().encode(text));
|
|
11
|
+
const key = await crypto.subtle.wrapKey('raw', aes, pub, { name: 'RSA-OAEP' });
|
|
12
|
+
return { alg: 'RSA-OAEP-256+A256GCM', key: b64(key), iv: b64(iv), data: b64(data) };
|
|
13
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The page's search, which runs in the browser over what the page already holds: each card's summary from GET /v1/state, and the
|
|
2
|
+
// whole card and answer where the page has fetched them. It never asks the inbox for anything. Matching is case-insensitive
|
|
3
|
+
// substring, and a card matches when every word of the query is somewhere in it.
|
|
4
|
+
|
|
5
|
+
// Lowercase a text without changing its length, so a position found in the folded text is the same position in the original.
|
|
6
|
+
// A letter whose lowercase is longer, such as İ, stays as it is.
|
|
7
|
+
const fold = (text) => Array.from(String(text), (ch) => { const l = ch.toLowerCase(); return l.length === ch.length ? l : ch; }).join('');
|
|
8
|
+
|
|
9
|
+
/** The words of a query: lowercase, split on spaces. A blank query has none. */
|
|
10
|
+
export const searchTerms = (query) => fold(query || '').split(/\s+/).filter(Boolean);
|
|
11
|
+
|
|
12
|
+
const flat = (v) => (Array.isArray(v) ? v.map(flat).join(' ') : typeof v === 'string' ? v : typeof v === 'number' ? String(v) : '');
|
|
13
|
+
|
|
14
|
+
// The fields of a card, each as [label, text]. The title comes first, so a title match needs no snippet.
|
|
15
|
+
function fieldsOf(summary, detail) {
|
|
16
|
+
const card = (detail && detail.card) || {};
|
|
17
|
+
const answer = (detail && detail.answer) || null;
|
|
18
|
+
const o = summary.origin || {};
|
|
19
|
+
const tags = Object.entries(summary.tags || {}).map(([k, v]) => `${k}: ${v}`).join(' · ');
|
|
20
|
+
const options = (card.options || []).map((x) => `${x.label} ${x.description || ''}`).join(' · ');
|
|
21
|
+
const questions = (card.questions || []).map((q) => [q.header, q.question, q.text, ...(q.options || []).map((x) => `${x.label} ${x.description || ''}`)].filter(Boolean).join(' ')).join(' · ');
|
|
22
|
+
return [
|
|
23
|
+
['Title', summary.title],
|
|
24
|
+
['Tag', tags],
|
|
25
|
+
['Agent', [o.name, summary.from, summary.agent].filter(Boolean).join(' · ')],
|
|
26
|
+
['Status', summary.status || ''],
|
|
27
|
+
['Text', card.text ?? summary.preview ?? ''],
|
|
28
|
+
['Recommendation', card.recommendation || ''],
|
|
29
|
+
['Options', options],
|
|
30
|
+
['Questions', questions],
|
|
31
|
+
['Reply', (card.replies || []).map((r) => r.text).join(' · ')],
|
|
32
|
+
['Answer', answer ? [answer.comment, ...Object.values(answer.values || {}).map(flat)].filter(Boolean).join(' · ') : ''],
|
|
33
|
+
['Outcome', summary.closed ? summary.closed.outcome || '' : ''],
|
|
34
|
+
];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const around = (label, text, term) => {
|
|
38
|
+
const one = text.replace(/\s+/g, ' ');
|
|
39
|
+
const at = fold(one).indexOf(term);
|
|
40
|
+
const start = Math.max(0, at - 30);
|
|
41
|
+
const end = at + term.length;
|
|
42
|
+
return { label, before: (start > 0 ? '…' : '') + one.slice(start, at), hit: one.slice(at, end), after: one.slice(end, end + 60) + (end + 60 < one.length ? '…' : '') };
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Null when the card lacks a term, else `{snippet}` with the first term's place outside the title, when it is not in the title. */
|
|
46
|
+
export function matchCard(terms, summary, detail) {
|
|
47
|
+
if (!terms.length) return {};
|
|
48
|
+
const fields = fieldsOf(summary, detail).map(([label, text]) => [label, String(text || '')]);
|
|
49
|
+
const lower = fields.map(([, text]) => fold(text));
|
|
50
|
+
const all = lower.join('\n');
|
|
51
|
+
if (!terms.every((t) => all.includes(t))) return null;
|
|
52
|
+
if (lower[0].includes(terms[0])) return {};
|
|
53
|
+
const i = lower.findIndex((text) => text.includes(terms[0]));
|
|
54
|
+
return i < 0 ? {} : { snippet: around(fields[i][0], fields[i][1], terms[0]) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A text split into parts, each flagged when it matches a term. The parts join back into the text. */
|
|
58
|
+
export function highlightParts(text, terms) {
|
|
59
|
+
const t = String(text);
|
|
60
|
+
if (!terms.length) return [{ text: t, hit: false }];
|
|
61
|
+
const lower = fold(t);
|
|
62
|
+
const marked = new Array(t.length).fill(false);
|
|
63
|
+
for (const term of terms) for (let at = lower.indexOf(term); at >= 0; at = lower.indexOf(term, at + term.length)) marked.fill(true, at, at + term.length);
|
|
64
|
+
const parts = [];
|
|
65
|
+
for (let i = 0; i < t.length; i += 1) {
|
|
66
|
+
const last = parts[parts.length - 1];
|
|
67
|
+
if (last && last.hit === marked[i]) last.text += t[i]; else parts.push({ text: t[i], hit: marked[i] });
|
|
68
|
+
}
|
|
69
|
+
return parts.length ? parts : [{ text: t, hit: false }];
|
|
70
|
+
}
|