@conarium-ai/core 0.2.15 → 0.2.17

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.
@@ -1,5 +1,12 @@
1
+ import { type CountersignSig } from './anchor-sign.js';
2
+ import type { SigningKey } from './keys.js';
3
+ export type AnchorRecordType = 'submit' | 'upgrade' | 'stamp';
1
4
  export interface AnchorRecord {
5
+ type: AnchorRecordType;
2
6
  id: string;
7
+ /** Customer-submitted digest (`sha256:…`). Public views expose this as `digest`. */
8
+ digest: string;
9
+ /** Entry hash — same rule as audit-hash.ts (`hash`/`sig`/`anchor` excluded). */
3
10
  hash: string;
4
11
  owner: string;
5
12
  log: 'opentimestamps';
@@ -8,6 +15,13 @@ export interface AnchorRecord {
8
15
  bitcoinBlock?: number;
9
16
  submittedAt: string;
10
17
  upgradedAt?: string;
18
+ seq: number;
19
+ prevHash: string;
20
+ /** Set on `type: 'upgrade'` — the submit/stamp seq this row confirms. */
21
+ upgradesSeq?: number;
22
+ /** Set on `type: 'stamp'` — the log seq whose entry hash was sent to calendars. */
23
+ stampedSeq?: number;
24
+ sig: CountersignSig;
11
25
  }
12
26
  export interface AnchorServiceOptions {
13
27
  /** JSONL store. Append-only: an anchoring log that can be rewritten is not one. */
@@ -16,6 +30,10 @@ export interface AnchorServiceOptions {
16
30
  tokens: Map<string, string>;
17
31
  /** Public base URL, used to build the permanent verification address. */
18
32
  publicBaseUrl: string;
33
+ /** Required. A countersign service that can start without a key is not one. */
34
+ signingKey: SigningKey;
35
+ /** Override the derived public PEM (tests). Still refused if it looks private. */
36
+ publicPem?: string;
19
37
  submitsPerMinute?: number;
20
38
  /** Injected in tests so the suite never touches a calendar server. */
21
39
  stamp?: (digest: Buffer) => Promise<string>;
@@ -25,8 +43,33 @@ export interface AnchorServiceOptions {
25
43
  ots?: string;
26
44
  }>;
27
45
  }
28
- /** Reads every record. The store is small by design — one line per anchor. */
46
+ /** Reads every record. Does not validate the chain — use readLiveStore. */
29
47
  export declare function readStore(path: string): AnchorRecord[];
48
+ export declare function validateAnchorLog(rows: AnchorRecord[]): void;
49
+ export declare function readLiveStore(path: string): AnchorRecord[];
50
+ export interface InclusionLink {
51
+ seq: number;
52
+ hash: string;
53
+ prevHash: string;
54
+ }
55
+ export interface InclusionProof {
56
+ seq: number;
57
+ hash: string;
58
+ prevHash: string;
59
+ head: {
60
+ seq: number;
61
+ hash: string;
62
+ state: 'pending' | 'bitcoin';
63
+ bitcoinBlock?: number;
64
+ };
65
+ path: InclusionLink[];
66
+ }
67
+ export declare function buildInclusionProof(rows: AnchorRecord[], target: AnchorRecord): InclusionProof;
68
+ export declare function verifyInclusionProof(record: {
69
+ seq: number;
70
+ hash: string;
71
+ prevHash: string;
72
+ }, proof: InclusionProof): boolean;
30
73
  export declare function loadTokensFile(path: string): Map<string, string>;
31
74
  export declare function createAnchorService(opts: AnchorServiceOptions): {
32
75
  app: import("express-serve-static-core").Express;
@@ -34,6 +77,10 @@ export declare function createAnchorService(opts: AnchorServiceOptions): {
34
77
  checked: number;
35
78
  upgraded: number;
36
79
  }>;
80
+ runStamp: () => Promise<{
81
+ attempted: number;
82
+ stamped: number;
83
+ }>;
37
84
  readStore: () => AnchorRecord[];
38
85
  };
39
86
  //# sourceMappingURL=anchor-service.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"anchor-service.d.ts","sourceRoot":"","sources":["../src/anchor-service.ts"],"names":[],"mappings":"AA4BA,MAAM,WAAW,YAAY;IAC3B,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,gBAAgB,CAAA;IACrB,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,SAAS,GAAG,SAAS,CAAA;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;IACnB,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAA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+ countersign endpoint.
3
3
  *
4
- * What it does: takes a hash, submits it to the OpenTimestamps calendars, keeps
5
- * the resulting proof, and serves it forever at a stable URL. A background pass
6
- * upgrades each proof from `pending` to a Bitcoin block height once the block
7
- * lands.
4
+ * What it does: takes a hash, countersigns the stored record with this
5
+ * process's Ed25519 key, submits the hash to the OpenTimestamps calendars,
6
+ * keeps the proof, and serves both forever at a stable URL. A background pass
7
+ * stamps the log head off the request path, and upgrades that stamp from
8
+ * `pending` to a Bitcoin block height by appending a new row — the original
9
+ * line is never rewritten.
8
10
  *
9
11
  * What it is NOT — and this must never be blurred in the copy: Conarium is not
10
- * the timestamp authority. The calendars and Bitcoin are. This service is
11
- * retention, a permanent public address, and the upgrade job nobody remembers
12
- * to run. It sells convenience and durability, never trust.
12
+ * the timestamp authority. The calendars and Bitcoin are. The signature is
13
+ * ours; the time is not. An anchoring service you have to trust for the stamp
14
+ * would defeat the point of anchoring. The countersign is a named claim that
15
+ * we saw this hash and wrote this record — nothing more.
13
16
  *
14
- * The proof is served raw at `/anchor/:id/ots`, so a third party can verify with
15
- * the reference OpenTimestamps client and ignore this service entirely. An
16
- * anchoring service you have to trust would defeat the point of anchoring.
17
+ * The proof is served raw at `/anchor/:id/ots`, so a third party can verify the
18
+ * stamp with the reference OpenTimestamps client and ignore this service. The
19
+ * public key is at `/anchor/key.pem`. The log head is at `/anchor/log/head`.
17
20
  *
18
21
  * The code is MIT like the rest — self-host it if you prefer. What is sold is
19
- * someone else keeping it alive.
22
+ * the key and someone else keeping the log alive.
20
23
  */
21
24
  import express from 'express';
22
- import { randomBytes, timingSafeEqual } from 'crypto';
23
- import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
25
+ import { createPublicKey, randomBytes, timingSafeEqual } from 'crypto';
26
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'fs';
24
27
  import { dirname } from 'path';
25
28
  import { hashPrefixToBuffer } from './anchor.js';
29
+ import { computeEntryHash, GENESIS_HASH } from './audit-hash.js';
30
+ import { isServablePublicPem, signAnchorRecord } from './anchor-sign.js';
26
31
  import { stampHash, upgradeProof } from './ots/client.js';
27
32
  // Matches conarium-stamp. One slow calendar out of four is normal; 20s was not
28
33
  // enough in practice and produced a 502 for a submission that would have landed.
@@ -44,7 +49,7 @@ async function defaultUpgrade(otsBase64) {
44
49
  ots: up.otsBytes.toString('base64'),
45
50
  };
46
51
  }
47
- /** Reads every record. The store is small by design — one line per anchor. */
52
+ /** Reads every record. Does not validate the chain — use readLiveStore. */
48
53
  export function readStore(path) {
49
54
  if (!existsSync(path))
50
55
  return [];
@@ -53,12 +58,99 @@ export function readStore(path) {
53
58
  return [];
54
59
  return raw.split('\n').filter(Boolean).map((l) => JSON.parse(l));
55
60
  }
56
- /**
57
- * An upgrade is the one legitimate reason to rewrite a line, so the whole file
58
- * is rewritten rather than appended to. Everything else is append-only.
59
- */
60
- function rewriteStore(path, rows) {
61
- writeFileSync(path, rows.map((r) => JSON.stringify(r)).join('\n') + (rows.length ? '\n' : ''));
61
+ export function validateAnchorLog(rows) {
62
+ let previous = GENESIS_HASH;
63
+ for (let i = 0; i < rows.length; i++) {
64
+ const row = rows[i];
65
+ if (!Number.isInteger(row.seq) || row.seq !== i + 1) {
66
+ throw new Error(`anchor log corrupt: seq at index ${i}`);
67
+ }
68
+ if (row.prevHash !== previous) {
69
+ throw new Error('anchor log corrupt: prevHash mismatch');
70
+ }
71
+ if (!row.hash) {
72
+ throw new Error('anchor log corrupt: missing entry hash');
73
+ }
74
+ const expected = computeEntryHash(row);
75
+ if (row.hash !== expected) {
76
+ throw new Error('anchor log corrupt: entry hash mismatch');
77
+ }
78
+ previous = row.hash;
79
+ }
80
+ }
81
+ export function readLiveStore(path) {
82
+ const rows = readStore(path);
83
+ validateAnchorLog(rows);
84
+ return rows;
85
+ }
86
+ export function buildInclusionProof(rows, target) {
87
+ if (!Number.isInteger(target.seq) || target.seq < 1 || target.seq > rows.length) {
88
+ throw new Error('cannot build inclusion proof: record not in log');
89
+ }
90
+ const at = rows[target.seq - 1];
91
+ if (at.hash !== target.hash || at.seq !== target.seq) {
92
+ throw new Error('cannot build inclusion proof: record moved');
93
+ }
94
+ const head = rows[rows.length - 1];
95
+ return {
96
+ seq: target.seq,
97
+ hash: target.hash,
98
+ prevHash: target.prevHash,
99
+ head: {
100
+ seq: head.seq,
101
+ hash: head.hash,
102
+ state: head.state,
103
+ ...(head.bitcoinBlock !== undefined ? { bitcoinBlock: head.bitcoinBlock } : {}),
104
+ },
105
+ path: rows.slice(target.seq - 1).map((r) => ({
106
+ seq: r.seq,
107
+ hash: r.hash,
108
+ prevHash: r.prevHash,
109
+ })),
110
+ };
111
+ }
112
+ export function verifyInclusionProof(record, proof) {
113
+ if (proof.seq !== record.seq || proof.hash !== record.hash || proof.prevHash !== record.prevHash) {
114
+ return false;
115
+ }
116
+ if (proof.path.length === 0)
117
+ return false;
118
+ if (proof.path[0].hash !== record.hash || proof.path[0].seq !== record.seq)
119
+ return false;
120
+ let prev = record.prevHash;
121
+ for (const step of proof.path) {
122
+ if (step.prevHash !== prev)
123
+ return false;
124
+ prev = step.hash;
125
+ }
126
+ const last = proof.path[proof.path.length - 1];
127
+ return last.hash === proof.head.hash && last.seq === proof.head.seq;
128
+ }
129
+ function nextLink(rows) {
130
+ if (rows.length === 0)
131
+ return { seq: 1, prevHash: GENESIS_HASH };
132
+ const last = rows[rows.length - 1];
133
+ return { seq: last.seq + 1, prevHash: last.hash };
134
+ }
135
+ function sealRecord(unsigned, key) {
136
+ const hashed = {
137
+ ...unsigned,
138
+ hash: computeEntryHash(unsigned),
139
+ };
140
+ return signAnchorRecord(hashed, key);
141
+ }
142
+ function findSubmit(rows, id) {
143
+ return rows.find((r) => r.id === id && r.type === 'submit');
144
+ }
145
+ function latestView(rows, submit) {
146
+ const upgrades = rows.filter((r) => r.type === 'upgrade' && r.upgradesSeq === submit.seq);
147
+ if (upgrades.length === 0)
148
+ return submit;
149
+ const last = upgrades[upgrades.length - 1];
150
+ return { ...last, id: submit.id, digest: submit.digest };
151
+ }
152
+ function alreadyUpgraded(rows, seq) {
153
+ return rows.some((r) => r.type === 'upgrade' && r.upgradesSeq === seq);
62
154
  }
63
155
  export function loadTokensFile(path) {
64
156
  const tokens = new Map();
@@ -84,10 +176,15 @@ function resolveOwner(tokens, presented) {
84
176
  return found;
85
177
  }
86
178
  export function createAnchorService(opts) {
179
+ if (!opts.signingKey) {
180
+ throw new Error('createAnchorService: signingKey is required — a countersign service without a key is not one');
181
+ }
87
182
  const stamp = opts.stamp ?? defaultStamp;
88
183
  const upgrade = opts.upgrade ?? defaultUpgrade;
89
184
  const perMinute = opts.submitsPerMinute ?? 60;
90
185
  const base = opts.publicBaseUrl.replace(/\/+$/, '');
186
+ const publicPem = opts.publicPem ??
187
+ createPublicKey(opts.signingKey.privateKey).export({ type: 'spki', format: 'pem' }).toString();
91
188
  mkdirSync(dirname(opts.storePath), { recursive: true });
92
189
  const buckets = new Map();
93
190
  function overLimit(owner) {
@@ -116,17 +213,95 @@ export function createAnchorService(opts) {
116
213
  }
117
214
  return owner;
118
215
  }
216
+ function live(res) {
217
+ try {
218
+ return readLiveStore(opts.storePath);
219
+ }
220
+ catch {
221
+ res.status(503).json({ error: 'anchor log corrupt' });
222
+ return null;
223
+ }
224
+ }
119
225
  app.get('/healthz', (_req, res) => {
120
- res.json({ ok: true, service: 'conarium-anchor', anchors: readStore(opts.storePath).length });
226
+ const rows = live(res);
227
+ if (!rows)
228
+ return;
229
+ res.json({
230
+ ok: true,
231
+ service: 'conarium-anchor',
232
+ anchors: rows.filter((r) => r.type === 'submit').length,
233
+ });
234
+ });
235
+ // `/anchor` is where a curious visitor types first, and it only accepted POST,
236
+ // so a browser got Express's default "Cannot GET /anchor" with <title>Error</title>.
237
+ // Every other surface in this product explains itself; the front door of the
238
+ // countersigning service should not be the one that looks broken.
239
+ app.get(['/anchor', '/anchor/'], (req, res) => {
240
+ const index = {
241
+ service: 'conarium-countersign',
242
+ keyId: opts.signingKey.keyId,
243
+ publicKey: `${base}/anchor/key.pem`,
244
+ keyIdSidecar: `${base}/anchor/key.pem.keyid`,
245
+ logHead: `${base}/anchor/log/head`,
246
+ record: `${base}/anchor/<id>`,
247
+ submit: {
248
+ method: 'POST',
249
+ path: '/anchor',
250
+ auth: 'Authorization: Bearer <token>',
251
+ body: { hash: 'sha256:<64 hex>' },
252
+ note: 'A digest and nothing else. No content is sent to this service and none is stored.',
253
+ },
254
+ verify: `npx conarium-countersign-verify record.json --pubkey key.pem --log-url ${base}/anchor/<id>`,
255
+ claim: 'A countersignature says a signer other than you saw this digest at this time and placed it at this position in a log that is appended to, never rewritten.',
256
+ limits: [
257
+ 'It does not say your records were correct when they were written.',
258
+ 'It is not a claim that the countersigner is honest — only that this log cannot be quietly rearranged afterwards.',
259
+ 'If the signing key leaks, every signature under this keyId is worthless and there is no recall.',
260
+ ],
261
+ };
262
+ res.setHeader('Vary', 'Accept');
263
+ if (req.accepts(['json', 'html']) === 'html') {
264
+ res.type('html').send(indexPage(index));
265
+ return;
266
+ }
267
+ res.json(index);
268
+ });
269
+ // Registered before /anchor/:id so these paths are never treated as an id.
270
+ app.get('/anchor/key.pem', (_req, res) => {
271
+ if (!isServablePublicPem(publicPem)) {
272
+ res.status(403).type('text/plain').send('refusing to serve a private key');
273
+ return;
274
+ }
275
+ res.type('application/x-pem-file').send(publicPem);
276
+ });
277
+ app.get('/anchor/key.pem.keyid', (_req, res) => {
278
+ res.type('text/plain').send(opts.signingKey.keyId + '\n');
279
+ });
280
+ app.get('/anchor/log/head', (_req, res) => {
281
+ const rows = live(res);
282
+ if (!rows)
283
+ return;
284
+ if (rows.length === 0) {
285
+ res.json({ seq: 0, hash: GENESIS_HASH, prevHash: GENESIS_HASH, empty: true });
286
+ return;
287
+ }
288
+ const head = rows[rows.length - 1];
289
+ res.json({
290
+ seq: head.seq,
291
+ hash: head.hash,
292
+ prevHash: head.prevHash,
293
+ type: head.type,
294
+ state: head.state,
295
+ ...(head.bitcoinBlock !== undefined ? { bitcoinBlock: head.bitcoinBlock } : {}),
296
+ });
121
297
  });
122
298
  app.post('/anchor', async (req, res) => {
123
299
  const owner = auth(req, res);
124
300
  if (!owner)
125
301
  return;
126
302
  const hash = typeof req.body?.hash === 'string' ? req.body.hash : '';
127
- let digest;
128
303
  try {
129
- digest = hashPrefixToBuffer(hash);
304
+ hashPrefixToBuffer(hash);
130
305
  }
131
306
  catch (err) {
132
307
  res.status(400).json({ error: err.message });
@@ -136,56 +311,84 @@ export function createAnchorService(opts) {
136
311
  res.status(429).json({ error: 'rate limit exceeded', retryAfterSeconds: 60 });
137
312
  return;
138
313
  }
314
+ const rows = live(res);
315
+ if (!rows)
316
+ return;
139
317
  // Same content, same owner, same answer. Re-anchoring an identical hash
140
318
  // wastes a calendar submission and produces a second id for one fact.
141
- const existing = readStore(opts.storePath).find((r) => r.hash === hash && r.owner === owner);
319
+ const existing = rows.find((r) => r.type === 'submit' && r.digest === hash && r.owner === owner);
142
320
  if (existing) {
143
- res.status(200).json({ ...publicView(existing, base), deduplicated: true });
321
+ res.status(200).json({
322
+ ...publicView(latestView(rows, existing), base, rows, existing),
323
+ countersign: existing,
324
+ deduplicated: true,
325
+ });
144
326
  return;
145
327
  }
146
- let ots;
147
- try {
148
- ots = await stamp(digest);
149
- }
150
- catch (err) {
151
- // Fail loudly. A silent 200 here would mean the customer believes their
152
- // chain is anchored when nothing was submitted.
153
- res.status(502).json({ error: `calendar submission failed: ${err.message}` });
154
- return;
155
- }
156
- const record = {
328
+ // Stamp is off the request path (C5). A slow calendar must not lock accept.
329
+ const link = nextLink(rows);
330
+ const record = sealRecord({
331
+ type: 'submit',
157
332
  id: randomBytes(9).toString('base64url'),
158
- hash,
333
+ digest: hash,
159
334
  owner,
160
335
  log: 'opentimestamps',
161
- ots,
336
+ ots: '',
162
337
  state: 'pending',
163
338
  submittedAt: new Date().toISOString(),
164
- };
339
+ seq: link.seq,
340
+ prevHash: link.prevHash,
341
+ }, opts.signingKey);
165
342
  appendFileSync(opts.storePath, JSON.stringify(record) + '\n');
166
- res.status(201).json(publicView(record, base));
343
+ res.status(201).json({ ...publicView(record, base, [...rows, record]), countersign: record });
167
344
  });
168
345
  app.get('/anchor/:id', (req, res) => {
169
- const record = readStore(opts.storePath).find((r) => r.id === req.params.id);
170
- if (!record) {
346
+ const rows = live(res);
347
+ if (!rows)
348
+ return;
349
+ const submit = findSubmit(rows, req.params.id);
350
+ if (!submit) {
171
351
  res.status(404).json({ error: 'no such anchor' });
172
352
  return;
173
353
  }
354
+ const record = latestView(rows, submit);
174
355
  // Public on purpose: a verification URL only a token holder can open is not
175
356
  // a verification URL. It carries a hash and a proof, never content.
176
357
  res.setHeader('Vary', 'Accept');
177
- if (req.accepts(['json', 'html']) === 'html') {
178
- res.type('html').send(humanPage(record, base));
179
- return;
358
+ try {
359
+ if (req.accepts(['json', 'html']) === 'html') {
360
+ res.type('html').send(humanPage(record, base, rows, submit));
361
+ return;
362
+ }
363
+ res.json(publicView(record, base, rows, submit));
364
+ }
365
+ catch (err) {
366
+ // Only an actual proof failure may be reported as one. This catch used to
367
+ // label every error "cannot build inclusion proof", so a rendering bug
368
+ // sent whoever was debugging it to the log instead of to the renderer.
369
+ const msg = err instanceof Error ? err.message : String(err);
370
+ if (msg.startsWith('cannot build inclusion proof')) {
371
+ res.status(503).json({ error: 'cannot build inclusion proof' });
372
+ return;
373
+ }
374
+ res.status(500).json({ error: 'internal error while rendering this record' });
180
375
  }
181
- res.json(publicView(record, base));
182
376
  });
183
377
  app.get('/anchor/:id/ots', (req, res) => {
184
- const record = readStore(opts.storePath).find((r) => r.id === req.params.id);
185
- if (!record) {
378
+ const rows = live(res);
379
+ if (!rows)
380
+ return;
381
+ const submit = findSubmit(rows, req.params.id);
382
+ if (!submit) {
186
383
  res.status(404).json({ error: 'no such anchor' });
187
384
  return;
188
385
  }
386
+ const stampRow = rows.find((r) => r.type === 'stamp' && (r.stampedSeq ?? 0) >= submit.seq);
387
+ if (!stampRow || !stampRow.ots) {
388
+ res.status(404).json({ error: 'not yet stamped — wait for the next head stamp' });
389
+ return;
390
+ }
391
+ const record = latestView(rows, stampRow);
189
392
  res.type('application/octet-stream').send(Buffer.from(record.ots, 'base64'));
190
393
  });
191
394
  /** Upgrade pass. Idempotent, safe to run from cron as often as you like. */
@@ -193,25 +396,82 @@ export function createAnchorService(opts) {
193
396
  const owner = auth(req, res);
194
397
  if (!owner)
195
398
  return;
196
- const result = await runUpgrade();
197
- res.json(result);
399
+ try {
400
+ const result = await runUpgrade();
401
+ res.json(result);
402
+ }
403
+ catch {
404
+ res.status(503).json({ error: 'anchor log corrupt' });
405
+ }
198
406
  });
407
+ async function runStamp() {
408
+ const rows = readLiveStore(opts.storePath);
409
+ if (rows.length === 0)
410
+ return { attempted: 0, stamped: 0 };
411
+ const head = rows[rows.length - 1];
412
+ if (head.type === 'stamp')
413
+ return { attempted: 0, stamped: 0 };
414
+ if (rows.some((r) => r.type === 'stamp' && r.stampedSeq === head.seq)) {
415
+ return { attempted: 0, stamped: 0 };
416
+ }
417
+ try {
418
+ const ots = await stamp(hashPrefixToBuffer(`sha256:${head.hash}`));
419
+ const link = nextLink(rows);
420
+ const next = sealRecord({
421
+ type: 'stamp',
422
+ id: randomBytes(9).toString('base64url'),
423
+ digest: `sha256:${head.hash}`,
424
+ owner: 'conarium',
425
+ log: 'opentimestamps',
426
+ ots,
427
+ state: 'pending',
428
+ submittedAt: new Date().toISOString(),
429
+ seq: link.seq,
430
+ prevHash: link.prevHash,
431
+ stampedSeq: head.seq,
432
+ }, opts.signingKey);
433
+ appendFileSync(opts.storePath, JSON.stringify(next) + '\n');
434
+ return { attempted: 1, stamped: 1 };
435
+ }
436
+ catch {
437
+ return { attempted: 1, stamped: 0 };
438
+ }
439
+ }
199
440
  async function runUpgrade() {
200
- const rows = readStore(opts.storePath);
441
+ const rows = readLiveStore(opts.storePath);
201
442
  let upgraded = 0;
202
443
  let checked = 0;
203
444
  for (const row of rows) {
204
- if (row.state !== 'pending')
445
+ if (row.type !== 'stamp' || row.state !== 'pending')
446
+ continue;
447
+ if (alreadyUpgraded(rows, row.seq))
448
+ continue;
449
+ if (!row.ots)
205
450
  continue;
206
451
  checked += 1;
207
452
  try {
208
453
  const out = await upgrade(row.ots);
209
454
  if (out.upgraded) {
210
- row.state = 'bitcoin';
211
- row.ots = out.ots ?? row.ots;
455
+ const link = nextLink(rows);
456
+ const unsigned = {
457
+ type: 'upgrade',
458
+ id: randomBytes(9).toString('base64url'),
459
+ digest: row.digest,
460
+ owner: row.owner,
461
+ log: row.log,
462
+ ots: out.ots ?? row.ots,
463
+ state: 'bitcoin',
464
+ submittedAt: row.submittedAt,
465
+ upgradedAt: new Date().toISOString(),
466
+ seq: link.seq,
467
+ prevHash: link.prevHash,
468
+ upgradesSeq: row.seq,
469
+ };
212
470
  if (typeof out.block === 'number')
213
- row.bitcoinBlock = out.block;
214
- row.upgradedAt = new Date().toISOString();
471
+ unsigned.bitcoinBlock = out.block;
472
+ const next = sealRecord(unsigned, opts.signingKey);
473
+ appendFileSync(opts.storePath, JSON.stringify(next) + '\n');
474
+ rows.push(next);
215
475
  upgraded += 1;
216
476
  }
217
477
  }
@@ -220,21 +480,31 @@ export function createAnchorService(opts) {
220
480
  // It stays pending and the next pass tries again.
221
481
  }
222
482
  }
223
- if (upgraded)
224
- rewriteStore(opts.storePath, rows);
225
483
  return { checked, upgraded };
226
484
  }
227
- return { app, runUpgrade, readStore: () => readStore(opts.storePath) };
485
+ return { app, runUpgrade, runStamp, readStore: () => readStore(opts.storePath) };
228
486
  }
229
- function publicView(r, base) {
487
+ function publicView(r, base, rows, target) {
488
+ const inclusion = rows ? buildInclusionProof(rows, target ?? r) : undefined;
230
489
  return {
231
490
  id: r.id,
232
- hash: r.hash,
491
+ // `digest` is what the customer submitted; `chainHash` is this record's link
492
+ // in our log. Both used to be reachable as "hash" in one document — the
493
+ // top-level field held the customer digest while inclusion.hash held the
494
+ // chain hash, so the same name carried two different values next to a
495
+ // prevHash that chains only one of them. In an evidence product that
496
+ // ambiguity is not a style question.
497
+ digest: r.digest,
498
+ chainHash: r.hash,
233
499
  log: r.log,
234
500
  state: r.state,
501
+ seq: r.seq,
502
+ prevHash: r.prevHash,
235
503
  ...(r.bitcoinBlock !== undefined ? { bitcoinBlock: r.bitcoinBlock } : {}),
236
504
  submittedAt: r.submittedAt,
237
505
  ...(r.upgradedAt ? { upgradedAt: r.upgradedAt } : {}),
506
+ sig: r.sig,
507
+ ...(inclusion ? { inclusion } : {}),
238
508
  verify: `${base}/anchor/${r.id}/ots`,
239
509
  claim: r.state === 'bitcoin'
240
510
  ? 'This hash existed no later than the Bitcoin block below. Conarium is not the time source — the OpenTimestamps calendars and Bitcoin are, and the proof above can be checked without us.'
@@ -244,16 +514,45 @@ function publicView(r, base) {
244
514
  function esc(s) {
245
515
  return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
246
516
  }
247
- function humanPage(r, base) {
248
- const v = publicView(r, base);
517
+ function indexPage(i) {
518
+ return `<!doctype html><meta charset="utf-8"><title>Conarium countersigning</title>
519
+ <body style="font:15px/1.6 system-ui,sans-serif;max-width:44rem;margin:3rem auto;padding:0 1rem">
520
+ <h1 style="font-size:1.3rem">Conarium countersigning</h1>
521
+ <p>${esc(i.claim)}</p>
522
+ <table style="border-collapse:collapse">
523
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">key id</td><td><code>${esc(i.keyId)}</code></td></tr>
524
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">public key</td><td><a href="${esc(i.publicKey)}"><code>${esc(i.publicKey)}</code></a></td></tr>
525
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">log head</td><td><a href="${esc(i.logHead)}"><code>${esc(i.logHead)}</code></a></td></tr>
526
+ </table>
527
+ <h2 style="font-size:1rem;margin-top:2rem">Submit a chain head</h2>
528
+ <pre style="background:#f5f5f5;padding:.8rem;overflow-x:auto"><code>${esc(i.submit.method)} ${esc(i.submit.path)}
529
+ ${esc(i.submit.auth)}
530
+ ${esc(JSON.stringify(i.submit.body))}</code></pre>
531
+ <p style="opacity:.75">A digest and nothing else. No content is sent to this service and none is stored.</p>
532
+ <h2 style="font-size:1rem;margin-top:2rem">Verify one you were given</h2>
533
+ <pre style="background:#f5f5f5;padding:.8rem;overflow-x:auto"><code>${esc(i.verify)}</code></pre>
534
+ <h2 style="font-size:1rem;margin-top:2rem">What this does not say</h2>
535
+ <ul>${i.limits.map((l) => `<li>${esc(l)}</li>`).join('')}</ul>
536
+ </body>`;
537
+ }
538
+ function humanPage(r, base, rows, target) {
539
+ const v = publicView(r, base, rows, target);
540
+ const proof = v.inclusion;
541
+ const incl = proof
542
+ ? `<tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">inclusion</td><td><code>seq ${proof.seq} → head ${proof.head.seq} (${esc(proof.head.state)})</code></td></tr>`
543
+ : '';
249
544
  return `<!doctype html><meta charset="utf-8"><title>Conarium anchor ${esc(r.id)}</title>
250
545
  <body style="font:15px/1.6 system-ui,sans-serif;max-width:44rem;margin:3rem auto;padding:0 1rem">
251
546
  <h1 style="font-size:1.3rem">Anchor ${esc(r.id)}</h1>
252
547
  <table style="border-collapse:collapse">
253
- <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">hash</td><td><code>${esc(r.hash)}</code></td></tr>
548
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">submitted digest</td><td><code>${esc(v.digest)}</code></td></tr>
549
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">chain hash</td><td><code>${esc(v.chainHash)}</code></td></tr>
550
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">seq</td><td><code>${r.seq}</code></td></tr>
254
551
  <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">state</td><td><code>${esc(r.state)}</code></td></tr>
255
552
  ${r.bitcoinBlock !== undefined ? `<tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">bitcoin block</td><td><code>${r.bitcoinBlock}</code></td></tr>` : ''}
256
553
  <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">submitted</td><td><code>${esc(r.submittedAt)}</code></td></tr>
554
+ <tr><td style="padding:.3rem 1rem .3rem 0;opacity:.7">countersign</td><td><code>Ed25519 ${esc(r.sig.keyId)}</code></td></tr>
555
+ ${incl}
257
556
  </table>
258
557
  <p>${esc(v.claim)}</p>
259
558
  <p>Raw proof: <a href="${esc(v.verify)}">${esc(v.verify)}</a> — verify it with the reference