@watchtowerobservability/activity 0.0.0-stage → 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/LICENSE +202 -0
- package/README.md +55 -2
- package/dist/ed25519ph.d.ts +2 -0
- package/dist/ed25519ph.test.d.ts +1 -0
- package/dist/index.cjs +931 -0
- package/dist/index.cjs.map +7 -0
- package/dist/index.d.cts +213 -0
- package/dist/index.d.ts +213 -0
- package/dist/index.js +908 -0
- package/dist/index.js.map +7 -0
- package/dist/index.test.d.ts +1 -0
- package/dist/model3.d.ts +30 -0
- package/dist/model3.test.d.ts +1 -0
- package/dist/model4.d.ts +74 -0
- package/dist/model4.test.d.ts +1 -0
- package/dist/types.d.ts +457 -0
- package/dist/verify.d.ts +104 -0
- package/dist/verify.test.d.ts +1 -0
- package/package.json +56 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,908 @@
|
|
|
1
|
+
// src/model3.ts
|
|
2
|
+
var enc = new TextEncoder();
|
|
3
|
+
var subtle = () => globalThis.crypto.subtle;
|
|
4
|
+
var b64 = (b) => btoa(String.fromCharCode(...b));
|
|
5
|
+
var unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
6
|
+
var byUtf8 = (a, b) => {
|
|
7
|
+
const x = enc.encode(a), y = enc.encode(b);
|
|
8
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i] - y[i];
|
|
9
|
+
return x.length - y.length;
|
|
10
|
+
};
|
|
11
|
+
function canonicalJson(v) {
|
|
12
|
+
if (Array.isArray(v)) return `[${v.map((x) => canonicalJson(x === void 0 ? null : x)).join(",")}]`;
|
|
13
|
+
if (v && typeof v === "object") {
|
|
14
|
+
const o = v;
|
|
15
|
+
const keys = Object.keys(o).filter((k) => o[k] !== void 0).sort(byUtf8);
|
|
16
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`).join(",")}}`;
|
|
17
|
+
}
|
|
18
|
+
return JSON.stringify(v ?? null);
|
|
19
|
+
}
|
|
20
|
+
async function signer(k) {
|
|
21
|
+
if (k.sign) return async (m) => k.sign(m);
|
|
22
|
+
if (!k.privateKey) throw new Error("signingKey needs privateKey or sign");
|
|
23
|
+
const pkcs8 = new Uint8Array([...unb64("MC4CAQAwBQYDK2VwBCIEIA=="), ...unb64(k.privateKey)]);
|
|
24
|
+
const key = await subtle().importKey("pkcs8", pkcs8, { name: "Ed25519" }, false, ["sign"]);
|
|
25
|
+
return async (m) => new Uint8Array(await subtle().sign("Ed25519", key, m));
|
|
26
|
+
}
|
|
27
|
+
async function aes(key, use) {
|
|
28
|
+
return subtle().importKey("raw", unb64(key), "AES-GCM", false, [use]);
|
|
29
|
+
}
|
|
30
|
+
async function wire(events, seal, signingKey) {
|
|
31
|
+
if (!seal && !signingKey) return events;
|
|
32
|
+
const key = seal ? await aes(seal.key, "encrypt") : void 0;
|
|
33
|
+
const sign = signingKey ? await signer(signingKey) : void 0;
|
|
34
|
+
const out = [];
|
|
35
|
+
for (const e of events) {
|
|
36
|
+
const o = JSON.parse(JSON.stringify(e));
|
|
37
|
+
for (const path of seal?.paths ?? []) {
|
|
38
|
+
const parts = path.split(".");
|
|
39
|
+
const last = parts.pop();
|
|
40
|
+
let node2 = o;
|
|
41
|
+
for (const p of parts) node2 = node2 && typeof node2 === "object" ? node2[p] : void 0;
|
|
42
|
+
if (!node2 || typeof node2 !== "object" || !(last in node2)) continue;
|
|
43
|
+
const parent = node2;
|
|
44
|
+
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
|
|
45
|
+
const ct = await subtle().encrypt({ name: "AES-GCM", iv, additionalData: enc.encode(path) }, key, enc.encode(canonicalJson(parent[last])));
|
|
46
|
+
parent[last] = { $wt_cse: seal.kid, alg: "A256GCM", iv: b64(iv), ct: b64(new Uint8Array(ct)) };
|
|
47
|
+
}
|
|
48
|
+
if (sign) {
|
|
49
|
+
delete o.signature;
|
|
50
|
+
const sig = await sign(enc.encode(canonicalJson(o)));
|
|
51
|
+
o.signature = { kid: signingKey.kid, alg: "ed25519", sig: b64(sig) };
|
|
52
|
+
}
|
|
53
|
+
out.push(o);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
async function openSealed(key, path, envelope) {
|
|
58
|
+
const pt = await subtle().decrypt({ name: "AES-GCM", iv: unb64(envelope.iv), additionalData: enc.encode(path) }, await aes(key, "decrypt"), unb64(envelope.ct));
|
|
59
|
+
return JSON.parse(new TextDecoder().decode(pt));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/model4.ts
|
|
63
|
+
var ActivityQueue = class {
|
|
64
|
+
#client;
|
|
65
|
+
#o;
|
|
66
|
+
#buf = [];
|
|
67
|
+
#timer;
|
|
68
|
+
#sending = Promise.resolve();
|
|
69
|
+
constructor(client, o = {}) {
|
|
70
|
+
this.#client = client;
|
|
71
|
+
this.#o = {
|
|
72
|
+
maxBatch: Math.min(Math.max(o.maxBatch ?? 100, 1), 1e3),
|
|
73
|
+
flushMs: o.flushMs ?? 1e3,
|
|
74
|
+
maxBuffer: o.maxBuffer ?? 1e4,
|
|
75
|
+
mode: o.mode ?? "open",
|
|
76
|
+
onDrop: o.onDrop,
|
|
77
|
+
flushOnExit: o.flushOnExit ?? true
|
|
78
|
+
};
|
|
79
|
+
this.#timer = setInterval(() => {
|
|
80
|
+
void this.flush();
|
|
81
|
+
}, this.#o.flushMs);
|
|
82
|
+
this.#timer.unref?.();
|
|
83
|
+
const p = typeof process !== "undefined" ? process : void 0;
|
|
84
|
+
if (this.#o.flushOnExit && p?.once) {
|
|
85
|
+
for (const sig of ["beforeExit", "SIGTERM", "SIGINT"]) p.once(sig, () => {
|
|
86
|
+
void this.close();
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** Events waiting to be sent. */
|
|
91
|
+
get size() {
|
|
92
|
+
return this.#buf.length;
|
|
93
|
+
}
|
|
94
|
+
/** Queue one event. In `closed` mode a full buffer rejects; in `open` mode it drops and calls `onDrop`. */
|
|
95
|
+
async enqueue(e) {
|
|
96
|
+
const ev = { ...e, idempotency_key: e.idempotency_key ?? globalThis.crypto.randomUUID() };
|
|
97
|
+
if (this.#buf.length >= this.#o.maxBuffer) {
|
|
98
|
+
const err = new Error("activity queue full");
|
|
99
|
+
if (this.#o.mode === "closed") throw err;
|
|
100
|
+
this.#o.onDrop?.([ev], err);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
this.#buf.push(ev);
|
|
104
|
+
if (this.#buf.length >= this.#o.maxBatch) void this.flush();
|
|
105
|
+
}
|
|
106
|
+
/** Send everything queued now; resolves when sent (or dropped). */
|
|
107
|
+
flush() {
|
|
108
|
+
this.#sending = this.#sending.then(async () => {
|
|
109
|
+
while (this.#buf.length) {
|
|
110
|
+
const batch = this.#buf.splice(0, this.#o.maxBatch);
|
|
111
|
+
try {
|
|
112
|
+
const r = await this.#client.recordBatch(batch, { partial: true });
|
|
113
|
+
const bad = (r.rejected ?? []).map((x) => batch[x.index]).filter((x) => !!x);
|
|
114
|
+
if (bad.length) this.#o.onDrop?.(bad, r.rejected);
|
|
115
|
+
} catch (err) {
|
|
116
|
+
this.#o.onDrop?.(batch, err);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
return this.#sending;
|
|
121
|
+
}
|
|
122
|
+
/** Stop the timer and flush. */
|
|
123
|
+
async close() {
|
|
124
|
+
if (this.#timer) clearInterval(this.#timer);
|
|
125
|
+
this.#timer = void 0;
|
|
126
|
+
await this.flush();
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
var header = (r, k) => {
|
|
130
|
+
const v = r.headers?.[k];
|
|
131
|
+
return Array.isArray(v) ? v[0] : v;
|
|
132
|
+
};
|
|
133
|
+
function middleware(queue, event) {
|
|
134
|
+
return (req, res, next) => {
|
|
135
|
+
const done = () => {
|
|
136
|
+
try {
|
|
137
|
+
const ctx = {
|
|
138
|
+
method: req.method ?? "GET",
|
|
139
|
+
path: (req.originalUrl ?? req.url ?? "/").split("?")[0],
|
|
140
|
+
status: res.statusCode ?? 0,
|
|
141
|
+
ip: req.ip ?? req.socket?.remoteAddress,
|
|
142
|
+
userAgent: header(req, "user-agent"),
|
|
143
|
+
requestId: header(req, "x-request-id")
|
|
144
|
+
};
|
|
145
|
+
const e = event(req, ctx);
|
|
146
|
+
if (!e) return;
|
|
147
|
+
const context = { ...ctx.ip ? { ip: ctx.ip } : {}, ...ctx.userAgent ? { user_agent: ctx.userAgent } : {}, ...ctx.requestId ? { request_id: ctx.requestId } : {}, ...e.context };
|
|
148
|
+
void queue.enqueue({ ...e, context }).catch(() => {
|
|
149
|
+
});
|
|
150
|
+
} catch {
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
(res.once ?? res.on)?.call(res, "finish", done);
|
|
154
|
+
next();
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// src/ed25519ph.ts
|
|
159
|
+
var P = 2n ** 255n - 19n;
|
|
160
|
+
var L = 2n ** 252n + 27742317777372353535851937790883648493n;
|
|
161
|
+
var md = (a) => (a % P + P) % P;
|
|
162
|
+
var pw = (b, e) => {
|
|
163
|
+
let r = 1n;
|
|
164
|
+
for (b = md(b); e > 0n; e >>= 1n, b = md(b * b)) if (e & 1n) r = md(r * b);
|
|
165
|
+
return r;
|
|
166
|
+
};
|
|
167
|
+
var D = md(-121665n * pw(121666n, P - 2n));
|
|
168
|
+
var SQRT_M1 = pw(2n, (P - 1n) / 4n);
|
|
169
|
+
var add = ([x1, y1, z1, t1], [x2, y2, z2, t2]) => {
|
|
170
|
+
const a = md((y1 - x1) * (y2 - x2)), b = md((y1 + x1) * (y2 + x2));
|
|
171
|
+
const c = md(t1 * 2n * D * t2), d = md(z1 * 2n * z2);
|
|
172
|
+
const e = b - a, f = d - c, g = d + c, h = b + a;
|
|
173
|
+
return [md(e * f), md(g * h), md(f * g), md(e * h)];
|
|
174
|
+
};
|
|
175
|
+
var mul = (s, p) => {
|
|
176
|
+
let q = [0n, 1n, 1n, 0n];
|
|
177
|
+
for (; s > 0n; s >>= 1n, p = add(p, p)) if (s & 1n) q = add(q, p);
|
|
178
|
+
return q;
|
|
179
|
+
};
|
|
180
|
+
var point = (y, sign) => {
|
|
181
|
+
const xx = md((y * y - 1n) * pw(D * y * y + 1n, P - 2n));
|
|
182
|
+
let x = pw(xx, (P + 3n) / 8n);
|
|
183
|
+
if (md(x * x - xx) !== 0n) x = md(x * SQRT_M1);
|
|
184
|
+
if (md(x * x - xx) !== 0n || x === 0n && sign === 1n) return null;
|
|
185
|
+
if ((x & 1n) !== sign) x = P - x;
|
|
186
|
+
return [x, y, 1n, md(x * y)];
|
|
187
|
+
};
|
|
188
|
+
var le = (b) => b.reduceRight((n, x) => n << 8n | BigInt(x), 0n);
|
|
189
|
+
var decode = (b) => {
|
|
190
|
+
if (b.length !== 32) return null;
|
|
191
|
+
const n = le(b), y = n & (1n << 255n) - 1n;
|
|
192
|
+
return y >= P ? null : point(y, n >> 255n);
|
|
193
|
+
};
|
|
194
|
+
var G = point(md(4n * pw(5n, P - 2n)), 0n);
|
|
195
|
+
var eq = (a, b) => md(a[0] * b[2] - b[0] * a[2]) === 0n && md(a[1] * b[2] - b[1] * a[2]) === 0n;
|
|
196
|
+
var DOM2 = new TextEncoder().encode("SigEd25519 no Ed25519 collisions\0");
|
|
197
|
+
async function ed25519phVerify(pk, sig, digest) {
|
|
198
|
+
if (sig.length !== 64 || digest.length !== 64) return false;
|
|
199
|
+
const a = decode(pk), r = decode(sig.subarray(0, 32)), s = le(sig.subarray(32));
|
|
200
|
+
if (!a || !r || s >= L) return false;
|
|
201
|
+
const msg = new Uint8Array(DOM2.length + 128);
|
|
202
|
+
msg.set(DOM2);
|
|
203
|
+
msg.set(sig.subarray(0, 32), DOM2.length);
|
|
204
|
+
msg.set(pk, DOM2.length + 32);
|
|
205
|
+
msg.set(digest, DOM2.length + 64);
|
|
206
|
+
const h = le(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512", msg))) % L;
|
|
207
|
+
return eq(mul(s, G), add(r, mul(h, a)));
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// src/verify.ts
|
|
211
|
+
var enc2 = new TextEncoder();
|
|
212
|
+
function fromHex(s) {
|
|
213
|
+
return new Uint8Array((s.match(/../g) ?? []).map((h) => parseInt(h, 16)));
|
|
214
|
+
}
|
|
215
|
+
function fromB64(s) {
|
|
216
|
+
const b = atob(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "="));
|
|
217
|
+
return Uint8Array.from(b, (c) => c.charCodeAt(0));
|
|
218
|
+
}
|
|
219
|
+
var toHex = (b) => [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
220
|
+
var cat = (...p) => {
|
|
221
|
+
const out = new Uint8Array(p.reduce((n, x) => n + x.length, 0));
|
|
222
|
+
p.reduce((o, x) => (out.set(x, o), o + x.length), 0);
|
|
223
|
+
return out;
|
|
224
|
+
};
|
|
225
|
+
var sha = async (b) => new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", cat(b)));
|
|
226
|
+
function canonical(v) {
|
|
227
|
+
if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
|
|
228
|
+
if (v && typeof v === "object") {
|
|
229
|
+
const o = v;
|
|
230
|
+
return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonical(o[k])}`).join(",")}}`;
|
|
231
|
+
}
|
|
232
|
+
return v === void 0 ? "null" : JSON.stringify(v);
|
|
233
|
+
}
|
|
234
|
+
async function chainHash(prevHex, body) {
|
|
235
|
+
return toHex(await sha(cat(fromHex(prevHex), enc2.encode(body))));
|
|
236
|
+
}
|
|
237
|
+
async function verifyRows(rows, anchor) {
|
|
238
|
+
let seq = anchor?.seq ?? 0, prev = anchor?.hash ?? "";
|
|
239
|
+
for (const r of rows) {
|
|
240
|
+
let bodySeq;
|
|
241
|
+
try {
|
|
242
|
+
bodySeq = JSON.parse(r.body).seq;
|
|
243
|
+
} catch {
|
|
244
|
+
bodySeq = void 0;
|
|
245
|
+
}
|
|
246
|
+
if (r.seq !== seq + 1 || r.prev_hash !== prev || bodySeq !== r.seq || await chainHash(r.prev_hash, r.body) !== r.hash) return r.seq;
|
|
247
|
+
seq = r.seq;
|
|
248
|
+
prev = r.hash;
|
|
249
|
+
}
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
async function verifySignature(s, keys) {
|
|
253
|
+
const k = keys.find((x) => x.kid === s.kid);
|
|
254
|
+
const sig = s.signature ?? s.sig;
|
|
255
|
+
if (!k || !sig) return false;
|
|
256
|
+
try {
|
|
257
|
+
const key = await globalThis.crypto.subtle.importKey("raw", fromB64(k.x), { name: "Ed25519" }, false, ["verify"]);
|
|
258
|
+
return await globalThis.crypto.subtle.verify({ name: "Ed25519" }, key, fromB64(sig), enc2.encode(s.message));
|
|
259
|
+
} catch {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
var merkleLeaf = async (chainHashHex) => toHex(await sha(cat(new Uint8Array([0]), fromHex(chainHashHex))));
|
|
264
|
+
var node = (l, r) => sha(cat(new Uint8Array([1]), l, r));
|
|
265
|
+
async function merkleRoot(leaves) {
|
|
266
|
+
const rec = async (l) => {
|
|
267
|
+
if (l.length === 0) return sha(new Uint8Array());
|
|
268
|
+
if (l.length === 1) return cat(l[0]);
|
|
269
|
+
let k = 1;
|
|
270
|
+
while (k * 2 < l.length) k *= 2;
|
|
271
|
+
return node(await rec(l.slice(0, k)), await rec(l.slice(k)));
|
|
272
|
+
};
|
|
273
|
+
return toHex(await rec(leaves.map(fromHex)));
|
|
274
|
+
}
|
|
275
|
+
async function verifyInclusion(leaf, index, size, path, root) {
|
|
276
|
+
if (index >= size) return false;
|
|
277
|
+
let f = index, s = size - 1, r = fromHex(leaf);
|
|
278
|
+
for (const p of path.map(fromHex)) {
|
|
279
|
+
if (s === 0) return false;
|
|
280
|
+
if (f % 2 === 1 || f === s) {
|
|
281
|
+
r = await node(p, r);
|
|
282
|
+
while (f % 2 === 0 && f !== 0) {
|
|
283
|
+
f >>= 1;
|
|
284
|
+
s >>= 1;
|
|
285
|
+
}
|
|
286
|
+
} else r = await node(r, p);
|
|
287
|
+
f >>= 1;
|
|
288
|
+
s >>= 1;
|
|
289
|
+
}
|
|
290
|
+
return s === 0 && toHex(r) === root;
|
|
291
|
+
}
|
|
292
|
+
async function verifyConsistency(m, n, oldRoot, newRoot, proof) {
|
|
293
|
+
if (m < 1 || m > n) return false;
|
|
294
|
+
if (m === n) return proof.length === 0 && oldRoot === newRoot;
|
|
295
|
+
const p = proof.map(fromHex);
|
|
296
|
+
if ((m & m - 1) === 0) p.unshift(fromHex(oldRoot));
|
|
297
|
+
let fn = m - 1, sn = n - 1;
|
|
298
|
+
while (fn % 2 === 1) {
|
|
299
|
+
fn >>= 1;
|
|
300
|
+
sn >>= 1;
|
|
301
|
+
}
|
|
302
|
+
let fr = p[0], sr = p[0];
|
|
303
|
+
if (!fr || !sr) return false;
|
|
304
|
+
for (const c of p.slice(1)) {
|
|
305
|
+
if (sn === 0) return false;
|
|
306
|
+
if (fn % 2 === 1 || fn === sn) {
|
|
307
|
+
fr = await node(c, fr);
|
|
308
|
+
sr = await node(c, sr);
|
|
309
|
+
while (fn % 2 === 0 && fn !== 0) {
|
|
310
|
+
fn >>= 1;
|
|
311
|
+
sn >>= 1;
|
|
312
|
+
}
|
|
313
|
+
} else sr = await node(sr, c);
|
|
314
|
+
fn >>= 1;
|
|
315
|
+
sn >>= 1;
|
|
316
|
+
}
|
|
317
|
+
return sn === 0 && toHex(fr) === oldRoot && toHex(sr) === newRoot;
|
|
318
|
+
}
|
|
319
|
+
async function verifyCommitment(f) {
|
|
320
|
+
return toHex(await sha(cat(fromHex(f.salt), enc2.encode(canonical(f.value))))) === f.commitment;
|
|
321
|
+
}
|
|
322
|
+
async function verifyReceipt(r, keys, projectId) {
|
|
323
|
+
let m;
|
|
324
|
+
try {
|
|
325
|
+
m = JSON.parse(r.message);
|
|
326
|
+
} catch {
|
|
327
|
+
return false;
|
|
328
|
+
}
|
|
329
|
+
const shape = m[0] === "wt.activity.receipt.v1" && (!projectId || m[1] === projectId) && m[2] === r.account_id && m[3] === r.seq && m[4] === r.chain_hash && m[5] === r.leaf_index;
|
|
330
|
+
return shape && verifySignature(r, keys);
|
|
331
|
+
}
|
|
332
|
+
var parse = (m) => {
|
|
333
|
+
try {
|
|
334
|
+
const v = JSON.parse(m);
|
|
335
|
+
return Array.isArray(v) ? v : [];
|
|
336
|
+
} catch {
|
|
337
|
+
return [];
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
var b64std = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
341
|
+
var b64enc = (b) => btoa(String.fromCharCode(...b));
|
|
342
|
+
var eqb = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
|
|
343
|
+
function origin(project, account) {
|
|
344
|
+
const safe = /[A-Za-z0-9\-._~]/;
|
|
345
|
+
const acct = [...enc2.encode(account)].map((c) => safe.test(String.fromCharCode(c)) && c < 128 ? String.fromCharCode(c) : `%${c.toString(16).toUpperCase().padStart(2, "0")}`).join("");
|
|
346
|
+
return `watchtower.dev/activity/${project}/${acct}`;
|
|
347
|
+
}
|
|
348
|
+
var keyHash = async (name, typ, pk) => (await sha(cat(enc2.encode(name), new Uint8Array([10, typ]), pk))).slice(0, 4);
|
|
349
|
+
function note(text) {
|
|
350
|
+
const i = text.indexOf("\n\n");
|
|
351
|
+
if (i < 0) return null;
|
|
352
|
+
const sigs = [];
|
|
353
|
+
for (const l of text.slice(i + 2).replace(/\n$/, "").split("\n")) {
|
|
354
|
+
const m = /^— (\S+) (\S+)$/.exec(l);
|
|
355
|
+
if (!m) return null;
|
|
356
|
+
try {
|
|
357
|
+
sigs.push([m[1], b64std(m[2])]);
|
|
358
|
+
} catch {
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return { body: text.slice(0, i + 1), sigs };
|
|
363
|
+
}
|
|
364
|
+
var ed = async (pk, sig, msg) => {
|
|
365
|
+
try {
|
|
366
|
+
const key = await globalThis.crypto.subtle.importKey("raw", cat(pk), { name: "Ed25519" }, false, ["verify"]);
|
|
367
|
+
return await globalThis.crypto.subtle.verify({ name: "Ed25519" }, key, cat(sig), cat(msg));
|
|
368
|
+
} catch {
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
async function verifyNote(text, name, pk) {
|
|
373
|
+
const n = note(text), kh = await keyHash(name, 1, pk);
|
|
374
|
+
if (!n) return false;
|
|
375
|
+
for (const [nm, s] of n.sigs) if (nm === name && s.length === 68 && eqb(s.slice(0, 4), kh) && await ed(pk, s.slice(4), enc2.encode(n.body))) return true;
|
|
376
|
+
return false;
|
|
377
|
+
}
|
|
378
|
+
var checkpointOf = (body) => {
|
|
379
|
+
const l = body.split("\n");
|
|
380
|
+
try {
|
|
381
|
+
return { origin: l[0], size: Number(l[1]), root: b64std(l[2]) };
|
|
382
|
+
} catch {
|
|
383
|
+
return null;
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
async function cosigned(body, sigs, name, pk) {
|
|
387
|
+
const kh = await keyHash(name, 4, pk);
|
|
388
|
+
for (const [nm, s] of sigs) {
|
|
389
|
+
if (nm !== name || s.length !== 76 || !eqb(s.slice(0, 4), kh)) continue;
|
|
390
|
+
const t = new DataView(s.buffer, s.byteOffset + 4, 8).getBigUint64(0);
|
|
391
|
+
if (await ed(pk, s.slice(12), enc2.encode(`cosignature/v1
|
|
392
|
+
time ${t}
|
|
393
|
+
${body}`))) return true;
|
|
394
|
+
}
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
async function rekorV2(e, top, keys, logs) {
|
|
398
|
+
const statement = JSON.stringify(["wt.activity.rekor.v1", top]);
|
|
399
|
+
if (e.statement !== statement) return false;
|
|
400
|
+
try {
|
|
401
|
+
const body = b64std(String(e.canonicalized_body));
|
|
402
|
+
const h = JSON.parse(new TextDecoder().decode(body)).spec.hashedRekordV002;
|
|
403
|
+
const k = keys.find((x) => x.kid === e.kid);
|
|
404
|
+
const p = e.inclusion_proof;
|
|
405
|
+
const dig = new Uint8Array(await globalThis.crypto.subtle.digest("SHA-512", enc2.encode(statement)));
|
|
406
|
+
if (!k || h.data.digest !== b64enc(dig) || !eqb(b64std(h.signature.verifier.publicKey.rawBytes), cat(fromHex("302a300506032b6570032100"), fromB64(k.x)))) return false;
|
|
407
|
+
if (!await ed25519phVerify(fromB64(k.x), b64std(h.signature.content), dig)) return false;
|
|
408
|
+
const root = toHex(b64std(p.root_hash));
|
|
409
|
+
if (!await verifyInclusion(toHex(await sha(cat(new Uint8Array([0]), body))), p.log_index, p.tree_size, p.hashes.map((x) => toHex(b64std(x))), root)) return false;
|
|
410
|
+
const n = note(p.checkpoint.envelope), c = n && checkpointOf(n.body);
|
|
411
|
+
const pk = c ? logs[c.origin] : void 0;
|
|
412
|
+
return !!c && !!pk && c.size === p.tree_size && toHex(c.root) === root && verifyNote(p.checkpoint.envelope, c.origin, pk);
|
|
413
|
+
} catch {
|
|
414
|
+
return false;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
async function anchored(head, keys, logs) {
|
|
418
|
+
const a = head.anchor;
|
|
419
|
+
if (!a || !await verifyInclusion(await merkleLeaf(head.root), a.index, a.size, a.path, a.top)) return false;
|
|
420
|
+
for (const r of a.receipts ?? []) {
|
|
421
|
+
if (r.kind !== "rekor" || r.version !== 2) continue;
|
|
422
|
+
for (const e of r.entries ?? []) if (await rekorV2(e, a.top, keys, logs)) return true;
|
|
423
|
+
}
|
|
424
|
+
return false;
|
|
425
|
+
}
|
|
426
|
+
async function verdict(p, keys, head, trust = {}) {
|
|
427
|
+
const rows = p.data;
|
|
428
|
+
const first = rows[0];
|
|
429
|
+
if (!first) return "VALID_UNANCHORED";
|
|
430
|
+
if (first.seq === 1 && first.prev_hash) return "INVALID";
|
|
431
|
+
if (await verifyRows(rows, { seq: first.seq - 1, hash: first.prev_hash }) !== null) return "INVALID";
|
|
432
|
+
const body = JSON.parse(first.body);
|
|
433
|
+
let pruned = false;
|
|
434
|
+
if (first.seq > 1) {
|
|
435
|
+
let next = 1;
|
|
436
|
+
for (const t of [...p.pruned ?? []].sort((a, b) => a.from_seq - b.from_seq)) {
|
|
437
|
+
const m = parse(t.message);
|
|
438
|
+
if (!await verifySignature(t, keys) || m[0] !== "wt.activity.pruned.v1" || m[3] !== t.from_seq || m[4] !== t.to_seq || m[5] !== t.last_hash) return "INVALID";
|
|
439
|
+
if (t.from_seq > next) break;
|
|
440
|
+
next = Math.max(next, t.to_seq + 1);
|
|
441
|
+
if (t.to_seq === first.seq - 1 && t.last_hash !== first.prev_hash) return "INVALID";
|
|
442
|
+
}
|
|
443
|
+
const erased = (p.erased ?? []).some((e) => e.from_seq <= next && e.to_seq >= first.seq - 1);
|
|
444
|
+
if (next < first.seq && !erased) return "INVALID";
|
|
445
|
+
pruned = true;
|
|
446
|
+
}
|
|
447
|
+
const hashes = new Map(rows.map((r) => [r.seq, r.hash]));
|
|
448
|
+
const cp = p.checkpoint;
|
|
449
|
+
if (cp) {
|
|
450
|
+
const m = parse(cp.message);
|
|
451
|
+
if (m[0] !== "wt.activity.checkpoint.v1" || m[3] !== cp.seq || m[4] !== cp.hash || (hashes.get(cp.seq) ?? cp.hash) !== cp.hash || !await verifySignature(cp, keys)) return "INVALID";
|
|
452
|
+
}
|
|
453
|
+
let ok = false;
|
|
454
|
+
if (head) {
|
|
455
|
+
const m = parse(head.message);
|
|
456
|
+
if (m[0] !== "wt.activity.merkle.v1" || m[3] !== head.from_seq || m[4] !== head.to_seq || m[5] !== head.root || head.size !== head.to_seq - head.from_seq + 1 || !await verifySignature(head, keys)) return "INVALID";
|
|
457
|
+
const cover = [];
|
|
458
|
+
for (let s = head.from_seq; s <= head.to_seq; s++) {
|
|
459
|
+
const h = hashes.get(s);
|
|
460
|
+
if (h) cover.push(h);
|
|
461
|
+
}
|
|
462
|
+
if (cover.length === head.size) {
|
|
463
|
+
if (await merkleRoot(await Promise.all(cover.map(merkleLeaf))) !== head.root) return "INVALID";
|
|
464
|
+
const k = keys.find((x) => x.kid === head.kid);
|
|
465
|
+
if (head.note) {
|
|
466
|
+
const n2 = note(head.note), c = n2 && checkpointOf(n2.body);
|
|
467
|
+
if (!k || !c || c.size !== head.size || toHex(c.root) !== head.root || !await verifyNote(head.note, origin(body.project_id ?? "", body.account_id ?? ""), fromB64(k.x))) return "INVALID";
|
|
468
|
+
}
|
|
469
|
+
let text = head.note ?? "";
|
|
470
|
+
for (const c of head.cosignatures ?? []) if (!text.includes(c.line)) text += `${c.line}
|
|
471
|
+
`;
|
|
472
|
+
const n = text ? note(text) : null;
|
|
473
|
+
let count = 0;
|
|
474
|
+
for (const [name, x] of Object.entries(trust.witnesses ?? {})) if (n && await cosigned(n.body, n.sigs, name, fromB64(x))) count++;
|
|
475
|
+
const logs = Object.fromEntries(Object.entries(trust.rekorLogs ?? {}).map(([o, x]) => [o, fromB64(x)]));
|
|
476
|
+
ok = count >= (trust.quorum ?? 0) && await anchored(head, keys, logs);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (pruned) return "VALID_PRUNED";
|
|
480
|
+
return ok ? "VALID" : "VALID_UNANCHORED";
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// src/index.ts
|
|
484
|
+
var OTEL = "@opentelemetry/api";
|
|
485
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
486
|
+
var otel;
|
|
487
|
+
function otelSpan() {
|
|
488
|
+
otel ??= import(OTEL).then(
|
|
489
|
+
(m) => () => {
|
|
490
|
+
const c = m.trace?.getActiveSpan?.()?.spanContext();
|
|
491
|
+
return c && HEX32.test(c.traceId) && !/^0+$/.test(c.traceId) ? { trace_id: c.traceId, span_id: c.spanId } : void 0;
|
|
492
|
+
},
|
|
493
|
+
() => void 0
|
|
494
|
+
);
|
|
495
|
+
return otel;
|
|
496
|
+
}
|
|
497
|
+
var ActivityError = class extends Error {
|
|
498
|
+
status;
|
|
499
|
+
type;
|
|
500
|
+
title;
|
|
501
|
+
detail;
|
|
502
|
+
instance;
|
|
503
|
+
extensions;
|
|
504
|
+
constructor(status, p = {}) {
|
|
505
|
+
const { type, title, detail, instance, status: _s, ...ext } = p;
|
|
506
|
+
const t = typeof title === "string" ? title : `HTTP ${status}`;
|
|
507
|
+
super(typeof detail === "string" ? `${t}: ${detail}` : t);
|
|
508
|
+
this.name = "ActivityError";
|
|
509
|
+
this.status = status;
|
|
510
|
+
this.type = typeof type === "string" ? type : "about:blank";
|
|
511
|
+
this.title = t;
|
|
512
|
+
this.detail = typeof detail === "string" ? detail : void 0;
|
|
513
|
+
this.instance = typeof instance === "string" ? instance : void 0;
|
|
514
|
+
this.extensions = ext;
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
var BATCH = 100;
|
|
518
|
+
var PARTIAL_BATCH = 1e3;
|
|
519
|
+
var defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
520
|
+
function retryAfterMs(h) {
|
|
521
|
+
if (!h) return void 0;
|
|
522
|
+
const s = Number(h);
|
|
523
|
+
if (Number.isFinite(s)) return Math.max(0, s * 1e3);
|
|
524
|
+
const d = Date.parse(h);
|
|
525
|
+
return Number.isNaN(d) ? void 0 : Math.max(0, d - Date.now());
|
|
526
|
+
}
|
|
527
|
+
var Activity = class {
|
|
528
|
+
#key;
|
|
529
|
+
#apiKey;
|
|
530
|
+
#base;
|
|
531
|
+
#region;
|
|
532
|
+
#regionDone = false;
|
|
533
|
+
#fetch;
|
|
534
|
+
#sleep;
|
|
535
|
+
#retries;
|
|
536
|
+
#trace;
|
|
537
|
+
#signingKey;
|
|
538
|
+
#seal;
|
|
539
|
+
constructor(opts) {
|
|
540
|
+
if (typeof window !== "undefined" && !opts.allowBrowser) {
|
|
541
|
+
throw new Error("@watchtowerobservability/activity is server-only: the secret key would ship to browsers. Use @watchtowerobservability/activity-web there.");
|
|
542
|
+
}
|
|
543
|
+
if (!opts?.secretKey) throw new Error("secretKey is required");
|
|
544
|
+
this.#key = opts.secretKey;
|
|
545
|
+
this.#apiKey = opts.apiKey;
|
|
546
|
+
const base = opts.baseUrl ?? (typeof process !== "undefined" ? process.env.WT_API_URL : void 0);
|
|
547
|
+
if (!base) throw new Error("baseUrl (or the WT_API_URL environment variable) is required");
|
|
548
|
+
this.#base = base.replace(/\/+$/, "");
|
|
549
|
+
this.#region = opts.region;
|
|
550
|
+
this.#fetch = opts.fetch ?? ((...a) => globalThis.fetch(...a));
|
|
551
|
+
this.#sleep = opts.sleep ?? defaultSleep;
|
|
552
|
+
this.#retries = opts.maxRetries ?? 4;
|
|
553
|
+
this.#trace = opts.traceContext ?? true;
|
|
554
|
+
this.#signingKey = opts.signingKey;
|
|
555
|
+
this.#seal = opts.seal;
|
|
556
|
+
}
|
|
557
|
+
/** Never expose the key via console.log / util.inspect / JSON.stringify. */
|
|
558
|
+
toJSON() {
|
|
559
|
+
return { baseUrl: this.#base };
|
|
560
|
+
}
|
|
561
|
+
/** With `region`: that region's API base from the directory, once (a failed lookup keeps `baseUrl`). */
|
|
562
|
+
async #resolveRegion() {
|
|
563
|
+
if (!this.#region || this.#regionDone) return;
|
|
564
|
+
this.#regionDone = true;
|
|
565
|
+
try {
|
|
566
|
+
const res = await this.#fetch(`${this.#base}/v1/regions`, { method: "GET" });
|
|
567
|
+
const d = await res.json();
|
|
568
|
+
const hit = d.current === this.#region ? void 0 : d.data?.find((r) => r.region === this.#region);
|
|
569
|
+
if (hit) this.#base = hit.api_base_url.replace(/\/+$/, "");
|
|
570
|
+
} catch {
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
async #request(method, path, body, key = this.#key) {
|
|
574
|
+
const backoff = (attempt) => Math.min(3e4, 250 * 2 ** attempt * (0.5 + Math.random() / 2));
|
|
575
|
+
await this.#resolveRegion();
|
|
576
|
+
let moved = false;
|
|
577
|
+
for (let attempt = 0; ; attempt++) {
|
|
578
|
+
let res;
|
|
579
|
+
try {
|
|
580
|
+
res = await this.#fetch(this.#base + path, {
|
|
581
|
+
method,
|
|
582
|
+
headers: {
|
|
583
|
+
authorization: `Bearer ${key}`,
|
|
584
|
+
...body === void 0 ? {} : { "content-type": "application/json" }
|
|
585
|
+
},
|
|
586
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
587
|
+
});
|
|
588
|
+
} catch (e) {
|
|
589
|
+
if (attempt >= this.#retries) throw e;
|
|
590
|
+
await this.#sleep(backoff(attempt));
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
if (res.ok) return res;
|
|
594
|
+
if ((res.status === 429 || res.status >= 500) && attempt < this.#retries) {
|
|
595
|
+
const wait = retryAfterMs(res.headers.get("retry-after")) ?? backoff(attempt);
|
|
596
|
+
await res.body?.cancel().catch(() => {
|
|
597
|
+
});
|
|
598
|
+
await this.#sleep(wait);
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
let p;
|
|
602
|
+
try {
|
|
603
|
+
p = await res.json();
|
|
604
|
+
} catch {
|
|
605
|
+
}
|
|
606
|
+
if (res.status === 421 && !moved && typeof p?.api_base_url === "string") {
|
|
607
|
+
moved = true;
|
|
608
|
+
this.#base = p.api_base_url.replace(/\/+$/, "");
|
|
609
|
+
attempt--;
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
throw new ActivityError(res.status, p);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
async record(event, o = {}) {
|
|
616
|
+
return o.dryRun ? this.validate([event]) : this.recordBatch([event]);
|
|
617
|
+
}
|
|
618
|
+
/** Normalized stored form, schema warnings, missing template and PII detector hits; stores nothing. */
|
|
619
|
+
async validate(events) {
|
|
620
|
+
return this.#json("POST", "/v1/activity/events/validate", { events: Array.isArray(events) ? events : [events] });
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* `partial: true`: batches of 1000, bad events are listed in `rejected` instead of failing the batch.
|
|
624
|
+
* `receipts: true`: a signed receipt per accepted event (check with `verifyReceipt`).
|
|
625
|
+
* `async: true`: queued server-side; poll `batch(id)` for each of `batch_ids`.
|
|
626
|
+
*/
|
|
627
|
+
async recordBatch(events, o = {}) {
|
|
628
|
+
const span = await this.#spanIds();
|
|
629
|
+
const prepared = await wire(events.map((e) => ({
|
|
630
|
+
...span && !e.trace_id ? span : {},
|
|
631
|
+
...e,
|
|
632
|
+
idempotency_key: e.idempotency_key ?? globalThis.crypto.randomUUID()
|
|
633
|
+
})), this.#seal, this.#signingKey);
|
|
634
|
+
const size = o.partial ? PARTIAL_BATCH : BATCH;
|
|
635
|
+
const out = { accepted: 0, rejected: [], warnings: [], receipts: [], coalesced: [], batch_ids: [] };
|
|
636
|
+
const q = [o.partial && "partial=true", o.receipts && "receipts=true", o.async && "async=true"].filter(Boolean).join("&");
|
|
637
|
+
for (let i = 0; i < prepared.length; i += size) {
|
|
638
|
+
const r = await this.#json("POST", `/v1/activity/events${q ? `?${q}` : ""}`, { events: prepared.slice(i, i + size) });
|
|
639
|
+
out.accepted += r.accepted;
|
|
640
|
+
for (const x of r.rejected ?? []) out.rejected.push({ ...x, index: x.index + i });
|
|
641
|
+
for (const x of r.warnings ?? []) out.warnings.push({ ...x, index: x.index + i });
|
|
642
|
+
for (const x of r.receipts ?? []) out.receipts.push({ ...x, index: x.index + i });
|
|
643
|
+
for (const x of r.coalesced ?? []) out.coalesced.push({ ...x, index: x.index + i });
|
|
644
|
+
if (r.batch_id) out.batch_ids.push(r.batch_id);
|
|
645
|
+
}
|
|
646
|
+
return {
|
|
647
|
+
accepted: out.accepted,
|
|
648
|
+
...o.partial ? { rejected: out.rejected } : {},
|
|
649
|
+
...out.warnings.length ? { warnings: out.warnings } : {},
|
|
650
|
+
...out.receipts.length ? { receipts: out.receipts } : {},
|
|
651
|
+
...out.coalesced.length ? { coalesced: out.coalesced } : {},
|
|
652
|
+
...out.batch_ids.length ? { batch_ids: out.batch_ids } : {}
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
/** The state of an async batch (`recordBatch(..., { async: true })`). */
|
|
656
|
+
async batch(id) {
|
|
657
|
+
return this.#json("GET", `/v1/activity/batches/${encodeURIComponent(id)}`);
|
|
658
|
+
}
|
|
659
|
+
/** One event by id (with lookup `labels`). */
|
|
660
|
+
async getEvent(projectId, id) {
|
|
661
|
+
return this.#json("GET", `${this.#prj(projectId)}/events/${encodeURIComponent(id)}`);
|
|
662
|
+
}
|
|
663
|
+
async #spanIds() {
|
|
664
|
+
if (this.#trace === false) return void 0;
|
|
665
|
+
if (typeof this.#trace === "function") return this.#trace();
|
|
666
|
+
return (await otelSpan())?.();
|
|
667
|
+
}
|
|
668
|
+
/** Write 25 realistic sample events into one account (default `sample`) through the ingest pipeline. */
|
|
669
|
+
async samples(projectId, o = {}) {
|
|
670
|
+
return this.#json("POST", `${this.#prj(projectId)}/samples`, o.accountId ? { account_id: o.accountId } : {});
|
|
671
|
+
}
|
|
672
|
+
async createViewerSession(o) {
|
|
673
|
+
const j = await this.#json("POST", "/v1/activity/sessions", {
|
|
674
|
+
account_id: o.accountId,
|
|
675
|
+
actor_id: o.actorId,
|
|
676
|
+
expires_in: o.expiresIn,
|
|
677
|
+
capabilities: o.capabilities,
|
|
678
|
+
locale: o.locale,
|
|
679
|
+
time_zone: o.timeZone,
|
|
680
|
+
sub_scope: o.subScope && { target_type: o.subScope.targetType, target_id: o.subScope.targetId }
|
|
681
|
+
});
|
|
682
|
+
return { token: j.token, url: j.url, expiresAt: j.expires_at, ...j.jti ? { jti: j.jti } : {} };
|
|
683
|
+
}
|
|
684
|
+
/** Revoke one viewer session by its `jti`. */
|
|
685
|
+
async revokeSession(jti) {
|
|
686
|
+
await this.#request("DELETE", `/v1/activity/sessions/${encodeURIComponent(jti)}`);
|
|
687
|
+
}
|
|
688
|
+
/** Revoke every live viewer session of an account (e.g. on offboarding). Returns how many were live. */
|
|
689
|
+
async revokeAccountSessions(accountId) {
|
|
690
|
+
return this.#json("POST", "/v1/activity/sessions/revoke", { account_id: accountId });
|
|
691
|
+
}
|
|
692
|
+
/** Project management calls authenticate with `apiKey`. */
|
|
693
|
+
#mgmt(method, path, body) {
|
|
694
|
+
if (!this.#apiKey) throw new Error("apiKey (an org API key) is required for accountTokens(), streams(), rules() and privacy()");
|
|
695
|
+
return this.#request(method, path, body, this.#apiKey);
|
|
696
|
+
}
|
|
697
|
+
async #mjson(method, path, body) {
|
|
698
|
+
return await (await this.#mgmt(method, path, body)).json();
|
|
699
|
+
}
|
|
700
|
+
/** End-customer API tokens (`wta_acct_...`) of one account; the token string is in the create response only. */
|
|
701
|
+
accountTokens(projectId, accountId) {
|
|
702
|
+
const base = `${this.#prj(projectId)}/accounts/${encodeURIComponent(accountId)}/tokens`;
|
|
703
|
+
return {
|
|
704
|
+
list: () => this.#mjson("GET", base),
|
|
705
|
+
create: (o) => this.#mjson("POST", base, o),
|
|
706
|
+
revoke: (id) => this.#mgmt("DELETE", `${base}/${encodeURIComponent(id)}`).then(() => void 0)
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
/** Email a one-time link to the account's hosted page (single use; it becomes a fresh session when opened). */
|
|
710
|
+
async invite(projectId, accountId, o) {
|
|
711
|
+
return this.#mjson("POST", `${this.#prj(projectId)}/accounts/${encodeURIComponent(accountId)}/invite`, o);
|
|
712
|
+
}
|
|
713
|
+
/** SIEM / log streams (secrets are write-only). */
|
|
714
|
+
streams(projectId) {
|
|
715
|
+
const base = `${this.#prj(projectId)}/streams`;
|
|
716
|
+
const one = (id) => `${base}/${encodeURIComponent(id)}`;
|
|
717
|
+
return {
|
|
718
|
+
list: () => this.#mjson("GET", base),
|
|
719
|
+
get: (id) => this.#mjson("GET", one(id)),
|
|
720
|
+
create: (s) => this.#mjson("POST", base, s),
|
|
721
|
+
update: (id, patch) => this.#mjson("PATCH", one(id), patch),
|
|
722
|
+
/** Re-send everything received since `from` (RFC 3339, within retention). */
|
|
723
|
+
replay: (id, o) => this.#mjson("POST", `${one(id)}/replay`, o),
|
|
724
|
+
delete: (id) => this.#mgmt("DELETE", one(id)).then(() => void 0),
|
|
725
|
+
/** Queues a test delivery (202); poll `get(id)` for `last_test`. */
|
|
726
|
+
test: (id) => this.#mgmt("POST", `${one(id)}/test`, {}).then(() => void 0)
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
/** Alert rules on chosen actions (email, Slack, signed webhook). */
|
|
730
|
+
rules(projectId) {
|
|
731
|
+
const base = `${this.#prj(projectId)}/rules`;
|
|
732
|
+
const one = (id) => `${base}/${encodeURIComponent(id)}`;
|
|
733
|
+
return {
|
|
734
|
+
list: () => this.#mjson("GET", base),
|
|
735
|
+
create: (r) => this.#mjson("POST", base, r),
|
|
736
|
+
/** A new `channel` returns a new `signing_secret` for webhooks. */
|
|
737
|
+
update: (id, patch) => this.#mjson("PATCH", one(id), patch),
|
|
738
|
+
delete: (id) => this.#mgmt("DELETE", one(id)).then(() => void 0)
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
/** Async exports (the file is kept 24 h) and restores of cold archives. */
|
|
742
|
+
exports(projectId) {
|
|
743
|
+
const base = `${this.#prj(projectId)}/exports`;
|
|
744
|
+
const one = (id) => `${base}/${encodeURIComponent(id)}`;
|
|
745
|
+
return {
|
|
746
|
+
create: (r = {}) => this.#mjson("POST", base, r),
|
|
747
|
+
get: (id) => this.#mjson("GET", one(id)),
|
|
748
|
+
download: async (id) => {
|
|
749
|
+
const res = await this.#mgmt("GET", `${one(id)}/download`);
|
|
750
|
+
if (!res.body) throw new ActivityError(res.status, { title: "Empty export body" });
|
|
751
|
+
return res.body;
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
archives(projectId) {
|
|
756
|
+
const base = `${this.#prj(projectId)}/archives`;
|
|
757
|
+
return {
|
|
758
|
+
list: (o = {}) => this.#mjson("GET", `${base}${o.accountId ? `?account_id=${encodeURIComponent(o.accountId)}` : ""}`),
|
|
759
|
+
/** Load an archive back for `days` (1 to 30, default 7); list it with `list(.., { source: 'archive' })`. */
|
|
760
|
+
restore: (id, o = {}) => this.#mjson("POST", `${base}/${encodeURIComponent(id)}/restore`, o)
|
|
761
|
+
};
|
|
762
|
+
}
|
|
763
|
+
/** Right to erasure. With `approval: true` the erase waits for a second member's `approve` (202 request). */
|
|
764
|
+
privacy(projectId) {
|
|
765
|
+
const base = this.#prj(projectId);
|
|
766
|
+
return {
|
|
767
|
+
eraseActor: (actorId, o = {}) => this.#mjson("POST", `${base}/actors/${encodeURIComponent(actorId)}/erase`, o.approval ? { approval: { required: true } } : {}),
|
|
768
|
+
/** Pending requests. */
|
|
769
|
+
erasures: () => this.#mjson("GET", `${base}/erasures`),
|
|
770
|
+
/** By a member other than the requester (else 404). */
|
|
771
|
+
approve: (id) => this.#mjson("POST", `${base}/erasures/${encodeURIComponent(id)}/approve`, {}),
|
|
772
|
+
/** Withdraw a pending request: its requester, or a member with the privacy permission (else 404). */
|
|
773
|
+
cancel: async (id) => {
|
|
774
|
+
await this.#mgmt("POST", `${base}/erasures/${encodeURIComponent(id)}/cancel`, {});
|
|
775
|
+
},
|
|
776
|
+
/** One event, org owners only. */
|
|
777
|
+
deleteEvent: (id) => this.#mjson("DELETE", `${base}/events/${encodeURIComponent(id)}`)
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
#prj(projectId) {
|
|
781
|
+
return `/v1/projects/${encodeURIComponent(projectId)}/activity`;
|
|
782
|
+
}
|
|
783
|
+
async #json(method, path, body) {
|
|
784
|
+
return await (await this.#request(method, path, body)).json();
|
|
785
|
+
}
|
|
786
|
+
#query(f, cursor) {
|
|
787
|
+
const m = {
|
|
788
|
+
account_id: f.accountId,
|
|
789
|
+
actor_id: f.actorId,
|
|
790
|
+
action: f.action,
|
|
791
|
+
target_type: f.targetType,
|
|
792
|
+
target_id: f.targetId,
|
|
793
|
+
q: f.q,
|
|
794
|
+
outcome: f.outcome,
|
|
795
|
+
severity: f.severity,
|
|
796
|
+
order: f.order,
|
|
797
|
+
from: f.from,
|
|
798
|
+
to: f.to,
|
|
799
|
+
limit: f.limit,
|
|
800
|
+
source: f.source,
|
|
801
|
+
since: f.since,
|
|
802
|
+
format: f.format,
|
|
803
|
+
fields: f.fields?.length ? f.fields.join(",") : void 0,
|
|
804
|
+
chain: f.chain ? 1 : void 0,
|
|
805
|
+
cursor
|
|
806
|
+
};
|
|
807
|
+
const q = new URLSearchParams();
|
|
808
|
+
for (const [k, v] of Object.entries(m)) if (v !== void 0) q.set(k, String(v));
|
|
809
|
+
const s = q.toString();
|
|
810
|
+
return s ? `?${s}` : "";
|
|
811
|
+
}
|
|
812
|
+
/** Async iterator over every event, following next_cursor page by page. */
|
|
813
|
+
async *list(projectId, filters = {}) {
|
|
814
|
+
let cursor;
|
|
815
|
+
do {
|
|
816
|
+
const page = await this.#json("GET", `${this.#prj(projectId)}/events${this.#query(filters, cursor)}`);
|
|
817
|
+
yield* page.data;
|
|
818
|
+
cursor = page.next_cursor ?? void 0;
|
|
819
|
+
} while (cursor);
|
|
820
|
+
}
|
|
821
|
+
/**
|
|
822
|
+
* Returns the streaming response body (csv, ndjson or OCSF NDJSON). `fields` keeps only those
|
|
823
|
+
* columns/keys (e.g. `['id', 'occurred_at', 'actor.email']`); `chain: true` (ndjson) adds `seq`,
|
|
824
|
+
* `chain_hash`, `prev_hash` and `chain_body` per line for offline verification.
|
|
825
|
+
*/
|
|
826
|
+
async export(projectId, o) {
|
|
827
|
+
const { format, limit: _limit, ...f } = o;
|
|
828
|
+
const res = await this.#request("GET", `${this.#prj(projectId)}/export${this.#query({ ...f, format })}`);
|
|
829
|
+
if (!res.body) throw new ActivityError(res.status, { title: "Empty export body" });
|
|
830
|
+
return res.body;
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* The browser feed's calls with one viewer credential (a viewer token from
|
|
834
|
+
* `createViewerSession` or an account token `wta_acct_...`), from server code: a backend that
|
|
835
|
+
* renders the log itself, or a support tool. The session's scopes always apply.
|
|
836
|
+
*/
|
|
837
|
+
viewer(token) {
|
|
838
|
+
const json = async (method, path, body) => await (await this.#request(method, path, body, token)).json();
|
|
839
|
+
const stream = async (path) => {
|
|
840
|
+
const res = await this.#request("GET", path, void 0, token);
|
|
841
|
+
if (!res.body) throw new ActivityError(res.status, { title: "Empty export body" });
|
|
842
|
+
return res.body;
|
|
843
|
+
};
|
|
844
|
+
const q = (f, extra = {}, cursor) => {
|
|
845
|
+
const s = new URLSearchParams(this.#query(f, cursor).slice(1));
|
|
846
|
+
for (const [k, v] of Object.entries(extra)) s.set(k, v);
|
|
847
|
+
return s.toString() ? `?${s}` : "";
|
|
848
|
+
};
|
|
849
|
+
return {
|
|
850
|
+
/** Every event of the session's scope, page by page. */
|
|
851
|
+
feed: async function* (filters = {}) {
|
|
852
|
+
let cursor;
|
|
853
|
+
do {
|
|
854
|
+
const page = await json("GET", `/v1/activity/feed${q(filters, {}, cursor)}`);
|
|
855
|
+
yield* page.data;
|
|
856
|
+
cursor = page.next_cursor ?? void 0;
|
|
857
|
+
} while (cursor);
|
|
858
|
+
},
|
|
859
|
+
facets: (field, filters = {}) => json("GET", `/v1/activity/feed/facets${q(filters, { field })}`),
|
|
860
|
+
histogram: (filters = {}) => json("GET", `/v1/activity/feed/histogram${q(filters, { bucket: "day" })}`),
|
|
861
|
+
/** Server-side saved views; account tokens only (a session gets 404 and keeps views in the browser). */
|
|
862
|
+
views: {
|
|
863
|
+
list: () => json("GET", "/v1/activity/views"),
|
|
864
|
+
create: (v) => json("POST", "/v1/activity/views", v),
|
|
865
|
+
delete: async (id) => {
|
|
866
|
+
await this.#request("DELETE", `/v1/activity/views/${encodeURIComponent(id)}`, void 0, token);
|
|
867
|
+
}
|
|
868
|
+
},
|
|
869
|
+
/** Merkle inclusion proof of one event (capability `verify`; 409 until its hour is signed). */
|
|
870
|
+
proof: (eventId) => json("GET", `/v1/activity/feed/proof?event_id=${encodeURIComponent(eventId)}`),
|
|
871
|
+
/** Consistency proof between two signed tree heads (`toSize` defaults to the latest). */
|
|
872
|
+
consistency: (fromSize, toSize) => json("GET", `/v1/activity/feed/consistency?from_size=${fromSize}${toSize ? `&to_size=${toSize}` : ""}`),
|
|
873
|
+
/** Synchronous download (capability `export`). */
|
|
874
|
+
export: (format, filters = {}) => stream(`/v1/activity/feed/export${q(filters, { format })}`),
|
|
875
|
+
exports: {
|
|
876
|
+
list: () => json("GET", "/v1/activity/exports"),
|
|
877
|
+
create: (r) => json("POST", "/v1/activity/exports", r),
|
|
878
|
+
get: (id) => json("GET", `/v1/activity/exports/${encodeURIComponent(id)}`),
|
|
879
|
+
download: (id) => stream(`/v1/activity/exports/${encodeURIComponent(id)}/download`)
|
|
880
|
+
}
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
};
|
|
884
|
+
export {
|
|
885
|
+
Activity,
|
|
886
|
+
ActivityError,
|
|
887
|
+
ActivityQueue,
|
|
888
|
+
canonical,
|
|
889
|
+
canonicalJson,
|
|
890
|
+
chainHash,
|
|
891
|
+
fromB64,
|
|
892
|
+
fromHex,
|
|
893
|
+
merkleLeaf,
|
|
894
|
+
merkleRoot,
|
|
895
|
+
middleware,
|
|
896
|
+
openSealed,
|
|
897
|
+
origin,
|
|
898
|
+
toHex,
|
|
899
|
+
verdict,
|
|
900
|
+
verifyCommitment,
|
|
901
|
+
verifyConsistency,
|
|
902
|
+
verifyInclusion,
|
|
903
|
+
verifyNote,
|
|
904
|
+
verifyReceipt,
|
|
905
|
+
verifyRows,
|
|
906
|
+
verifySignature
|
|
907
|
+
};
|
|
908
|
+
//# sourceMappingURL=index.js.map
|