@oked/receipt-core 0.5.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OKed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # @oked/receipt-core
2
+
3
+ The format and the cryptography of OKed signed approval receipts, shared by the
4
+ OKed backend (which signs), `@oked/sdk` (which verifies before an action runs)
5
+ and `@oked/verify` (which auditors run). One implementation, so all three
6
+ compute the same bytes and the same digests.
7
+
8
+ A receipt is a JSON body signed with Ed25519 over its RFC 8785 canonical form
9
+ (JCS). It proves who decided on an agent action, how they were verified, what
10
+ exact action they decided on, and when. See
11
+ [docs/receipts.md](https://github.com/oked-ai/oked-sdk/blob/main/docs/receipts.md)
12
+ for the format, what a receipt proves and what it does not.
13
+
14
+ ```ts
15
+ import { verifyReceipt, verifyChain } from "@oked/receipt-core";
16
+
17
+ const keys = await (await fetch("https://api.oked.ai/.well-known/oked-receipt-keys.json")).json();
18
+ const check = verifyReceipt(receipt, { keys });
19
+ // { ok: true, problems: [] } or e.g. { ok: false, problems: ["bad_signature"] }
20
+ ```
21
+
22
+ | Export | What it does |
23
+ |---|---|
24
+ | `canonicalize(value)` | RFC 8785 JCS. Throws on values JSON cannot carry. |
25
+ | `jsonValue(value)` | The value as the other side of a JSON request sees it (undefined becomes null). |
26
+ | `subjectDigest(subject)` | `sha256:` digest of what was authorized (`subject_core`). |
27
+ | `displayDigest(shown)` | `sha256:` digest of what the approver was shown. |
28
+ | `bodyDigest(body)` | A receipt body's digest; the next receipt's `prev_receipt_digest`. |
29
+ | `verifyReceipt(receipt, { keys, subject? })` | Shape, key window, signature and, given the original request, the subject digest. |
30
+ | `verifyChain(receipts, heads?)` | Seq gaps, broken `prev_receipt_digest` links, duplicates, and agreement with saved chain heads. |
31
+ | `signerFromSeed(seed, kid)`, `signBody(body, signer)` | Signing, for the issuer. |
32
+
33
+ Node 18+, ESM, no dependencies (uses `node:crypto`). MIT.
@@ -0,0 +1,12 @@
1
+ import type { Digest, DisplayShown, ToolCallSubject } from "./types.js";
2
+ /** `sha256:` + lowercase hex of SHA-256 over the UTF-8 bytes of `text`. */
3
+ export declare function sha256Digest(text: string): Digest;
4
+ /** Digest of any JSON value's canonical form. */
5
+ export declare function jcsDigest(value: unknown): Digest;
6
+ /** What was authorized. */
7
+ export declare function subjectDigest(subject: ToolCallSubject): Digest;
8
+ /** What the approver was shown. */
9
+ export declare function displayDigest(shown: DisplayShown): Digest;
10
+ /** A signed body's digest; the next receipt's prev_receipt_digest. */
11
+ export declare function bodyDigest(body: unknown): Digest;
12
+ export declare const DIGEST_PATTERN: RegExp;
package/dist/digest.js ADDED
@@ -0,0 +1,23 @@
1
+ import { createHash } from "node:crypto";
2
+ import { canonicalize } from "./jcs.js";
3
+ /** `sha256:` + lowercase hex of SHA-256 over the UTF-8 bytes of `text`. */
4
+ export function sha256Digest(text) {
5
+ return `sha256:${createHash("sha256").update(text, "utf8").digest("hex")}`;
6
+ }
7
+ /** Digest of any JSON value's canonical form. */
8
+ export function jcsDigest(value) {
9
+ return sha256Digest(canonicalize(value));
10
+ }
11
+ /** What was authorized. */
12
+ export function subjectDigest(subject) {
13
+ return jcsDigest(subject);
14
+ }
15
+ /** What the approver was shown. */
16
+ export function displayDigest(shown) {
17
+ return jcsDigest(shown);
18
+ }
19
+ /** A signed body's digest; the next receipt's prev_receipt_digest. */
20
+ export function bodyDigest(body) {
21
+ return jcsDigest(body);
22
+ }
23
+ export const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/;
package/dist/ids.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { ReceiptDecision } from "./types.js";
2
+ /** `rcpt_` + 26 Crockford base32 characters (128 random bits). */
3
+ export declare function newReceiptId(): string;
4
+ /** The short form shown in Telegram and the dashboard, e.g. `rcpt_7Q2F`. */
5
+ export declare function shortReceiptId(receiptId: string): string;
6
+ /** Chain key: per operator, or per API key for a key with no operator. */
7
+ export declare function chainIdFor(operatorId: string | null, apiKeyId: string | null): string;
8
+ /** DB status -> receipt decision. The DB says "timeout"; receipts say "timed_out". */
9
+ export declare function receiptDecision(status: string): ReceiptDecision;
10
+ /** Receipt decision -> the decision string /approve returns to clients. */
11
+ export declare function responseDecision(decision: ReceiptDecision): "approved" | "denied" | "timeout";
package/dist/ids.js ADDED
@@ -0,0 +1,44 @@
1
+ import { randomBytes } from "node:crypto";
2
+ const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
3
+ /** `rcpt_` + 26 Crockford base32 characters (128 random bits). */
4
+ export function newReceiptId() {
5
+ const bytes = randomBytes(16);
6
+ let bits = 0;
7
+ let value = 0;
8
+ let out = "";
9
+ for (const byte of bytes) {
10
+ value = (value << 8) | byte;
11
+ bits += 8;
12
+ while (bits >= 5) {
13
+ out += CROCKFORD[(value >>> (bits - 5)) & 31];
14
+ bits -= 5;
15
+ }
16
+ }
17
+ if (bits > 0)
18
+ out += CROCKFORD[(value << (5 - bits)) & 31];
19
+ return `rcpt_${out}`;
20
+ }
21
+ /** The short form shown in Telegram and the dashboard, e.g. `rcpt_7Q2F`. */
22
+ export function shortReceiptId(receiptId) {
23
+ return receiptId.slice(0, 9);
24
+ }
25
+ /** Chain key: per operator, or per API key for a key with no operator. */
26
+ export function chainIdFor(operatorId, apiKeyId) {
27
+ if (operatorId)
28
+ return `op_${operatorId}`;
29
+ if (apiKeyId)
30
+ return `key_${apiKeyId}`;
31
+ throw new Error("a receipt chain needs an operator or an API key");
32
+ }
33
+ /** DB status -> receipt decision. The DB says "timeout"; receipts say "timed_out". */
34
+ export function receiptDecision(status) {
35
+ if (status === "approved" || status === "denied")
36
+ return status;
37
+ if (status === "timeout")
38
+ return "timed_out";
39
+ throw new Error(`no receipt decision for status ${JSON.stringify(status)}`);
40
+ }
41
+ /** Receipt decision -> the decision string /approve returns to clients. */
42
+ export function responseDecision(decision) {
43
+ return decision === "timed_out" ? "timeout" : decision;
44
+ }
@@ -0,0 +1,8 @@
1
+ export { canonicalize, jsonValue } from "./jcs.js";
2
+ export { sha256Digest, jcsDigest, subjectDigest, displayDigest, bodyDigest, DIGEST_PATTERN } from "./digest.js";
3
+ export { generateSigningSeed, publicKeyFromSeed, signerFromSeed, signBody, signatureValid, type ReceiptSigner, } from "./sign.js";
4
+ export { verifyReceipt, verifySigned, verifyChain, keyCovers, type ReceiptCheck, type ReceiptProblem, type VerifyReceiptOptions, type ChainReport, } from "./verify.js";
5
+ export { newReceiptId, shortReceiptId, chainIdFor, receiptDecision, responseDecision } from "./ids.js";
6
+ export type * from "./types.js";
7
+ /** Where OKed publishes its receipt keys. */
8
+ export declare const OKED_RECEIPT_KEYS_URL = "https://api.oked.ai/.well-known/oked-receipt-keys.json";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { canonicalize, jsonValue } from "./jcs.js";
2
+ export { sha256Digest, jcsDigest, subjectDigest, displayDigest, bodyDigest, DIGEST_PATTERN } from "./digest.js";
3
+ export { generateSigningSeed, publicKeyFromSeed, signerFromSeed, signBody, signatureValid, } from "./sign.js";
4
+ export { verifyReceipt, verifySigned, verifyChain, keyCovers, } from "./verify.js";
5
+ export { newReceiptId, shortReceiptId, chainIdFor, receiptDecision, responseDecision } from "./ids.js";
6
+ /** Where OKed publishes its receipt keys. */
7
+ export const OKED_RECEIPT_KEYS_URL = "https://api.oked.ai/.well-known/oked-receipt-keys.json";
package/dist/jcs.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import type { JsonValue } from "./types.js";
2
+ /**
3
+ * RFC 8785 JSON Canonicalization Scheme. Objects get their keys sorted by
4
+ * UTF-16 code unit (the default JavaScript string order) and no whitespace;
5
+ * numbers and strings use the ECMAScript serialization RFC 8785 adopts, which
6
+ * is what JSON.stringify produces for a finite number or a string.
7
+ *
8
+ * Throws on values JSON cannot carry (undefined, functions, non-finite
9
+ * numbers), so a digest is never taken over something the other side could
10
+ * not have received.
11
+ */
12
+ export declare function canonicalize(value: unknown): string;
13
+ /**
14
+ * The value the other side of a JSON request actually sees: undefined becomes
15
+ * null, nested undefined members disappear, Dates become strings, non-finite
16
+ * numbers become null. Hash this, never the raw in-memory object.
17
+ */
18
+ export declare function jsonValue(value: unknown): JsonValue;
package/dist/jcs.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * RFC 8785 JSON Canonicalization Scheme. Objects get their keys sorted by
3
+ * UTF-16 code unit (the default JavaScript string order) and no whitespace;
4
+ * numbers and strings use the ECMAScript serialization RFC 8785 adopts, which
5
+ * is what JSON.stringify produces for a finite number or a string.
6
+ *
7
+ * Throws on values JSON cannot carry (undefined, functions, non-finite
8
+ * numbers), so a digest is never taken over something the other side could
9
+ * not have received.
10
+ */
11
+ export function canonicalize(value) {
12
+ if (value === null)
13
+ return "null";
14
+ switch (typeof value) {
15
+ case "boolean":
16
+ return value ? "true" : "false";
17
+ case "number":
18
+ if (!Number.isFinite(value))
19
+ throw new TypeError(`JCS: non-finite number ${value}`);
20
+ return JSON.stringify(value);
21
+ case "string":
22
+ return JSON.stringify(value);
23
+ case "object": {
24
+ if (Array.isArray(value))
25
+ return `[${value.map(canonicalize).join(",")}]`;
26
+ const obj = value;
27
+ const keys = Object.keys(obj).sort();
28
+ const parts = [];
29
+ for (const key of keys) {
30
+ if (obj[key] === undefined)
31
+ throw new TypeError(`JCS: undefined value at key ${JSON.stringify(key)}`);
32
+ parts.push(`${JSON.stringify(key)}:${canonicalize(obj[key])}`);
33
+ }
34
+ return `{${parts.join(",")}}`;
35
+ }
36
+ default:
37
+ throw new TypeError(`JCS: cannot serialize a ${typeof value}`);
38
+ }
39
+ }
40
+ /**
41
+ * The value the other side of a JSON request actually sees: undefined becomes
42
+ * null, nested undefined members disappear, Dates become strings, non-finite
43
+ * numbers become null. Hash this, never the raw in-memory object.
44
+ */
45
+ export function jsonValue(value) {
46
+ if (value === undefined)
47
+ return null;
48
+ const text = JSON.stringify(value);
49
+ return text === undefined ? null : JSON.parse(text);
50
+ }
package/dist/sign.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { ReceiptKey, Signed } from "./types.js";
2
+ export interface ReceiptSigner {
3
+ kid: string;
4
+ /** base64url of the raw 32-byte public key, as published in the key set. */
5
+ publicKey: string;
6
+ sign(message: Uint8Array): string;
7
+ }
8
+ /** A fresh signing key: the seed is the secret, the public key is published. */
9
+ export declare function generateSigningSeed(): {
10
+ seed: string;
11
+ publicKey: string;
12
+ };
13
+ export declare function publicKeyFromSeed(seed: string): string;
14
+ /** A signer for the base64url seed held in OKED_RECEIPT_SIGNING_KEY. */
15
+ export declare function signerFromSeed(seed: string, kid: string): ReceiptSigner;
16
+ /** Sign a body: Ed25519 over the UTF-8 bytes of JCS(body). */
17
+ export declare function signBody<B>(body: B, signer: ReceiptSigner): Signed<B>;
18
+ /** True when `envelope.sig` is a valid signature by `key` over JCS(envelope.body). */
19
+ export declare function signatureValid(envelope: Signed<unknown>, key: Pick<ReceiptKey, "public_key">): boolean;
package/dist/sign.js ADDED
@@ -0,0 +1,52 @@
1
+ import { createPrivateKey, createPublicKey, randomBytes, sign, verify } from "node:crypto";
2
+ import { canonicalize } from "./jcs.js";
3
+ // PKCS#8 DER prefix for a raw 32-byte Ed25519 seed (RFC 8410).
4
+ const PKCS8_ED25519_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
5
+ function decodeSeed(seed) {
6
+ const raw = Buffer.from(seed.trim(), "base64url");
7
+ if (raw.length !== 32)
8
+ throw new Error("receipt signing key must be a base64url-encoded 32-byte Ed25519 seed");
9
+ return raw;
10
+ }
11
+ function rawPublicKey(key) {
12
+ const jwk = key.export({ format: "jwk" });
13
+ if (!jwk.x)
14
+ throw new Error("not an Ed25519 key");
15
+ return jwk.x;
16
+ }
17
+ /** A fresh signing key: the seed is the secret, the public key is published. */
18
+ export function generateSigningSeed() {
19
+ const seed = randomBytes(32).toString("base64url");
20
+ return { seed, publicKey: publicKeyFromSeed(seed) };
21
+ }
22
+ export function publicKeyFromSeed(seed) {
23
+ const priv = createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_PREFIX, decodeSeed(seed)]), format: "der", type: "pkcs8" });
24
+ return rawPublicKey(createPublicKey(priv));
25
+ }
26
+ /** A signer for the base64url seed held in OKED_RECEIPT_SIGNING_KEY. */
27
+ export function signerFromSeed(seed, kid) {
28
+ const priv = createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_PREFIX, decodeSeed(seed)]), format: "der", type: "pkcs8" });
29
+ return {
30
+ kid,
31
+ publicKey: rawPublicKey(createPublicKey(priv)),
32
+ sign: (message) => sign(null, message, priv).toString("base64url"),
33
+ };
34
+ }
35
+ /** Sign a body: Ed25519 over the UTF-8 bytes of JCS(body). */
36
+ export function signBody(body, signer) {
37
+ const message = Buffer.from(canonicalize(body), "utf8");
38
+ return { body, alg: "Ed25519", kid: signer.kid, sig: signer.sign(message) };
39
+ }
40
+ function publicKeyObject(publicKey) {
41
+ return createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: publicKey }, format: "jwk" });
42
+ }
43
+ /** True when `envelope.sig` is a valid signature by `key` over JCS(envelope.body). */
44
+ export function signatureValid(envelope, key) {
45
+ try {
46
+ const message = Buffer.from(canonicalize(envelope.body), "utf8");
47
+ return verify(null, message, publicKeyObject(key.public_key), Buffer.from(envelope.sig, "base64url"));
48
+ }
49
+ catch {
50
+ return false;
51
+ }
52
+ }
@@ -0,0 +1,119 @@
1
+ /** A JSON value as it travels over the wire (after a JSON round-trip). */
2
+ export type JsonValue = null | boolean | number | string | JsonValue[] | {
3
+ [key: string]: JsonValue;
4
+ };
5
+ /** `sha256:` followed by 64 lowercase hex characters. */
6
+ export type Digest = `sha256:${string}`;
7
+ export type ReceiptDecision = "approved" | "denied" | "timed_out";
8
+ export type DeciderKind = "human" | "rule" | "system";
9
+ export type Assurance = "none" | "channel" | "passkey";
10
+ export type DecisionChannel = "telegram" | "dashboard";
11
+ /** Why a system decider decided. Null for human and rule deciders. */
12
+ export type SystemReason = "timeout" | "classified_safe";
13
+ export type RiskTier = "safe" | "warning" | "review" | "high_stakes";
14
+ export interface ReceiptDecider {
15
+ kind: DeciderKind;
16
+ operator_id: string | null;
17
+ display_name: string | null;
18
+ assurance: Assurance;
19
+ channel: DecisionChannel | null;
20
+ rule_id: string | null;
21
+ reason: SystemReason | null;
22
+ }
23
+ export interface ReceiptRequester {
24
+ operator_id: string | null;
25
+ api_key_id: string | null;
26
+ /** The integration that asked, e.g. "@oked/claude-code@0.5.0". Null for older clients. */
27
+ client: string | null;
28
+ }
29
+ /** The signed part of a receipt. Every field is covered by the signature. */
30
+ export interface ReceiptBody {
31
+ v: 1;
32
+ receipt_id: string;
33
+ /** "op_<operatorId>", or "key_<apiKeyId>" for a key with no operator. */
34
+ chain_id: string;
35
+ /** Position in the chain, starting at 1, with no gaps. */
36
+ seq: number;
37
+ issued_at: string;
38
+ issuer: string;
39
+ operator_id: string | null;
40
+ request_id: string;
41
+ subject_type: "tool_call";
42
+ /** What was authorized: sha256(JCS(subject_core)). */
43
+ subject_digest: Digest;
44
+ /** What the approver was shown: sha256(JCS(shown)). Null when nothing was rendered. */
45
+ display_digest: Digest | null;
46
+ /** The rendered title. Null when the operator turned summaries off. */
47
+ summary: string | null;
48
+ risk_tier: RiskTier;
49
+ decision: ReceiptDecision;
50
+ decided_at: string;
51
+ decider: ReceiptDecider;
52
+ requester: ReceiptRequester;
53
+ /** True only for a human decider whose operator is also the requester's. */
54
+ same_person: boolean;
55
+ /** body_digest of the previous receipt in this chain. Null for seq 1. */
56
+ prev_receipt_digest: Digest | null;
57
+ }
58
+ /** Any signed OKed document: a body plus an Ed25519 signature over JCS(body). */
59
+ export interface Signed<B> {
60
+ body: B;
61
+ alg: "Ed25519";
62
+ kid: string;
63
+ /** base64url (no padding) Ed25519 signature over the UTF-8 bytes of JCS(body). */
64
+ sig: string;
65
+ }
66
+ export type SignedReceipt = Signed<ReceiptBody>;
67
+ /** The latest position of one chain, signed so a customer can keep checkpoints. */
68
+ export interface ChainHeadBody {
69
+ v: 1;
70
+ type: "chain_head";
71
+ chain_id: string;
72
+ operator_id: string | null;
73
+ seq: number;
74
+ /** body_digest of the receipt at `seq`. Null for an empty chain. */
75
+ digest: Digest | null;
76
+ issued_at: string;
77
+ issuer: string;
78
+ }
79
+ export type SignedChainHead = Signed<ChainHeadBody>;
80
+ /** One entry of /.well-known/oked-receipt-keys.json. */
81
+ export interface ReceiptKey {
82
+ kid: string;
83
+ alg: "Ed25519";
84
+ /** base64url (no padding) of the raw 32-byte Ed25519 public key. */
85
+ public_key: string;
86
+ not_before: string;
87
+ /** Null while the key is active. Retired keys stay listed with a not_after. */
88
+ not_after: string | null;
89
+ }
90
+ export interface ReceiptKeySet {
91
+ keys: ReceiptKey[];
92
+ }
93
+ /**
94
+ * subject_core for a hook or SDK tool call: the exact action that was
95
+ * authorized, as the client sent it. Values are JSON as received (missing
96
+ * becomes null), so client and server hash identical bytes.
97
+ */
98
+ export interface ToolCallSubject {
99
+ type: "tool_call";
100
+ operator_id: string | null;
101
+ request_id: string;
102
+ source: string;
103
+ action: string;
104
+ description: JsonValue;
105
+ tool_input: JsonValue;
106
+ /** Random per request, chosen by the client, so an old receipt cannot be replayed. */
107
+ client_nonce: string | null;
108
+ }
109
+ /** What the approver was shown: the classification row that rendered the card. */
110
+ export interface DisplayShown {
111
+ classifier_version: string;
112
+ tier: string;
113
+ title: string;
114
+ target: string | null;
115
+ annotation: string | null;
116
+ subline: string | null;
117
+ body: string | null;
118
+ footnote: string | null;
119
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,57 @@
1
+ import type { ChainHeadBody, ReceiptKey, ReceiptKeySet, SignedReceipt, ToolCallSubject } from "./types.js";
2
+ export type ReceiptProblem = "malformed" | "unknown_kid" | "key_not_valid_at_issued_at" | "bad_signature" | "subject_mismatch";
3
+ export interface ReceiptCheck {
4
+ ok: boolean;
5
+ problems: ReceiptProblem[];
6
+ /** The key that verified the signature, when one was found. */
7
+ key?: ReceiptKey;
8
+ }
9
+ export interface VerifyReceiptOptions {
10
+ keys: ReceiptKey[] | ReceiptKeySet;
11
+ /** The original request. When given, subject_digest must match it. */
12
+ subject?: ToolCallSubject;
13
+ }
14
+ /** A key covers an instant when not_before <= t and (no not_after or t < not_after). */
15
+ export declare function keyCovers(key: ReceiptKey, isoTime: string): boolean;
16
+ /** Verify any signed OKed document (receipt or chain head) against a key set. */
17
+ export declare function verifySigned(envelope: unknown, keys: ReceiptKey[] | ReceiptKeySet, issuedAt?: string): ReceiptCheck;
18
+ /**
19
+ * Check one receipt: shape, a known key whose window covers issued_at, the
20
+ * signature, and, when the original request is given, the subject digest.
21
+ */
22
+ export declare function verifyReceipt(receipt: unknown, opts: VerifyReceiptOptions): ReceiptCheck;
23
+ export interface ChainReport {
24
+ chain_id: string;
25
+ count: number;
26
+ first_seq: number;
27
+ last_seq: number;
28
+ /** True when the receipts start at seq 1, so the first link is checkable too. */
29
+ from_genesis: boolean;
30
+ /** Missing runs of seq between receipts we have, e.g. { after: 4, before: 7 }. */
31
+ gaps: {
32
+ after: number;
33
+ before: number;
34
+ }[];
35
+ /** A receipt whose prev_receipt_digest does not match the receipt before it, or a repeated seq. */
36
+ breaks: {
37
+ seq: number;
38
+ reason: "prev_digest_mismatch" | "duplicate_seq" | "genesis_has_prev";
39
+ }[];
40
+ /**
41
+ * Set when a chain head was given. digest_matches is null when the receipt
42
+ * at the head's seq is not in the set; missing_tail means the head is ahead
43
+ * of the newest receipt we have.
44
+ */
45
+ head?: {
46
+ seq: number;
47
+ digest_matches: boolean | null;
48
+ missing_tail: boolean;
49
+ };
50
+ }
51
+ /**
52
+ * Check chain integrity over a set of receipts (an export, or a local copy).
53
+ * Signatures are not checked here; run verifyReceipt on each receipt too.
54
+ * A local copy from one device legitimately has gaps: other devices of the
55
+ * same operator share the chain.
56
+ */
57
+ export declare function verifyChain(receipts: SignedReceipt[], heads?: ChainHeadBody[]): ChainReport[];
package/dist/verify.js ADDED
@@ -0,0 +1,130 @@
1
+ import { bodyDigest, subjectDigest, DIGEST_PATTERN } from "./digest.js";
2
+ import { signatureValid } from "./sign.js";
3
+ const DECISIONS = new Set(["approved", "denied", "timed_out"]);
4
+ const KINDS = new Set(["human", "rule", "system"]);
5
+ function keyList(keys) {
6
+ return Array.isArray(keys) ? keys : keys.keys ?? [];
7
+ }
8
+ function isEnvelope(x) {
9
+ if (!x || typeof x !== "object")
10
+ return false;
11
+ const e = x;
12
+ return (!!e.body && typeof e.body === "object" && !Array.isArray(e.body) &&
13
+ e.alg === "Ed25519" && typeof e.kid === "string" && typeof e.sig === "string");
14
+ }
15
+ function isReceiptShape(x) {
16
+ if (!isEnvelope(x))
17
+ return false;
18
+ const b = x.body;
19
+ const decider = b.decider;
20
+ return (b.v === 1 &&
21
+ typeof b.receipt_id === "string" &&
22
+ typeof b.chain_id === "string" &&
23
+ Number.isInteger(b.seq) && b.seq >= 1 &&
24
+ typeof b.issued_at === "string" &&
25
+ typeof b.request_id === "string" &&
26
+ typeof b.subject_digest === "string" && DIGEST_PATTERN.test(b.subject_digest) &&
27
+ typeof b.decision === "string" && DECISIONS.has(b.decision) &&
28
+ !!decider && typeof decider.kind === "string" && KINDS.has(decider.kind) &&
29
+ (b.prev_receipt_digest === null || (typeof b.prev_receipt_digest === "string" && DIGEST_PATTERN.test(b.prev_receipt_digest))));
30
+ }
31
+ /** A key covers an instant when not_before <= t and (no not_after or t < not_after). */
32
+ export function keyCovers(key, isoTime) {
33
+ const t = Date.parse(isoTime);
34
+ if (Number.isNaN(t))
35
+ return false;
36
+ if (Date.parse(key.not_before) > t)
37
+ return false;
38
+ return key.not_after === null || t < Date.parse(key.not_after);
39
+ }
40
+ /** Verify any signed OKed document (receipt or chain head) against a key set. */
41
+ export function verifySigned(envelope, keys, issuedAt) {
42
+ if (!isEnvelope(envelope))
43
+ return { ok: false, problems: ["malformed"] };
44
+ const key = keyList(keys).find((k) => k.kid === envelope.kid && k.alg === "Ed25519");
45
+ if (!key)
46
+ return { ok: false, problems: ["unknown_kid"] };
47
+ const problems = [];
48
+ const at = issuedAt ?? envelope.body.issued_at;
49
+ if (typeof at !== "string" || !keyCovers(key, at))
50
+ problems.push("key_not_valid_at_issued_at");
51
+ if (!signatureValid(envelope, key))
52
+ problems.push("bad_signature");
53
+ return { ok: problems.length === 0, problems, key };
54
+ }
55
+ /**
56
+ * Check one receipt: shape, a known key whose window covers issued_at, the
57
+ * signature, and, when the original request is given, the subject digest.
58
+ */
59
+ export function verifyReceipt(receipt, opts) {
60
+ if (!isReceiptShape(receipt))
61
+ return { ok: false, problems: ["malformed"] };
62
+ const check = verifySigned(receipt, opts.keys);
63
+ if (opts.subject) {
64
+ const s = opts.subject;
65
+ const matches = s.request_id === receipt.body.request_id &&
66
+ s.operator_id === receipt.body.operator_id &&
67
+ subjectDigest(s) === receipt.body.subject_digest;
68
+ if (!matches) {
69
+ check.problems.push("subject_mismatch");
70
+ check.ok = false;
71
+ }
72
+ }
73
+ return check;
74
+ }
75
+ /**
76
+ * Check chain integrity over a set of receipts (an export, or a local copy).
77
+ * Signatures are not checked here; run verifyReceipt on each receipt too.
78
+ * A local copy from one device legitimately has gaps: other devices of the
79
+ * same operator share the chain.
80
+ */
81
+ export function verifyChain(receipts, heads = []) {
82
+ const byChain = new Map();
83
+ for (const r of receipts) {
84
+ const list = byChain.get(r.body.chain_id) ?? [];
85
+ list.push(r);
86
+ byChain.set(r.body.chain_id, list);
87
+ }
88
+ const reports = [];
89
+ for (const [chainId, list] of byChain) {
90
+ list.sort((a, b) => a.body.seq - b.body.seq);
91
+ const report = {
92
+ chain_id: chainId,
93
+ count: list.length,
94
+ first_seq: list[0].body.seq,
95
+ last_seq: list[list.length - 1].body.seq,
96
+ from_genesis: list[0].body.seq === 1,
97
+ gaps: [],
98
+ breaks: [],
99
+ };
100
+ if (list[0].body.seq === 1 && list[0].body.prev_receipt_digest !== null) {
101
+ report.breaks.push({ seq: 1, reason: "genesis_has_prev" });
102
+ }
103
+ for (let i = 1; i < list.length; i++) {
104
+ const prev = list[i - 1].body;
105
+ const cur = list[i].body;
106
+ if (cur.seq === prev.seq) {
107
+ report.breaks.push({ seq: cur.seq, reason: "duplicate_seq" });
108
+ }
109
+ else if (cur.seq === prev.seq + 1) {
110
+ if (cur.prev_receipt_digest !== bodyDigest(prev)) {
111
+ report.breaks.push({ seq: cur.seq, reason: "prev_digest_mismatch" });
112
+ }
113
+ }
114
+ else {
115
+ report.gaps.push({ after: prev.seq, before: cur.seq });
116
+ }
117
+ }
118
+ const head = heads.find((h) => h.chain_id === chainId);
119
+ if (head) {
120
+ const atHead = list.find((r) => r.body.seq === head.seq);
121
+ report.head = {
122
+ seq: head.seq,
123
+ digest_matches: atHead ? bodyDigest(atHead.body) === head.digest : null,
124
+ missing_tail: report.last_seq < head.seq,
125
+ };
126
+ }
127
+ reports.push(report);
128
+ }
129
+ return reports;
130
+ }
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@oked/receipt-core",
3
+ "version": "0.5.0",
4
+ "description": "OKed signed approval receipts: format, canonical JSON, digests, signing and verification",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.js",
11
+ "types": "./dist/index.d.ts"
12
+ }
13
+ },
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "dev": "tsc --watch",
17
+ "test": "tsx --test test/*.test.ts",
18
+ "prepublishOnly": "npm run build"
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "keywords": [
24
+ "approval",
25
+ "receipt",
26
+ "audit",
27
+ "ed25519",
28
+ "agents"
29
+ ],
30
+ "repository": {
31
+ "type": "git",
32
+ "url": "git+https://github.com/oked-ai/oked-sdk.git",
33
+ "directory": "packages/receipt-core"
34
+ },
35
+ "bugs": {
36
+ "url": "https://github.com/oked-ai/oked-sdk/issues"
37
+ },
38
+ "homepage": "https://github.com/oked-ai/oked-sdk/blob/main/docs/receipts.md",
39
+ "license": "MIT",
40
+ "engines": {
41
+ "node": ">=18"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "^22.13.10",
48
+ "tsx": "^4.22.0",
49
+ "typescript": "^5.6.0"
50
+ }
51
+ }