@oxy.so/protocol 1.0.0

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.
Files changed (122) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +16 -0
  3. package/dist/cjs/.tsbuildinfo +1 -0
  4. package/dist/cjs/chain/continuity.js +54 -0
  5. package/dist/cjs/chain/engine.js +34 -0
  6. package/dist/cjs/chain/recordStore.js +25 -0
  7. package/dist/cjs/chain/types.js +22 -0
  8. package/dist/cjs/chain/verify.js +82 -0
  9. package/dist/cjs/envelope/canonicalJson.js +107 -0
  10. package/dist/cjs/envelope/recordId.js +60 -0
  11. package/dist/cjs/envelope/sign.js +75 -0
  12. package/dist/cjs/envelope/signingInput.js +32 -0
  13. package/dist/cjs/identity/resolver.js +50 -0
  14. package/dist/cjs/index.js +71 -0
  15. package/dist/cjs/node/constants.js +85 -0
  16. package/dist/cjs/node/didWebResolver.js +126 -0
  17. package/dist/cjs/node/httpFetch.js +61 -0
  18. package/dist/cjs/node/index.js +71 -0
  19. package/dist/cjs/node/nodeApp.js +344 -0
  20. package/dist/cjs/node/nodeClient.js +204 -0
  21. package/dist/cjs/node/rateLimit.js +187 -0
  22. package/dist/cjs/node/verifyRecord.js +51 -0
  23. package/dist/cjs/platform/crypto.js +186 -0
  24. package/dist/cjs/platform/crypto.native.js +204 -0
  25. package/dist/cjs/platform/expoTypes.js +24 -0
  26. package/dist/cjs/platform/platform.js +33 -0
  27. package/dist/cjs/secp256k1.js +148 -0
  28. package/dist/cjs/transparency/checkpoint.js +79 -0
  29. package/dist/cjs/transparency/tree.js +197 -0
  30. package/dist/esm/.tsbuildinfo +1 -0
  31. package/dist/esm/chain/continuity.js +51 -0
  32. package/dist/esm/chain/engine.js +31 -0
  33. package/dist/esm/chain/recordStore.js +24 -0
  34. package/dist/esm/chain/types.js +19 -0
  35. package/dist/esm/chain/verify.js +78 -0
  36. package/dist/esm/envelope/canonicalJson.js +104 -0
  37. package/dist/esm/envelope/recordId.js +56 -0
  38. package/dist/esm/envelope/sign.js +69 -0
  39. package/dist/esm/envelope/signingInput.js +29 -0
  40. package/dist/esm/identity/resolver.js +47 -0
  41. package/dist/esm/index.js +36 -0
  42. package/dist/esm/node/constants.js +82 -0
  43. package/dist/esm/node/didWebResolver.js +122 -0
  44. package/dist/esm/node/httpFetch.js +55 -0
  45. package/dist/esm/node/index.js +28 -0
  46. package/dist/esm/node/nodeApp.js +336 -0
  47. package/dist/esm/node/nodeClient.js +198 -0
  48. package/dist/esm/node/rateLimit.js +182 -0
  49. package/dist/esm/node/verifyRecord.js +48 -0
  50. package/dist/esm/platform/crypto.js +145 -0
  51. package/dist/esm/platform/crypto.native.js +196 -0
  52. package/dist/esm/platform/expoTypes.js +23 -0
  53. package/dist/esm/platform/platform.js +29 -0
  54. package/dist/esm/secp256k1.js +137 -0
  55. package/dist/esm/transparency/checkpoint.js +73 -0
  56. package/dist/esm/transparency/tree.js +189 -0
  57. package/dist/types/.tsbuildinfo +1 -0
  58. package/dist/types/chain/continuity.d.ts +28 -0
  59. package/dist/types/chain/engine.d.ts +27 -0
  60. package/dist/types/chain/recordStore.d.ts +85 -0
  61. package/dist/types/chain/types.d.ts +79 -0
  62. package/dist/types/chain/verify.d.ts +45 -0
  63. package/dist/types/envelope/canonicalJson.d.ts +44 -0
  64. package/dist/types/envelope/recordId.d.ts +30 -0
  65. package/dist/types/envelope/sign.d.ts +47 -0
  66. package/dist/types/envelope/signingInput.d.ts +33 -0
  67. package/dist/types/identity/resolver.d.ts +67 -0
  68. package/dist/types/index.d.ts +32 -0
  69. package/dist/types/node/constants.d.ts +80 -0
  70. package/dist/types/node/didWebResolver.d.ts +47 -0
  71. package/dist/types/node/httpFetch.d.ts +60 -0
  72. package/dist/types/node/index.d.ts +28 -0
  73. package/dist/types/node/nodeApp.d.ts +120 -0
  74. package/dist/types/node/nodeClient.d.ts +135 -0
  75. package/dist/types/node/rateLimit.d.ts +95 -0
  76. package/dist/types/node/verifyRecord.d.ts +41 -0
  77. package/dist/types/platform/crypto.d.ts +93 -0
  78. package/dist/types/platform/crypto.native.d.ts +77 -0
  79. package/dist/types/platform/expoTypes.d.ts +99 -0
  80. package/dist/types/platform/platform.d.ts +25 -0
  81. package/dist/types/secp256k1.d.ts +45 -0
  82. package/dist/types/transparency/checkpoint.d.ts +71 -0
  83. package/dist/types/transparency/tree.d.ts +135 -0
  84. package/package.json +157 -0
  85. package/src/__tests__/canonicalJson.test.ts +116 -0
  86. package/src/__tests__/chain.test.ts +279 -0
  87. package/src/__tests__/didWebResolver.test.ts +132 -0
  88. package/src/__tests__/envelope.test.ts +267 -0
  89. package/src/__tests__/nodeApp.test.ts +410 -0
  90. package/src/__tests__/nodeClient.test.ts +177 -0
  91. package/src/__tests__/nodeHarness.ts +151 -0
  92. package/src/__tests__/optionalNativePeers.test.ts +233 -0
  93. package/src/__tests__/rateLimit.test.ts +268 -0
  94. package/src/__tests__/runnerGuard.test.ts +85 -0
  95. package/src/__tests__/secp256k1.test.ts +118 -0
  96. package/src/__tests__/transparency.test.ts +353 -0
  97. package/src/chain/continuity.ts +59 -0
  98. package/src/chain/engine.ts +43 -0
  99. package/src/chain/recordStore.ts +98 -0
  100. package/src/chain/types.ts +85 -0
  101. package/src/chain/verify.ts +102 -0
  102. package/src/envelope/canonicalJson.ts +120 -0
  103. package/src/envelope/recordId.ts +63 -0
  104. package/src/envelope/sign.ts +86 -0
  105. package/src/envelope/signingInput.ts +48 -0
  106. package/src/identity/resolver.ts +90 -0
  107. package/src/index.ts +101 -0
  108. package/src/node/constants.ts +105 -0
  109. package/src/node/didWebResolver.ts +162 -0
  110. package/src/node/httpFetch.ts +88 -0
  111. package/src/node/index.ts +87 -0
  112. package/src/node/nodeApp.ts +471 -0
  113. package/src/node/nodeClient.ts +322 -0
  114. package/src/node/rateLimit.ts +233 -0
  115. package/src/node/verifyRecord.ts +60 -0
  116. package/src/platform/crypto.native.ts +251 -0
  117. package/src/platform/crypto.ts +172 -0
  118. package/src/platform/expoTypes.ts +99 -0
  119. package/src/platform/platform.ts +31 -0
  120. package/src/secp256k1.ts +207 -0
  121. package/src/transparency/checkpoint.ts +109 -0
  122. package/src/transparency/tree.ts +258 -0
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Chain continuity — the pure "does this record extend the head by exactly one?"
3
+ * check, with NO storage or crypto dependency.
4
+ *
5
+ * This is the single definition of continuity that used to be duplicated in
6
+ * oxy-api (`verifyChainContinuity`) and the node store (`appendTxn`). The engine
7
+ * calls it with the head it read from the injected store; a store MAY call it
8
+ * again inside its atomic append, but the unique-index backstop (surfaced as
9
+ * `chain_conflict`) is the real race guard.
10
+ *
11
+ * v1 envelopes have no chain coordinates, so they always pass (the caller does
12
+ * not advance a chain for them).
13
+ */
14
+ /**
15
+ * True when `head` represents an actual existing chain (as opposed to `null` or
16
+ * the "no chain yet" sentinel head a store may return).
17
+ */
18
+ function hasChain(head) {
19
+ return head !== null && head.headRecordId !== null && head.seq >= 0;
20
+ }
21
+ /**
22
+ * Check that `env` validly extends `head`:
23
+ *
24
+ * - **v1** (no chain coordinates): always `{ ok: true }` — v1 records are not
25
+ * chained.
26
+ * - **no head** (genesis position): only a genesis (`seq === 0`, `prev` null)
27
+ * is accepted; anything else is `chain_gap` (it claims to extend a chain that
28
+ * does not exist).
29
+ * - **head exists**: `env.prev` MUST equal `head.headRecordId` (else
30
+ * `chain_fork`, which also covers a re-genesis whose `prev` is `null`), and
31
+ * `env.seq` MUST equal `head.seq + 1` (else `bad_seq`).
32
+ */
33
+ export function checkContinuity(head, env) {
34
+ if (env.version !== 2) {
35
+ return { ok: true };
36
+ }
37
+ const isGenesis = env.seq === 0 && (env.prev === null || env.prev === undefined);
38
+ if (!hasChain(head)) {
39
+ if (!isGenesis) {
40
+ return { ok: false, reason: 'chain_gap' };
41
+ }
42
+ return { ok: true };
43
+ }
44
+ if (env.prev !== head.headRecordId) {
45
+ return { ok: false, reason: 'chain_fork' };
46
+ }
47
+ if (env.seq !== head.seq + 1) {
48
+ return { ok: false, reason: 'bad_seq' };
49
+ }
50
+ return { ok: true };
51
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Chain engine — verify-then-append orchestration.
3
+ *
4
+ * The one entry point an app's adapter calls to publish a record: it runs the
5
+ * full {@link verifyEnvelope} state machine, computes the content address
6
+ * (`recordId`), and hands the verified envelope to the injected
7
+ * {@link RecordStore} to persist atomically. The store owns the durable
8
+ * concurrency backstop (`chain_conflict` on a unique-index collision); the
9
+ * engine owns the verification + ordering policy.
10
+ *
11
+ * Storage and identity are both injected, so the engine has zero knowledge of
12
+ * Mongo/SQLite, Oxy DIDs, or any app's lexicon — exactly what makes it reusable.
13
+ */
14
+ import { computeRecordId } from '../envelope/recordId.js';
15
+ import { verifyEnvelope } from './verify.js';
16
+ /**
17
+ * Verify `env` and, if it passes, append it to the subject's chain.
18
+ *
19
+ * On a verification failure the rejection is returned WITHOUT touching the store.
20
+ * On success the (engine-computed) `recordId` is passed to `store.append`, whose
21
+ * own outcome — including the `chain_conflict` backstop on a concurrent-writer
22
+ * collision — is returned verbatim.
23
+ */
24
+ export async function verifyAndAppend(store, resolver, env, opts = {}) {
25
+ const verification = await verifyEnvelope(store, resolver, env, opts);
26
+ if (!verification.ok) {
27
+ return verification;
28
+ }
29
+ const recordId = await computeRecordId(env);
30
+ return store.append(env.subject, env, recordId);
31
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Storage interfaces — the injected persistence the chain engine drives.
3
+ *
4
+ * The engine ({@link ./verify}, {@link ./engine}) is storage-agnostic: it owns
5
+ * the verification state machine and continuity logic, and delegates EVERY read
6
+ * and write to an injected {@link RecordStore}. An app supplies a store over its
7
+ * own backend (oxy-api over Mongo `SignedRecord`/`RepoHead`, a node over SQLite,
8
+ * Mention over its own Mongo) without the engine knowing anything Oxy- or
9
+ * app-specific.
10
+ *
11
+ * All methods are **subject-keyed**: `subject` is the chain's subject DID
12
+ * (`env.subject`). A store maps that DID to its own primary key (e.g. an Oxy
13
+ * userId) internally; the engine never sees that mapping.
14
+ *
15
+ * ## Concurrency contract
16
+ *
17
+ * `append` MUST be atomic (record insert + head advance in one unit) and MUST
18
+ * translate a duplicate-key collision on the unique `(subject, seq)` /
19
+ * `recordId` index — i.e. a concurrent writer that already took this `seq` — into
20
+ * `{ ok: false, reason: 'chain_conflict' }` (Mongo E11000 / SQLite
21
+ * `SQLITE_CONSTRAINT`). That is the real multi-writer race guard; the engine's
22
+ * pre-append continuity check is only the fast-path rejection.
23
+ */
24
+ export {};
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Chain engine types — the per-subject hash-chain vocabulary.
3
+ *
4
+ * A "chain" is a single signer's append-only log of signed-record envelopes
5
+ * ("personal blockchain": one signer, no consensus/mining), ordered by a
6
+ * strictly-increasing `seq` with each record's `prev` pointing at the content
7
+ * address (`recordId`) of the one before it. These types are storage-agnostic:
8
+ * the engine ({@link ./verify}, {@link ./engine}) drives them over an injected
9
+ * {@link ./recordStore.RecordStore}, and any app (Oxy identity/civic/node,
10
+ * Mention posts, …) supplies its own store + resolver.
11
+ *
12
+ * The {@link RejectionReason} union is the SINGLE source of truth for every way
13
+ * an append can fail — it consolidates what used to be three divergent copies
14
+ * (oxy-api's `EnvelopeRejectionReason`, the node store's `AppendOutcome.reason`,
15
+ * and the node verifier's `VerifyRejectionReason`). The exact strings match the
16
+ * ones oxy-api returns today, so API responses are byte-for-byte unchanged.
17
+ */
18
+ /** The `seq` reported for a v1 (unchained) append — it has no sequence. */
19
+ export const UNCHAINED_SEQ = -1;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Envelope verification — the ordered state machine that decides whether a
3
+ * signed-record envelope may be appended to its subject's chain.
4
+ *
5
+ * This is the engine that used to live, Oxy-specific, in
6
+ * `api/services/signedRecord.service.verifyEnvelope`. Every Oxy detail has been
7
+ * lifted out into the two injected collaborators:
8
+ * - the {@link VerificationMethodResolver} owns "is this key authorized for this
9
+ * issuer?" (self vs. custodial vs. untrusted),
10
+ * - the {@link RecordStore} owns the monotonicity frontier + the chain head.
11
+ *
12
+ * The ordered checks (first failure wins):
13
+ * 1. **shape** — the base `signedRecordEnvelopeSchema` (open `type`, opaque
14
+ * `record`). An app re-narrows `type` to its own set in its adapter.
15
+ * 2. **signature** — `verifyEnvelopeSignature` recomputes the canonical signing
16
+ * input and checks the secp256k1 signature against the embedded `publicKey`.
17
+ * 3. **issuer authorization** — `resolver.resolve(subject)` + {@link isAuthorizedKey}.
18
+ * 4. **freshness** — `issuedAt` not beyond the tolerated clock skew.
19
+ * 5. **monotonicity** — `issuedAt` strictly newer than the store's latest record
20
+ * for the same logical key (replay/rollback defence).
21
+ * 6. **continuity** — `checkContinuity` against the store's chain head (v1 skips).
22
+ *
23
+ * The `subject_mismatch` binding ("is the caller allowed to write for THIS
24
+ * subject?") is intentionally NOT here — it is an adapter-policy decision the
25
+ * caller makes before invoking the engine, not a property of the envelope.
26
+ */
27
+ import { signedRecordEnvelopeSchema } from '@oxy.so/contracts';
28
+ import { verifyEnvelopeSignature } from '../envelope/sign.js';
29
+ import { isAuthorizedKey } from '../identity/resolver.js';
30
+ import { checkContinuity } from './continuity.js';
31
+ /** Default tolerated forward clock skew for a record's `issuedAt` (5 minutes). */
32
+ export const DEFAULT_CLOCK_SKEW_MS = 5 * 60 * 1000;
33
+ /**
34
+ * Run the full verification state machine for `env` against the injected
35
+ * `store` (monotonicity + continuity) and `resolver` (issuer authorization).
36
+ * Returns a verdict; it never throws on a bad envelope.
37
+ */
38
+ export async function verifyEnvelope(store, resolver, env, opts = {}) {
39
+ // 1. Base envelope shape (open `type`, `record` opaque). An app's adapter
40
+ // re-narrows `type` to its own accepted set before/around this call.
41
+ if (!signedRecordEnvelopeSchema.safeParse(env).success) {
42
+ return { ok: false, reason: 'invalid_envelope' };
43
+ }
44
+ // 2. Signature is internally consistent with the embedded `publicKey`. Cheap,
45
+ // pure crypto — rejected before any store/resolver I/O.
46
+ if (!(await verifyEnvelopeSignature(env))) {
47
+ return { ok: false, reason: 'bad_signature' };
48
+ }
49
+ // Enforce that v2 envelopes strictly contain required chain fields.
50
+ if (env.version === 2 && (typeof env.seq !== 'number' || typeof env.collection !== 'string' || typeof env.rkey !== 'string')) {
51
+ return { ok: false, reason: 'invalid_envelope' };
52
+ }
53
+ // 3. The signing key is an authorized writer for the issuer (self-issued ⇒ a
54
+ // current VM of the subject; custodial ⇒ the custodial key; else untrusted).
55
+ const resolved = await resolver.resolve(env.subject);
56
+ const authorization = isAuthorizedKey(resolved, env);
57
+ if (!authorization.ok) {
58
+ return authorization;
59
+ }
60
+ // 4. Freshness: not issued beyond the tolerated forward clock skew.
61
+ const now = opts.now ?? Date.now();
62
+ const clockSkewMs = opts.clockSkewMs ?? DEFAULT_CLOCK_SKEW_MS;
63
+ if (env.issuedAt > now + clockSkewMs) {
64
+ return { ok: false, reason: 'issued_in_future' };
65
+ }
66
+ // 5. Monotonicity: strictly newer than the latest record for the same key.
67
+ const latestIssuedAt = await store.latestIssuedAtForKey(env.subject, env);
68
+ if (latestIssuedAt !== null && env.issuedAt <= latestIssuedAt) {
69
+ return { ok: false, reason: 'stale_issued_at' };
70
+ }
71
+ // 6. Continuity: the record extends the chain head by exactly one. Only v2 is
72
+ // chained, so v1 never reads the head (it has no chain to extend).
73
+ if (env.version !== 2) {
74
+ return { ok: true };
75
+ }
76
+ const head = await store.getHead(env.subject);
77
+ return checkContinuity(head, env);
78
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Canonical JSON (RFC 8785 / JCS-style) serialization.
3
+ *
4
+ * `canonicalize(value)` produces a deterministic string for any JSON-compatible
5
+ * value so that a client which SIGNS a record and a server which VERIFIES it
6
+ * agree byte-for-byte on the signing input — regardless of the order in which
7
+ * object keys happen to be written, how the value was deserialized, or which
8
+ * runtime built it.
9
+ *
10
+ * This is the load-bearing primitive for the protocol's signed records
11
+ * (`signEnvelope` + `verifyEnvelopeSignature`): every implementation imports
12
+ * THIS function from `@oxy.so/protocol`, so cross-implementation number/string
13
+ * formatting differences cannot cause a verify mismatch.
14
+ *
15
+ * Rules (the JSON Canonicalization Scheme subset we need):
16
+ * - Objects: keys are sorted (ascending, by UTF-16 code unit — the default
17
+ * `Array.prototype.sort` order) and serialized recursively. Properties whose
18
+ * value is `undefined`, a function, or a symbol are OMITTED (matching
19
+ * `JSON.stringify` object semantics).
20
+ * - Arrays: element order is PRESERVED; `undefined`/function/symbol elements
21
+ * serialize to `null` (matching `JSON.stringify` array semantics).
22
+ * - `null`, booleans, strings, and finite numbers serialize via the standard
23
+ * JSON representation.
24
+ * - Values exposing a `toJSON()` method (e.g. `Date`) are replaced by its
25
+ * result first, then serialized — so a `Date` and its ISO-string equivalent
26
+ * canonicalize identically (the wire always carries the string form).
27
+ * - Non-finite numbers (`NaN`, `Infinity`) and `bigint` are not part of the
28
+ * JSON data model and throw, rather than silently producing `null`.
29
+ *
30
+ * Platform-agnostic — zero dependencies, no `require()`, no react/react-native/
31
+ * expo. Safe in the dual CJS + ESM build.
32
+ */
33
+ function hasToJSON(value) {
34
+ return typeof value.toJSON === 'function';
35
+ }
36
+ /**
37
+ * Serialize a single value into its canonical JSON fragment. Recursive; called
38
+ * on each nested member. Object keys are sorted at every level.
39
+ */
40
+ function serialize(value) {
41
+ if (value === null) {
42
+ return 'null';
43
+ }
44
+ const valueType = typeof value;
45
+ if (valueType === 'number') {
46
+ if (!Number.isFinite(value)) {
47
+ throw new Error('canonicalize: non-finite numbers cannot be serialized');
48
+ }
49
+ return JSON.stringify(value);
50
+ }
51
+ if (valueType === 'string' || valueType === 'boolean') {
52
+ return JSON.stringify(value);
53
+ }
54
+ if (valueType === 'bigint') {
55
+ throw new Error('canonicalize: bigint values cannot be serialized');
56
+ }
57
+ if (Array.isArray(value)) {
58
+ const items = value.map((item) => {
59
+ const itemType = typeof item;
60
+ // JSON array semantics: undefined / function / symbol become null so the
61
+ // element positions (and therefore the array length) are preserved.
62
+ if (item === undefined || itemType === 'function' || itemType === 'symbol') {
63
+ return 'null';
64
+ }
65
+ return serialize(item);
66
+ });
67
+ return `[${items.join(',')}]`;
68
+ }
69
+ if (valueType === 'object') {
70
+ const obj = value;
71
+ if (hasToJSON(obj)) {
72
+ return serialize(obj.toJSON());
73
+ }
74
+ const record = obj;
75
+ const parts = [];
76
+ for (const key of Object.keys(record).sort()) {
77
+ const member = record[key];
78
+ const memberType = typeof member;
79
+ // JSON object semantics: properties with undefined / function / symbol
80
+ // values are omitted entirely.
81
+ if (member === undefined || memberType === 'function' || memberType === 'symbol') {
82
+ continue;
83
+ }
84
+ parts.push(`${JSON.stringify(key)}:${serialize(member)}`);
85
+ }
86
+ return `{${parts.join(',')}}`;
87
+ }
88
+ // undefined / function / symbol at the top level have no JSON representation.
89
+ throw new Error(`canonicalize: cannot serialize a value of type ${valueType}`);
90
+ }
91
+ /**
92
+ * Produce the canonical JSON string for `value`.
93
+ *
94
+ * Deterministic: two structurally-equal values yield identical strings even if
95
+ * their object keys were written in different orders. Use this — never an
96
+ * ad-hoc `JSON.stringify` of a hand-sorted object — as the signing input for
97
+ * signed records, so client signing and server verification cannot drift.
98
+ *
99
+ * @throws if `value` (or any nested member used as the top-level/primitive)
100
+ * contains a non-finite number or a `bigint`, which have no JSON form.
101
+ */
102
+ export function canonicalize(value) {
103
+ return serialize(value);
104
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Content hashing — SHA-256 + `recordId` (content address).
3
+ *
4
+ * `sha256` is the protocol's single platform-aware SHA-256: it uses
5
+ * `expo-crypto` on React Native, Node's built-in `crypto` on the server, and
6
+ * the Web Crypto API in the browser — always producing the same lowercase-hex
7
+ * digest. `computeRecordId` is `sha256(signedRecordSigningInput(fields))`: the
8
+ * content address that a record's chain `prev` pointer references.
9
+ */
10
+ import { isReactNative, isNodeJS } from '../platform/platform.js';
11
+ import { loadExpoCrypto, loadNodeCrypto } from '../platform/crypto.js';
12
+ import { signedRecordSigningInput } from './signingInput.js';
13
+ /**
14
+ * Compute the SHA-256 hash of a string, returned as lowercase hex.
15
+ *
16
+ * Platform-aware: `expo-crypto` (RN) → Node `crypto` (server) → Web Crypto
17
+ * (browser). The three paths produce byte-identical digests, so a record
18
+ * hashed on a device and re-hashed on the server agree.
19
+ */
20
+ export async function sha256(message) {
21
+ // In React Native, use expo-crypto
22
+ if (isReactNative()) {
23
+ const Crypto = await loadExpoCrypto();
24
+ return Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, message);
25
+ }
26
+ if (isNodeJS()) {
27
+ try {
28
+ const nodeCrypto = await loadNodeCrypto();
29
+ return nodeCrypto.createHash('sha256').update(message).digest('hex');
30
+ }
31
+ catch {
32
+ // Node crypto failed to load — fall through to the Web Crypto API below,
33
+ // which is a correct, equivalent SHA-256 on any runtime that exposes it.
34
+ }
35
+ }
36
+ // Browser: use Web Crypto API
37
+ const encoder = new TextEncoder();
38
+ const data = encoder.encode(message);
39
+ const hashBuffer = await globalThis.crypto.subtle.digest('SHA-256', data);
40
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
41
+ return hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
42
+ }
43
+ /**
44
+ * Compute the `recordId` (content address) of a signed record: the SHA-256 hex
45
+ * digest of its canonical {@link signedRecordSigningInput}.
46
+ *
47
+ * Deterministic and stable across runtimes (it reuses the same canonicalization
48
+ * + SHA-256 the signature itself is built on). The recordId is what `prev`
49
+ * references in the per-subject hash chain, so every implementation MUST
50
+ * compute it identically — all call this function. It is taken over the SIGNING
51
+ * input (excluding `publicKey`/`signature`), so it is a pure content address of
52
+ * the record's meaning, independent of who signed.
53
+ */
54
+ export async function computeRecordId(fields) {
55
+ return sha256(signedRecordSigningInput(fields));
56
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Signing & verification — explicit-key crypto for signed-record envelopes.
3
+ *
4
+ * Stateless: every function takes the key material explicitly (no KeyManager,
5
+ * no secure storage). `@oxy.so/core` binds these to a device key; nodes and the
6
+ * API verify with them. The scheme is `ES256K-DER-SHA256` everywhere:
7
+ * secp256k1 over the SHA-256 of the canonical bytes, DER-encoded.
8
+ */
9
+ import { signedRecordSigningInput } from './signingInput.js';
10
+ import { sha256 } from './recordId.js';
11
+ import { deriveSecp256k1PublicKey, signSecp256k1Digest, verifySecp256k1Digest, } from '../secp256k1.js';
12
+ /** The one signature algorithm identifier the protocol emits. */
13
+ const ALG = 'ES256K-DER-SHA256';
14
+ /**
15
+ * Sign an arbitrary message with an explicit private key.
16
+ *
17
+ * Hashes the message with SHA-256, then signs the digest with secp256k1,
18
+ * returning the DER-encoded hex signature. The low-level primitive behind both
19
+ * {@link signEnvelope} and `@oxy.so/core`'s device-key signing helpers.
20
+ */
21
+ export async function signMessage(message, privateKeyHex) {
22
+ const digest = await sha256(message);
23
+ return signSecp256k1Digest(privateKeyHex, digest);
24
+ }
25
+ /**
26
+ * Verify a DER-encoded signature over a message against a public key.
27
+ *
28
+ * Returns `false` on any error (invalid signature, malformed key/signature,
29
+ * etc.) rather than throwing, so callers can treat verification as a boolean.
30
+ */
31
+ export async function verifySignature(message, signature, publicKeyHex) {
32
+ try {
33
+ const digest = await sha256(message);
34
+ return verifySecp256k1Digest(publicKeyHex, digest, signature);
35
+ }
36
+ catch {
37
+ // Malformed key / signature / input is not a valid signature.
38
+ return false;
39
+ }
40
+ }
41
+ /**
42
+ * Build a fully-signed {@link SignedRecordEnvelope} from its signing fields and
43
+ * an explicit private key.
44
+ *
45
+ * Computes the canonical {@link signedRecordSigningInput}, signs it
46
+ * (`ES256K-DER-SHA256`), and attaches the DERIVED `publicKey` (uncompressed
47
+ * hex — identical to `KeyManager`'s stored key for the same private key) plus
48
+ * the `alg`/`signature`. The signature covers every field EXCEPT
49
+ * `publicKey`/`signature`.
50
+ */
51
+ export async function signEnvelope(fields, privateKeyHex) {
52
+ const signingInput = signedRecordSigningInput(fields);
53
+ const signature = await signMessage(signingInput, privateKeyHex);
54
+ const publicKey = deriveSecp256k1PublicKey(privateKeyHex);
55
+ return { ...fields, publicKey, alg: ALG, signature };
56
+ }
57
+ /**
58
+ * Verify a signed-record envelope: recompute the canonical signing input from
59
+ * the envelope's own fields and check the signature against the envelope's
60
+ * `publicKey`.
61
+ *
62
+ * This confirms the signature is internally consistent with the embedded
63
+ * `publicKey`. It does NOT establish that `publicKey` is an authorized
64
+ * verification method for `subject` — that authorization check belongs to the
65
+ * server / node owner check.
66
+ */
67
+ export async function verifyEnvelopeSignature(envelope) {
68
+ return verifySignature(signedRecordSigningInput(envelope), envelope.signature, envelope.publicKey);
69
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Signed-record signing input — "what the signature covers".
3
+ *
4
+ * The single definition shared by every implementation (client signing and
5
+ * server verification), so a record signed by one and verified by another
6
+ * cannot drift.
7
+ */
8
+ import { canonicalize } from './canonicalJson.js';
9
+ /**
10
+ * Compute the canonical signing input for a signed-record envelope.
11
+ *
12
+ * - **v1**: the canonical JSON of `{version, type, subject, issuer, record,
13
+ * issuedAt}` — BYTE-IDENTICAL to the original scheme, so every signature
14
+ * already in production keeps verifying.
15
+ * - **v2**: the canonical JSON additionally includes the hash-chain fields
16
+ * `{seq, prev, collection, rkey}`. Because {@link canonicalize} sorts keys,
17
+ * the on-the-wire field order is irrelevant; the resulting canonical key
18
+ * order is `collection, issuedAt, issuer, prev, record, rkey, seq, subject,
19
+ * type, version`. `prev` is `null` at genesis (serialized as `null`, not
20
+ * omitted), so it is always part of the signed bytes.
21
+ */
22
+ export function signedRecordSigningInput(fields) {
23
+ const { version, type, subject, issuer, record, issuedAt } = fields;
24
+ if (version === 2) {
25
+ const { seq, prev, collection, rkey } = fields;
26
+ return canonicalize({ version, type, subject, issuer, record, issuedAt, seq, prev, collection, rkey });
27
+ }
28
+ return canonicalize({ version, type, subject, issuer, record, issuedAt });
29
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Verification-method resolution — the injected authorization policy the chain
3
+ * engine consults to decide whether an envelope's signing key is allowed to
4
+ * write to the subject's chain.
5
+ *
6
+ * The engine is identity-agnostic: it does NOT know about Oxy DIDs, the `User`
7
+ * model, custodial keys, or any app's notion of "current key". It asks an
8
+ * injected {@link VerificationMethodResolver} to resolve a subject DID to its
9
+ * current verification methods (plus the optional custodial issuer that may sign
10
+ * provenance records ABOUT the subject), then applies the uniform authorization
11
+ * rule in {@link isAuthorizedKey}.
12
+ *
13
+ * This is what lets the SAME engine serve Oxy identity/civic records (where the
14
+ * resolver reads `User.publicKey`/`authMethods` and the Oxy custodial key), a
15
+ * self-hosted node (where the authority is a configured owner key), and Mention
16
+ * posts (subject VMs from the Oxy DID + a Mention custodial server key) — each
17
+ * supplies its own resolver; the decision logic lives here, once.
18
+ */
19
+ /**
20
+ * Decide whether `env`'s signing key (`env.publicKey`) is authorized for its
21
+ * `issuer`, given the subject's resolved verification methods:
22
+ *
23
+ * - **Self-issued** (`issuer === subject`): the key MUST be one of the subject's
24
+ * `currentPublicKeys`; otherwise `public_key_not_a_current_verification_method`.
25
+ * - **Custodial** (`issuer === custodialIssuer`): the key MUST equal
26
+ * `custodialPublicKey`; otherwise `public_key_not_a_current_verification_method`.
27
+ * - **Any other issuer** (including an unresolvable subject): `untrusted_issuer`.
28
+ *
29
+ * The signature itself is checked separately (against `env.publicKey`), so this
30
+ * only decides whether that key is an authorized writer — it is not a trust
31
+ * shortcut.
32
+ */
33
+ export function isAuthorizedKey(resolved, env) {
34
+ if (resolved !== null && env.issuer === env.subject) {
35
+ return resolved.currentPublicKeys.includes(env.publicKey)
36
+ ? { ok: true }
37
+ : { ok: false, reason: 'public_key_not_a_current_verification_method' };
38
+ }
39
+ if (resolved !== null &&
40
+ resolved.custodialIssuer !== undefined &&
41
+ env.issuer === resolved.custodialIssuer) {
42
+ return resolved.custodialPublicKey !== undefined && env.publicKey === resolved.custodialPublicKey
43
+ ? { ok: true }
44
+ : { ok: false, reason: 'public_key_not_a_current_verification_method' };
45
+ }
46
+ return { ok: false, reason: 'untrusted_issuer' };
47
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @oxy.so/protocol — the app-agnostic Oxy Protocol base.
3
+ *
4
+ * The reusable substrate any Oxy app can use to decentralize its own content:
5
+ * the signed-record envelope grammar (canonical JSON, signing input, content
6
+ * address), explicit-key signing/verification, and the platform-aware crypto
7
+ * loaders. App-specific lexicons and the chain engine layer on top of this.
8
+ *
9
+ * Platform-agnostic root entry. Node-only pieces live under the `./node`
10
+ * subpath so they never enter React Native / web bundles.
11
+ */
12
+ // ---------------------------------------------------------------------------
13
+ // Envelope — canonical JSON, signing input, content address, signing/verify
14
+ // ---------------------------------------------------------------------------
15
+ export { canonicalize } from './envelope/canonicalJson.js';
16
+ export { signedRecordSigningInput } from './envelope/signingInput.js';
17
+ export { sha256, computeRecordId } from './envelope/recordId.js';
18
+ export { signMessage, verifySignature, signEnvelope, verifyEnvelopeSignature, } from './envelope/sign.js';
19
+ export { UNCHAINED_SEQ } from './chain/types.js';
20
+ export { checkContinuity } from './chain/continuity.js';
21
+ export { verifyEnvelope, DEFAULT_CLOCK_SKEW_MS } from './chain/verify.js';
22
+ export { verifyAndAppend } from './chain/engine.js';
23
+ // ---------------------------------------------------------------------------
24
+ // Transparency — Merkle commitment over chain heads + co-signable checkpoints
25
+ // ---------------------------------------------------------------------------
26
+ export { EMPTY_TRANSPARENCY_ROOT, transparencyLeafHash, buildTransparencyTree, buildTransparencyTreeFromHeads, inclusionProof, verifyInclusionProof, } from './transparency/tree.js';
27
+ export { checkpointSigningInput, checkpointHash, signCheckpoint, verifyCheckpointSignature, } from './transparency/checkpoint.js';
28
+ // ---------------------------------------------------------------------------
29
+ // Identity — injected verification-method resolution + authorization rule
30
+ // ---------------------------------------------------------------------------
31
+ export { isAuthorizedKey } from './identity/resolver.js';
32
+ // ---------------------------------------------------------------------------
33
+ // Platform — runtime predicates + lazy crypto/storage loaders
34
+ // ---------------------------------------------------------------------------
35
+ export { isReactNative, isNodeJS } from './platform/platform.js';
36
+ export { loadNodeCrypto, loadExpoCrypto, loadSecureStore, loadAsyncStorage, getRandomBytesRN, loadSharedIdentityBridge, } from './platform/crypto.js';
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Node-protocol shape constants — the wire-level contract of an Oxy-protocol
3
+ * data node, shared by the generic node app factory ({@link ./nodeApp}), the
4
+ * HTTP {@link ./nodeClient.NodeClient}, and any app's node deployment
5
+ * (`@oxy.so/node`, a future `mention-node`).
6
+ *
7
+ * These were previously hardcoded inside `@oxy.so/node`; they live here so the
8
+ * SAME values drive a server and a client without either side re-declaring (and
9
+ * drifting) the contract. Deployment-specific knobs (owner key, port, data dir)
10
+ * are still resolved per-deployment from the environment — only the protocol's
11
+ * own shape constants live here.
12
+ */
13
+ /**
14
+ * The node-protocol version advertised at the well-known manifest. Bumped only
15
+ * on a breaking change to the wire shape of the log / head / record APIs. This
16
+ * is the DEFAULT `protocolId` a deployment advertises (overridable per app).
17
+ */
18
+ export const PROTOCOL_VERSION = 'oxy-node/1';
19
+ /** Default well-known manifest path (the existing `@oxy.so/node` value). */
20
+ export const DEFAULT_WELL_KNOWN_PATH = '/.well-known/oxy-node.json';
21
+ /** Default DID-document service-type label advertised by a node deployment. */
22
+ export const DEFAULT_SERVICE_TYPE = 'OxyPersonalDataNode';
23
+ /**
24
+ * Default application namespace a node deployment serves. The records a node
25
+ * stores all live under this namespace (e.g. `app.oxy.*`); a `collections`
26
+ * allowlist (when set) MUST be within it.
27
+ */
28
+ export const DEFAULT_APP_NAMESPACE = 'app.oxy';
29
+ /** Default HTTP port when the port env var is unset (always overridable). */
30
+ export const DEFAULT_PORT = 4000;
31
+ /** Default and maximum number of log entries returned by `GET /oxy/log`. */
32
+ export const DEFAULT_LOG_LIMIT = 100;
33
+ export const MAX_LOG_LIMIT = 500;
34
+ /** Default upper bound on a single pinned blob's size when unset (25 MiB). */
35
+ export const DEFAULT_MAX_BLOB_BYTES = 25 * 1024 * 1024;
36
+ /** Maximum number of envelopes accepted in one `POST /sync/push` batch. */
37
+ export const MAX_SYNC_BATCH = 200;
38
+ /** Body-size ceiling for JSON request bodies (`/records`, `/sync/push`). */
39
+ export const JSON_BODY_LIMIT = '5mb';
40
+ /** HTTP headers carrying an owner-signed action authorization (blob pins). */
41
+ export const OWNER_AUTH_HEADERS = {
42
+ publicKey: 'x-oxy-node-public-key',
43
+ signature: 'x-oxy-node-signature',
44
+ timestamp: 'x-oxy-node-timestamp',
45
+ };
46
+ /**
47
+ * Freshness window for an owner-signed action (e.g. a blob pin). A signed
48
+ * authorization header older/newer than this (accounting for clock skew) is
49
+ * rejected, bounding replay of a captured pin authorization.
50
+ */
51
+ export const OWNER_AUTH_MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes
52
+ /** Operating modes a node can advertise. */
53
+ export const NODE_MODES = ['self-hosted', 'managed'];
54
+ /** The node operation an owner can authorize with a signed header. */
55
+ export const OWNER_ACTION_BLOB_PIN = 'blob-pin';
56
+ /** A 32-byte (64 hex char) lowercase SHA-256 digest, used as the blob address. */
57
+ export const SHA256_HEX = /^[0-9a-f]{64}$/;
58
+ /* -------------------------------------------------------------------------- */
59
+ /* HTTP NodeClient — the node-facing routes a client drives */
60
+ /* -------------------------------------------------------------------------- */
61
+ /** Chain head endpoint (`GET`). */
62
+ export const NODE_HEAD_PATH = '/oxy/head';
63
+ /** Ordered log endpoint (`GET ?since=&limit=`). */
64
+ export const NODE_LOG_PATH = '/oxy/log';
65
+ /** Single-record write endpoint (`POST`, owner-signed envelope). */
66
+ export const NODE_RECORDS_PATH = '/records';
67
+ /** Batch push endpoint (`POST`, owner-signed envelopes). */
68
+ export const NODE_SYNC_PUSH_PATH = '/sync/push';
69
+ /** Content-addressed blob endpoint prefix (`GET|PUT /blobs/:hash`). */
70
+ export const NODE_BLOBS_PATH = '/blobs';
71
+ /** Default time-to-first-byte deadline for a NodeClient request (ms). */
72
+ export const DEFAULT_CLIENT_TIMEOUT_MS = 8000;
73
+ /** Default redirect budget for a NodeClient request (each re-validated upstream). */
74
+ export const DEFAULT_CLIENT_MAX_REDIRECTS = 1;
75
+ /** Default bounded read for a `/oxy/head` response (tiny JSON). */
76
+ export const DEFAULT_HEAD_MAX_BYTES = 64 * 1024;
77
+ /** Default bounded read for a `/oxy/log` page response. */
78
+ export const DEFAULT_LOG_MAX_BYTES = 2 * 1024 * 1024;
79
+ /** Default bounded read for a small JSON write response (`/records`, blob pin). */
80
+ export const DEFAULT_WRITE_RESPONSE_MAX_BYTES = 64 * 1024;
81
+ /** Default bounded read for a fetched `<did>.json` document. */
82
+ export const DEFAULT_DID_DOC_MAX_BYTES = 256 * 1024;