@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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.17 — 2026-08-15
4
+
5
+ - **`GET /anchor` describes the service.** The path only accepted POST, so the
6
+ address a visitor types first answered with Express's default `Cannot GET
7
+ /anchor` under `<title>Error</title>`. Every other surface in this product
8
+ explains itself; the front door of the countersigning service was the one that
9
+ looked broken. It now returns, in JSON or HTML, who signs, where the public key
10
+ and log head are, how to submit, the exact verify command — and the three
11
+ sentences about what a countersignature does **not** say. The test asserts the
12
+ index carries nothing that was not already public.
13
+
14
+ ## 0.2.16 — 2026-08-15
15
+
16
+ Countersigning: a second party on your chain head, and a revocation fix that
17
+ turned up while building it.
18
+
19
+ - **The anchoring endpoint countersigns.** Every accepted submission is signed
20
+ with the service's own Ed25519 key, so the record carries a signature from
21
+ someone other than the party that produced the chain. Relaying a hash to a
22
+ public timestamp calendar was never worth paying for — the customer can do
23
+ that themselves, for free, and now the code says which of the two is the
24
+ point. The service refuses to start without a signing key, and refuses a key
25
+ file other users can read.
26
+
27
+ - **The log is an append-only hash chain.** Records carry `seq`, `prevHash` and
28
+ their own entry hash, and a pending anchor that later confirms is appended as
29
+ a new row instead of rewriting the old one. The file previously carried a
30
+ comment promising append-only next to a function that rewrote the whole thing.
31
+ A tampered log now fails the chain check instead of being served.
32
+
33
+ - **Inclusion proofs and an offline verifier.** `GET /anchor/:id` returns the
34
+ path from a record to the log head, and `conarium-countersign-verify` checks a
35
+ countersignature with zero imports from this package. "Could not check the
36
+ log" (15) stays distinct from "the proof is false" (14).
37
+
38
+ - **The timestamp covers the log head, not each submission.** N submissions cost
39
+ one calendar request instead of N, and a slow calendar can no longer delay
40
+ accepting a submission — stamping is off the request path entirely.
41
+
42
+ - **Public records name one thing per word.** The submitted value is `digest`
43
+ and the record's own link is `chainHash`. Both used to be reachable as `hash`
44
+ in a single document, next to a `prevHash` that chains only one of them.
45
+
46
+ - **Token revocation could be silently ignored.** The token store reloaded only
47
+ when the file's mtime changed, and mtime resolution is filesystem dependent —
48
+ so a revocation written inside the same tick as an earlier edit never took
49
+ effect, and the revoked token kept resolving to its user. Staleness is now
50
+ decided by the file's content. This had been showing up as an intermittently
51
+ failing test and was read as flakiness rather than as the bug it was.
52
+
3
53
  ## 0.2.15 — 2026-08-15
4
54
 
5
55
  A rendering fix that only shows up when something else has gone wrong.
package/LIMITATIONS.md CHANGED
@@ -45,6 +45,21 @@ Bus factor 1.
45
45
 
46
46
  An OpenTimestamps stamp can take hours to confirm on Bitcoin. Receipts already show `pending`.
47
47
 
48
+ ## A countersignature is not a statement about the data
49
+
50
+ The countersigning service says that a signer other than you saw this chain head
51
+ at this time and put it at this position in a log that is appended to, never
52
+ rewritten. It says nothing about whether the records were correct, and it is not
53
+ a claim that the countersigner is honest — only that the log's own history
54
+ cannot be quietly rearranged afterwards. If the signing key leaks, every
55
+ signature it ever made is worth what the key is worth: nothing.
56
+
57
+ ## Conarium does not run a countersigning service yet
58
+
59
+ The endpoint ships in this package and you can operate it. There is no public
60
+ Conarium-operated one, so the tier of the argument that depends on the signer
61
+ being someone other than you is, today, code rather than a service.
62
+
48
63
  ## The operator is inside the boundary
49
64
 
50
65
  The product defends the assistant-to-gateway path. Code that imports the
package/LIMITATIONS.tr.md CHANGED
@@ -44,6 +44,21 @@ Bus factor 1.
44
44
 
45
45
  OpenTimestamps damgasının Bitcoin'de onaylanması saatler sürebilir. Makbuzda `pending` zaten görünür.
46
46
 
47
+ ## Karşı-imza, verinin doğruluğu hakkında bir beyan değildir
48
+
49
+ Karşı-imza servisi şunu söyler: senden başka bir imzalayan bu zincir başını şu
50
+ anda gördü ve üzerine eklenen, yeniden yazılmayan bir kütükte şu sıraya koydu.
51
+ Kayıtların doğru olduğunu söylemez; karşı-imzalayanın dürüst olduğunu da
52
+ iddia etmez — yalnızca kütüğün kendi geçmişinin sonradan sessizce yeniden
53
+ dizilemeyeceğini söyler. İmza anahtarı sızarsa, o anahtarın attığı bütün
54
+ imzalar anahtar kadar değerlidir: hiç.
55
+
56
+ ## Conarium henüz bir karşı-imza servisi işletmiyor
57
+
58
+ Uç nokta bu pakette geliyor ve kendin çalıştırabilirsin. Conarium'un işlettiği
59
+ halka açık bir tanesi yok; dolayısıyla "imzalayan sen değilsin" argümanına
60
+ dayanan katman bugün bir servis değil, çalıştırabileceğin bir kod.
61
+
47
62
  ## Operatör sınırın içindedir
48
63
 
49
64
  Ürün asistan ↔ kapı yolunu korur. Kütüphaneyi import eden kod kapıyı,
package/README.md CHANGED
@@ -6,7 +6,6 @@
6
6
  <p>
7
7
  <a href="https://conarium.dev"><img src="https://img.shields.io/badge/Website-conarium.dev-5a8cff?style=for-the-badge" alt="Website" /></a>
8
8
  <a href="https://github.com/dogrucanemek-alt/conarium/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-f2d79a?style=for-the-badge" alt="License" /></a>
9
- <a href="https://github.com/dogrucanemek-alt/conarium/blob/main/LICENSE"><img src="https://img.shields.io/badge/License-MIT-f2d79a?style=for-the-badge" alt="License" /></a>
10
9
  <img src="https://img.shields.io/badge/Status-Early%20Access-ff6f80?style=for-the-badge" alt="Early Access" />
11
10
  </p>
12
11
  </div>
@@ -229,6 +228,42 @@ performed on ourselves and the tool caught:
229
228
 
230
229
  Full schema, exit codes, and known gaps: [`docs/RECEIPT-SPEC.md`](docs/RECEIPT-SPEC.md).
231
230
 
231
+ ### Countersigning (the part you cannot do for yourself)
232
+
233
+ Receipts prove what went **through** the gateway. Reconciliation proves nothing
234
+ went **around** it. Both are yours, self-hosted, and signed by your own key —
235
+ which is exactly what an auditor discounts: you kept the record, you signed it,
236
+ and you stored it. A countersignature answers that by putting a **second party**
237
+ on the same chain head.
238
+
239
+ The service is in this package, so you can run your own and sign your own heads
240
+ — useful for a second internal custodian, and pointless against the objection
241
+ above. What makes it worth anything is that the signer is not you.
242
+
243
+ ```bash
244
+ # Run the endpoint (refuses to start without a signing key or a token file)
245
+ CONARIUM_ANCHOR_TOKENS=./anchor.tokens.json \
246
+ CONARIUM_ANCHOR_SIGNING_KEY=./anchor.pem \
247
+ CONARIUM_ANCHOR_BASE_URL=https://anchor.example.com \
248
+ npx conarium-anchor-service
249
+
250
+ # Verify a countersignature you were given — offline, no network, no package
251
+ npx conarium-countersign-verify ./record.json --pubkey ./anchor.pub.pem
252
+ # exit 0 = signature valid (and inclusion valid if a proof or --log-url was given)
253
+ # exit 13 = signature invalid / unknown keyId
254
+ # exit 14 = inclusion proof present and false
255
+ # exit 15 = the log could NOT be checked — deliberately not the same as 14
256
+ ```
257
+
258
+ The log is a hash chain: entries are appended, never rewritten, and an OTS
259
+ timestamp covers the head rather than each submission. What a countersignature
260
+ proves — and, just as importantly, what it does not — is written out in
261
+ [`docs/COUNTERSIGN.md`](docs/COUNTERSIGN.md), together with what a leaked
262
+ signing key would cost.
263
+
264
+ ⚠️ Conarium does not operate a public countersigning endpoint yet. Until it
265
+ does, this is code you can run, not a service you can buy.
266
+
232
267
  ### Implementing the format yourself
233
268
 
234
269
  The receipt is meant to outlive this implementation, so it ships with
package/SECURITY.md CHANGED
@@ -39,6 +39,22 @@ OpenTimestamps calendars over HTTPS and hashes with Node `crypto`.
39
39
  Bitcoin-block checks use `blockstream.info`. Unreachable explorer → exit 15
40
40
  ("could not check"), never a silent pass.
41
41
 
42
+ ## Countersigning key
43
+
44
+ The countersigning endpoint (`conarium-anchor-service`) signs with an Ed25519
45
+ key read from `CONARIUM_ANCHOR_SIGNING_KEY`. It refuses to start without one,
46
+ and refuses a key file other users can read — an unsigned countersigning
47
+ service is not one, and a readable key is not a key. The published
48
+ `GET /anchor/key.pem` serves the public half only and inspects the file
49
+ contents before answering, so a private PEM placed at that path is refused
50
+ rather than served.
51
+
52
+ What the key protects is the whole product: a leaked signing key makes every
53
+ countersignature it ever produced worthless, including past ones. Custody,
54
+ rotation, and what a compromise costs are in
55
+ [`docs/COUNTERSIGN.md`](docs/COUNTERSIGN.md). Conarium does not operate a
56
+ public countersigning endpoint yet.
57
+
42
58
  The tester pack is [`docs/security/THREAT-MODEL.md`](docs/security/THREAT-MODEL.md)
43
59
  and [`docs/security/PENTEST-SCOPE.md`](docs/security/PENTEST-SCOPE.md).
44
60
  npm provenance (after a dispatch publish): [`docs/security/NPM-PROVENANCE.md`](docs/security/NPM-PROVENANCE.md).
@@ -8,20 +8,23 @@
8
8
  * node bin/conarium-anchor-service.mjs
9
9
  *
10
10
  * Env:
11
- * CONARIUM_ANCHOR_TOKENS required — JSON map of {"token":"owner-id"}
12
- * CONARIUM_ANCHOR_BASE_URL required — public origin used to build verify URLs
13
- * CONARIUM_ANCHOR_STORE default ./anchor-store.jsonl
14
- * CONARIUM_ANCHOR_PORT default 8797
15
- * CONARIUM_ANCHOR_HOST default 127.0.0.1 (put a TLS proxy in front)
16
- * CONARIUM_ANCHOR_RATE default 60 submissions per owner per minute
11
+ * CONARIUM_ANCHOR_TOKENS required — JSON map of {"token":"owner-id"}
12
+ * CONARIUM_ANCHOR_BASE_URL required — public origin used to build verify URLs
13
+ * CONARIUM_ANCHOR_SIGNING_KEY required — Ed25519 private PEM path
14
+ * CONARIUM_ANCHOR_KEY_ID optional — else read <pem>.keyid
15
+ * CONARIUM_ANCHOR_STORE default ./anchor-store.jsonl
16
+ * CONARIUM_ANCHOR_PORT default 8797
17
+ * CONARIUM_ANCHOR_HOST default 127.0.0.1 (put a TLS proxy in front)
18
+ * CONARIUM_ANCHOR_RATE default 60 submissions per owner per minute
17
19
  * CONARIUM_ANCHOR_UPGRADE_MINUTES default 60; 0 disables the background pass
18
20
  *
19
21
  * Exits non-zero on missing configuration rather than starting an endpoint that
20
22
  * accepts anonymous writes — an anchoring service anyone can write to is a disk
21
- * filling up, not a service.
23
+ * filling up, not a service. A countersign service without a key is not one.
22
24
  */
23
25
  import { existsSync } from 'fs'
24
26
  import { createAnchorService, loadTokensFile } from '../dist/anchor-service.js'
27
+ import { loadAnchorSigningKey } from '../dist/keys.js'
25
28
 
26
29
  function need(name) {
27
30
  const v = process.env[name]
@@ -34,6 +37,7 @@ function need(name) {
34
37
 
35
38
  const tokensPath = need('CONARIUM_ANCHOR_TOKENS')
36
39
  const baseUrl = need('CONARIUM_ANCHOR_BASE_URL')
40
+ const signingKeyPath = need('CONARIUM_ANCHOR_SIGNING_KEY')
37
41
 
38
42
  if (!existsSync(tokensPath)) {
39
43
  console.error(`token file not found: ${tokensPath}`)
@@ -46,18 +50,38 @@ if (tokens.size === 0) {
46
50
  process.exit(2)
47
51
  }
48
52
 
53
+ if (!existsSync(signingKeyPath)) {
54
+ console.error(`signing key file not found: ${signingKeyPath}`)
55
+ process.exit(2)
56
+ }
57
+
58
+ let signingKey
59
+ try {
60
+ signingKey = loadAnchorSigningKey()
61
+ } catch (err) {
62
+ console.error(err.message)
63
+ process.exit(2)
64
+ }
65
+
49
66
  const storePath = process.env.CONARIUM_ANCHOR_STORE ?? './anchor-store.jsonl'
50
67
  const port = Number(process.env.CONARIUM_ANCHOR_PORT ?? 8797)
51
68
  const host = process.env.CONARIUM_ANCHOR_HOST ?? '127.0.0.1'
52
69
  const submitsPerMinute = Number(process.env.CONARIUM_ANCHOR_RATE ?? 60)
53
70
  const upgradeMinutes = Number(process.env.CONARIUM_ANCHOR_UPGRADE_MINUTES ?? 60)
54
71
 
55
- const { app, runUpgrade } = createAnchorService({ storePath, tokens, publicBaseUrl: baseUrl, submitsPerMinute })
72
+ const { app, runUpgrade, runStamp } = createAnchorService({
73
+ storePath,
74
+ tokens,
75
+ publicBaseUrl: baseUrl,
76
+ submitsPerMinute,
77
+ signingKey,
78
+ })
56
79
 
57
80
  app.listen(port, host, () => {
58
81
  console.log(`conarium-anchor listening on http://${host}:${port}`)
59
82
  console.log(` store ${storePath}`)
60
83
  console.log(` owners ${new Set(tokens.values()).size}`)
84
+ console.log(` keyId ${signingKey.keyId}`)
61
85
  console.log(` public ${baseUrl}`)
62
86
  })
63
87
 
@@ -66,10 +90,12 @@ app.listen(port, host, () => {
66
90
  if (upgradeMinutes > 0) {
67
91
  const tick = async () => {
68
92
  try {
93
+ const s = await runStamp()
94
+ if (s.stamped) console.log(`stamped log head (${s.stamped}/${s.attempted})`)
69
95
  const r = await runUpgrade()
70
- if (r.upgraded) console.log(`upgraded ${r.upgraded}/${r.checked} pending anchor(s)`)
96
+ if (r.upgraded) console.log(`upgraded ${r.upgraded}/${r.checked} pending stamp(s)`)
71
97
  } catch (err) {
72
- console.error(`upgrade pass failed: ${err.message}`)
98
+ console.error(`maintenance pass failed: ${err.message}`)
73
99
  }
74
100
  }
75
101
  setInterval(tick, upgradeMinutes * 60_000).unref?.()
@@ -0,0 +1,280 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * conarium-countersign-verify — independent offline verifier for a VERAX
4
+ * countersign record.
5
+ *
6
+ * ZERO imports from src/. Canonicalization is duplicated here on purpose:
7
+ * a third party must be able to run this single file without the Conarium package.
8
+ *
9
+ * Usage:
10
+ * conarium-countersign-verify <record.json> --pubkey <path>
11
+ * [--inclusion <proof.json>] [--log-url <url>]
12
+ *
13
+ * Exit codes (same class as conarium-verify):
14
+ * 0 signature valid; inclusion valid if a proof or log URL was given
15
+ * 13 signature invalid / no pubkey / unknown keyId
16
+ * 14 inclusion proof present and false (record not in the claimed path)
17
+ * 15 log COULD NOT BE CHECKED (URL unreachable) — not the same as 14
18
+ * 20 schema invalid / file missing
19
+ */
20
+ import { createHash, createPublicKey, verify as cryptoVerify } from 'crypto'
21
+ import { readFileSync, existsSync } from 'fs'
22
+
23
+ function canonicalize(obj) {
24
+ return canonValue(obj)
25
+ }
26
+
27
+ function canonValue(v) {
28
+ if (v === null) return 'null'
29
+ if (v === undefined) {
30
+ throw new Error('canonicalize: undefined is not allowed (omit the field)')
31
+ }
32
+ if (typeof v === 'boolean') return v ? 'true' : 'false'
33
+ if (typeof v === 'number') {
34
+ if (!Number.isFinite(v)) throw new Error('canonicalize: non-finite number')
35
+ return JSON.stringify(v)
36
+ }
37
+ if (typeof v === 'string') return JSON.stringify(v)
38
+ if (Array.isArray(v)) {
39
+ return '[' + v.map(canonValue).join(',') + ']'
40
+ }
41
+ if (typeof v === 'object') {
42
+ const keys = Object.keys(v)
43
+ .filter((k) => v[k] !== undefined)
44
+ .sort()
45
+ const parts = []
46
+ for (const k of keys) {
47
+ parts.push(JSON.stringify(k) + ':' + canonValue(v[k]))
48
+ }
49
+ return '{' + parts.join(',') + '}'
50
+ }
51
+ throw new Error(`canonicalize: unsupported type ${typeof v}`)
52
+ }
53
+
54
+ function countersignDigest(record) {
55
+ const copy = { ...record }
56
+ delete copy.sig
57
+ const digest = createHash('sha256').update(canonicalize(copy)).digest('hex')
58
+ return `sha256:${digest}`
59
+ }
60
+
61
+ function verifyHash(publicKey, hash, signatureBase64) {
62
+ try {
63
+ return cryptoVerify(null, Buffer.from(hash, 'utf-8'), publicKey, Buffer.from(signatureBase64, 'base64'))
64
+ } catch {
65
+ return false
66
+ }
67
+ }
68
+
69
+ function verifyInclusionProof(record, proof) {
70
+ if (!proof || typeof proof !== 'object') return false
71
+ if (proof.seq !== record.seq || proof.hash !== record.hash || proof.prevHash !== record.prevHash) {
72
+ return false
73
+ }
74
+ if (!Array.isArray(proof.path) || proof.path.length === 0) return false
75
+ if (proof.path[0].hash !== record.hash || proof.path[0].seq !== record.seq) return false
76
+ let prev = record.prevHash
77
+ for (const step of proof.path) {
78
+ if (!step || step.prevHash !== prev) return false
79
+ prev = step.hash
80
+ }
81
+ const last = proof.path[proof.path.length - 1]
82
+ return last.hash === proof.head?.hash && last.seq === proof.head?.seq
83
+ }
84
+
85
+ function usage(msg) {
86
+ if (msg) console.error(msg)
87
+ console.error(
88
+ 'Usage: conarium-countersign-verify <record.json> --pubkey <path> [--inclusion <proof.json>] [--log-url <url>]',
89
+ )
90
+ }
91
+
92
+ function parseArgs(argv) {
93
+ const out = { target: null, pubkey: null, inclusion: null, logUrl: null }
94
+ const args = [...argv]
95
+ while (args.length) {
96
+ const a = args.shift()
97
+ if (a === '--pubkey') {
98
+ const p = args.shift()
99
+ if (!p) throw new Error('--pubkey requires a path')
100
+ out.pubkey = p
101
+ } else if (a === '--inclusion') {
102
+ const p = args.shift()
103
+ if (!p) throw new Error('--inclusion requires a path')
104
+ out.inclusion = p
105
+ } else if (a === '--log-url') {
106
+ const p = args.shift()
107
+ if (!p) throw new Error('--log-url requires a URL')
108
+ out.logUrl = p
109
+ } else if (a === '--help' || a === '-h') {
110
+ usage()
111
+ process.exit(0)
112
+ } else if (a.startsWith('-')) {
113
+ throw new Error(`unknown flag: ${a}`)
114
+ } else if (!out.target) {
115
+ out.target = a
116
+ } else {
117
+ throw new Error(`unexpected argument: ${a}`)
118
+ }
119
+ }
120
+ return out
121
+ }
122
+
123
+ function fail(code, msg) {
124
+ console.error(msg)
125
+ process.exit(code)
126
+ }
127
+
128
+ function loadRecord(path) {
129
+ if (!existsSync(path)) return { error: `path not found: ${path}`, code: 20 }
130
+ let raw
131
+ try {
132
+ raw = readFileSync(path, 'utf-8').trim()
133
+ } catch (err) {
134
+ return { error: `cannot read ${path}: ${err.message}`, code: 20 }
135
+ }
136
+ // Whole file first: the usage line says <record.json>, and anyone who saves an
137
+ // API response readably (`curl … | jq . > record.json`) has a pretty-printed
138
+ // object whose first line is just "{". Parsing only that line rejected valid
139
+ // JSON with "invalid JSON" — the instruction failing for the natural form of
140
+ // its own documented input. The single-line path stays for a store line
141
+ // lifted straight out of the JSONL log.
142
+ let rec
143
+ try {
144
+ rec = JSON.parse(raw)
145
+ } catch {
146
+ try {
147
+ rec = JSON.parse(raw.split('\n')[0])
148
+ } catch (err) {
149
+ return { error: `invalid JSON: ${err.message}`, code: 20 }
150
+ }
151
+ }
152
+ if (!rec || typeof rec !== 'object') return { error: 'record must be an object', code: 20 }
153
+ if (rec.type !== 'submit' && rec.type !== 'upgrade') {
154
+ return { error: 'schema: type must be submit or upgrade', code: 20 }
155
+ }
156
+ if (typeof rec.id !== 'string' || !rec.id) return { error: 'schema: missing id', code: 20 }
157
+ if (typeof rec.digest !== 'string' || !/^sha256:[0-9a-fA-F]{64}$/.test(rec.digest)) {
158
+ return { error: 'schema: digest must be sha256:<64 hex>', code: 20 }
159
+ }
160
+ if (typeof rec.hash !== 'string' || !/^[0-9a-f]{64}$/.test(rec.hash)) {
161
+ return { error: 'schema: hash must be 64 hex chars (entry hash)', code: 20 }
162
+ }
163
+ if (!Number.isInteger(rec.seq) || rec.seq < 1) return { error: 'schema: seq must be an integer >= 1', code: 20 }
164
+ if (typeof rec.prevHash !== 'string' || !rec.prevHash) {
165
+ return { error: 'schema: missing prevHash', code: 20 }
166
+ }
167
+ const sig = rec.sig
168
+ if (!sig || sig.alg !== 'Ed25519' || typeof sig.keyId !== 'string' || typeof sig.value !== 'string') {
169
+ return { error: 'schema: sig must be { alg: Ed25519, keyId, value }', code: 20 }
170
+ }
171
+ return { rec }
172
+ }
173
+
174
+ function loadPubkey(path) {
175
+ if (!path) return { error: 'no --pubkey given (refusing to skip signature checks)', code: 13 }
176
+ if (!existsSync(path)) return { error: `public key not found: ${path}`, code: 13 }
177
+ let pem
178
+ try {
179
+ pem = readFileSync(path, 'utf-8')
180
+ } catch (err) {
181
+ return { error: `cannot read public key ${path}: ${err.message}`, code: 13 }
182
+ }
183
+ let publicKey
184
+ try {
185
+ publicKey = createPublicKey(pem)
186
+ } catch (err) {
187
+ return { error: `invalid public PEM ${path}: ${err.message}`, code: 13 }
188
+ }
189
+ if (publicKey.asymmetricKeyType !== 'ed25519') {
190
+ return { error: `expected Ed25519 at ${path}, got ${publicKey.asymmetricKeyType}`, code: 13 }
191
+ }
192
+ const sidecar = `${path}.keyid`
193
+ if (!existsSync(sidecar)) return { error: `missing keyId sidecar: ${sidecar}`, code: 13 }
194
+ const keyId = readFileSync(sidecar, 'utf-8').trim()
195
+ if (!keyId) return { error: `empty keyId sidecar: ${sidecar}`, code: 13 }
196
+ return { publicKey, keyId }
197
+ }
198
+
199
+ function loadInclusion(path) {
200
+ if (!existsSync(path)) return { error: `inclusion file not found: ${path}`, code: 20 }
201
+ try {
202
+ return { proof: JSON.parse(readFileSync(path, 'utf-8')) }
203
+ } catch (err) {
204
+ return { error: `invalid inclusion JSON: ${err.message}`, code: 20 }
205
+ }
206
+ }
207
+
208
+ async function fetchInclusion(url) {
209
+ let res
210
+ try {
211
+ res = await fetch(url, {
212
+ headers: { accept: 'application/json' },
213
+ signal: AbortSignal.timeout(8000),
214
+ })
215
+ } catch (err) {
216
+ return { error: `log could not be checked: ${err.message}`, code: 15 }
217
+ }
218
+ if (!res.ok) {
219
+ return { error: `log could not be checked: HTTP ${res.status}`, code: 15 }
220
+ }
221
+ let body
222
+ try {
223
+ body = await res.json()
224
+ } catch (err) {
225
+ return { error: `log could not be checked: ${err.message}`, code: 15 }
226
+ }
227
+ if (!body || typeof body !== 'object' || !body.inclusion) {
228
+ return { error: 'inclusion proof missing from log response', code: 14 }
229
+ }
230
+ return { proof: body.inclusion }
231
+ }
232
+
233
+ async function main() {
234
+ let opts
235
+ try {
236
+ opts = parseArgs(process.argv.slice(2))
237
+ } catch (err) {
238
+ usage(err.message)
239
+ process.exit(20)
240
+ }
241
+ if (!opts.target) {
242
+ usage('missing record.json')
243
+ process.exit(20)
244
+ }
245
+
246
+ const loaded = loadRecord(opts.target)
247
+ if (loaded.error) fail(loaded.code, loaded.error)
248
+ const rec = loaded.rec
249
+
250
+ const key = loadPubkey(opts.pubkey)
251
+ if (key.error) fail(key.code, key.error)
252
+ if (rec.sig.keyId !== key.keyId) {
253
+ fail(13, `signature keyId ${rec.sig.keyId} is not in the provided pubkey set`)
254
+ }
255
+ if (!verifyHash(key.publicKey, countersignDigest(rec), rec.sig.value)) {
256
+ fail(13, 'signature invalid')
257
+ }
258
+
259
+ let proof = null
260
+ if (opts.inclusion) {
261
+ const inc = loadInclusion(opts.inclusion)
262
+ if (inc.error) fail(inc.code, inc.error)
263
+ proof = inc.proof
264
+ }
265
+ if (opts.logUrl) {
266
+ const fetched = await fetchInclusion(opts.logUrl)
267
+ if (fetched.error) fail(fetched.code, fetched.error)
268
+ proof = fetched.proof
269
+ }
270
+ if (proof) {
271
+ if (!verifyInclusionProof(rec, proof)) {
272
+ fail(14, 'inclusion proof does not place this record in the claimed log')
273
+ }
274
+ }
275
+
276
+ console.log(`ok countersign ${rec.id} seq ${rec.seq} keyId ${rec.sig.keyId}`)
277
+ process.exit(0)
278
+ }
279
+
280
+ main().catch((err) => fail(15, `could not be checked: ${err.message}`))
@@ -5,18 +5,22 @@ This directory is the operator pack for self-hosting
5
5
  this tree.** Copy the files, fill `.env`, start it yourself.
6
6
 
7
7
  Conarium is not the timestamp authority. The OpenTimestamps calendars and
8
- Bitcoin are. This process is retention, a stable URL, and the upgrade job
9
- nobody remembers to run.
8
+ Bitcoin are. This process countersigns each accepted hash, keeps an
9
+ append-only log, and stamps the log head. What that does and does not
10
+ prove: [`docs/COUNTERSIGN.md`](../../docs/COUNTERSIGN.md).
10
11
 
11
12
  ## What must be set
12
13
 
13
- See `env.example`. The process **refuses to start** if either of these is
14
+ See `env.example`. The process **refuses to start** if any of these is
14
15
  missing, and names the variable:
15
16
 
16
17
  - `CONARIUM_ANCHOR_TOKENS` — path to a JSON map `{"token":"owner-id"}`
17
18
  - `CONARIUM_ANCHOR_BASE_URL` — public origin used in verify URLs
19
+ - `CONARIUM_ANCHOR_SIGNING_KEY` — Ed25519 private PEM (sidecar `.keyid` or `CONARIUM_ANCHOR_KEY_ID`)
18
20
 
19
21
  An anchoring endpoint anyone can write to is a disk filling up, not a service.
22
+ A countersign service without a key is not one. The public half is served at
23
+ `GET /anchor/key.pem` — a private PEM is refused with 403.
20
24
 
21
25
  ## Ports and health
22
26
 
@@ -41,8 +45,9 @@ node deploy/anchor-service/dry-run.mjs
41
45
  It asserts:
42
46
 
43
47
  1. missing env → exit 2, the variable is named
44
- 2. with a throwaway tokens file, `GET /healthz` returns 200
45
- 3. the process is then killed
48
+ 2. tokens present but no signing key → exit 2, `CONARIUM_ANCHOR_SIGNING_KEY` is named
49
+ 3. with throwaway tokens + key, `GET /healthz` returns 200
50
+ 4. the process is then killed
46
51
 
47
52
  `CONARIUM_ANCHOR_UPGRADE_MINUTES=0` so the dry-run never talks to a calendar.
48
53
 
@@ -66,13 +71,16 @@ Then: `curl -fsS http://127.0.0.1:8797/healthz`
66
71
 
67
72
  1. Stop the unit / `pm2 stop conarium-anchor`
68
73
  2. The store is append-only JSONL (`CONARIUM_ANCHOR_STORE`). Keep the file.
69
- Starting an older binary against the same store is safe: records are
70
- `{id,hash,owner,log,ots,state,...}` and unknown fields are ignored on read.
74
+ Each line is a hash-chained, countersigned row (`seq` / `prevHash` / `hash`).
75
+ A pending→bitcoin upgrade appends a new `type: 'upgrade'` line; the original
76
+ submit line stays. An older binary that does not know `digest`/`seq` will
77
+ not read this store correctly — do not mix versions against one file.
71
78
  3. Do not rewrite the store to "fix" a proof. A store that can be rewritten
72
- is not an anchoring log.
79
+ is not an anchoring log. The process will refuse to serve a tampered file.
73
80
 
74
81
  ## Peer dependency
75
82
 
76
- The OpenTimestamps client is built in (`src/ots/`). A live anchoring service
77
- needs outbound HTTPS to the calendars, or `POST /anchor` returns 502.
83
+ The OpenTimestamps client is built in (`src/ots/`). Calendars are reached
84
+ from the background tick (`runStamp` / `runUpgrade`), never from `POST /anchor`.
85
+ A calendar outage does not return 5xx on submit; the next tick retries the head.
78
86
  `/healthz` does not stamp — a health probe does not depend on a calendar.
@@ -6,7 +6,8 @@
6
6
  * 2. with env present, GET /healthz returns 200 (pm2 "online" is not this)
7
7
  */
8
8
  import { spawn } from 'node:child_process'
9
- import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
9
+ import { generateKeyPairSync } from 'node:crypto'
10
+ import { mkdtempSync, writeFileSync, rmSync, chmodSync } from 'node:fs'
10
11
  import { tmpdir } from 'node:os'
11
12
  import { dirname, join } from 'node:path'
12
13
  import { fileURLToPath } from 'node:url'
@@ -66,7 +67,34 @@ console.log('ok missing env refuses start and names CONARIUM_ANCHOR_TOKENS')
66
67
  const dir = mkdtempSync(join(tmpdir(), 'conarium-anchor-dry-'))
67
68
  const tokensPath = join(dir, 'tokens.json')
68
69
  const storePath = join(dir, 'store.jsonl')
70
+ const keyPath = join(dir, 'anchor.pem')
69
71
  writeFileSync(tokensPath, JSON.stringify({ 'dry-run-token': 'dry-run-owner' }) + '\n')
72
+
73
+ const missingKey = await runOnce({
74
+ CONARIUM_ANCHOR_TOKENS: tokensPath,
75
+ CONARIUM_ANCHOR_BASE_URL: 'http://127.0.0.1:1',
76
+ CONARIUM_ANCHOR_SIGNING_KEY: '',
77
+ })
78
+ if (missingKey.status !== 2) {
79
+ console.error(`expected exit 2 on missing signing key, got ${missingKey.status}\n${missingKey.out}`)
80
+ rmSync(dir, { recursive: true, force: true })
81
+ process.exit(1)
82
+ }
83
+ if (!/CONARIUM_ANCHOR_SIGNING_KEY/.test(missingKey.out)) {
84
+ console.error(`missing-key refusal did not name CONARIUM_ANCHOR_SIGNING_KEY:\n${missingKey.out}`)
85
+ rmSync(dir, { recursive: true, force: true })
86
+ process.exit(1)
87
+ }
88
+ console.log('ok missing signing key refuses start and names CONARIUM_ANCHOR_SIGNING_KEY')
89
+
90
+ const pair = generateKeyPairSync('ed25519')
91
+ writeFileSync(keyPath, pair.privateKey.export({ type: 'pkcs8', format: 'pem' }).toString())
92
+ // The loader refuses a private key others can read, which is the behaviour we
93
+ // want and which this dry run must not ask to be excused from. Windows ignores
94
+ // the mode bits, so writing 644 here passed locally and only failed on a POSIX
95
+ // runner. chmod after the write: the mode argument is masked by umask.
96
+ chmodSync(keyPath, 0o600)
97
+ writeFileSync(keyPath + '.keyid', 'dry-run-key\n')
70
98
  const port = await freePort()
71
99
 
72
100
  const child = spawn(process.execPath, [BIN], {
@@ -74,6 +102,7 @@ const child = spawn(process.execPath, [BIN], {
74
102
  ...process.env,
75
103
  CONARIUM_ANCHOR_TOKENS: tokensPath,
76
104
  CONARIUM_ANCHOR_BASE_URL: 'http://127.0.0.1:' + port,
105
+ CONARIUM_ANCHOR_SIGNING_KEY: keyPath,
77
106
  CONARIUM_ANCHOR_STORE: storePath,
78
107
  CONARIUM_ANCHOR_HOST: '127.0.0.1',
79
108
  CONARIUM_ANCHOR_PORT: String(port),
@@ -1,8 +1,11 @@
1
1
  # Copy to .env and fill. Never commit the filled file.
2
- # The process refuses to start if TOKENS or BASE_URL is missing.
2
+ # The process refuses to start if TOKENS, BASE_URL, or SIGNING_KEY is missing.
3
3
 
4
4
  CONARIUM_ANCHOR_TOKENS=./anchor.tokens.json
5
5
  CONARIUM_ANCHOR_BASE_URL=https://anchor.example.invalid
6
+ CONARIUM_ANCHOR_SIGNING_KEY=./anchor-ed25519.pem
7
+ # Optional if <pem>.keyid exists next to the private key.
8
+ # CONARIUM_ANCHOR_KEY_ID=verax-2026-08
6
9
  CONARIUM_ANCHOR_STORE=./anchor-store.jsonl
7
10
  CONARIUM_ANCHOR_HOST=127.0.0.1
8
11
  CONARIUM_ANCHOR_PORT=8797