@sess.si/sdk 0.4.0 → 0.6.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/CHANGELOG.md +23 -0
- package/README.md +19 -16
- package/dist/ask.d.ts +5 -5
- package/dist/ask.js +6 -6
- package/dist/client.js +1 -0
- package/dist/commerce/builders.d.ts +2 -2
- package/dist/commerce/builders.js +4 -4
- package/dist/commerce/items.d.ts +3 -3
- package/dist/commerce/items.js +2 -2
- package/dist/errors.d.ts +1 -1
- package/dist/generated/openapi.d.ts +6692 -2673
- package/dist/internal/decode.js +21 -0
- package/dist/internal/version.d.ts +1 -1
- package/dist/internal/version.js +1 -1
- package/dist/receipts/closing.d.ts +82 -0
- package/dist/receipts/closing.js +237 -0
- package/dist/receipts/index.d.ts +3 -1
- package/dist/receipts/index.js +1 -0
- package/dist/receipts/resource.d.ts +22 -1
- package/dist/receipts/resource.js +91 -0
- package/dist/receipts/verify.d.ts +4 -0
- package/dist/receipts/verify.js +3 -3
- package/dist/types.d.ts +22 -14
- package/package.json +1 -1
package/dist/internal/decode.js
CHANGED
|
@@ -349,8 +349,29 @@ export function decodeEvents(value, expectedId) {
|
|
|
349
349
|
// Event type), only where the deployment enables them.
|
|
350
350
|
if (v.link_extensions !== undefined)
|
|
351
351
|
linkExtensions(v.link_extensions);
|
|
352
|
+
// Decision 0016: the closing receipt is its own typed member beside the Events, never an Event
|
|
353
|
+
// and never a round's receipt. Only its shape is checked here; verifying it is verifyClosing's.
|
|
354
|
+
if (v.closing !== undefined)
|
|
355
|
+
closing(v.closing, v.events);
|
|
352
356
|
return value;
|
|
353
357
|
}
|
|
358
|
+
const closingPattern = new RegExp(`^cls_${ulid}$`);
|
|
359
|
+
const closingKeys = ['typ', 'closure_id', 'cause', 'terminal_event_id', 'accepted_rounds', 'receipt'];
|
|
360
|
+
function closing(value, events) {
|
|
361
|
+
const v = object(value);
|
|
362
|
+
if (Object.keys(v).length !== closingKeys.length || !closingKeys.every((k) => Object.hasOwn(v, k)))
|
|
363
|
+
protocol();
|
|
364
|
+
if (v.typ !== 'sess-closing-receipt+jwt')
|
|
365
|
+
protocol();
|
|
366
|
+
string(v.closure_id, closingPattern);
|
|
367
|
+
oneOf(v.cause, ['completed_by_owner', 'completed_by_ask_rule', 'final_expiry', 'revoked']);
|
|
368
|
+
if (v.terminal_event_id !== null)
|
|
369
|
+
string(v.terminal_event_id, eventPattern);
|
|
370
|
+
// Present only beside exactly the rounds it signs: its count is the Events' accepted answers.
|
|
371
|
+
if (integer(v.accepted_rounds) !== events.filter((e) => e.type === 'response.accepted').length)
|
|
372
|
+
protocol();
|
|
373
|
+
string(v.receipt, receiptPattern, 8192);
|
|
374
|
+
}
|
|
354
375
|
function endpoint(value) {
|
|
355
376
|
const v = object(value);
|
|
356
377
|
string(v.id, new RegExp(`^whe_${ulid}$`));
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version, sent in the User-Agent header. Tests check it against package.json. */
|
|
2
|
-
export declare const SDK_VERSION = "0.
|
|
2
|
+
export declare const SDK_VERSION = "0.6.0";
|
package/dist/internal/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version, sent in the User-Agent header. Tests check it against package.json. */
|
|
2
|
-
export const SDK_VERSION = '0.
|
|
2
|
+
export const SDK_VERSION = '0.6.0';
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type DeepReadonly } from './json.js';
|
|
2
|
+
import { type ReceiptKeyResolver, type ReceiptKeySet } from './verify.js';
|
|
3
|
+
/** Protected `typ` of a closing receipt (closing-receipt-v1 §1); never a round receipt's. */
|
|
4
|
+
export declare const CLOSING_RECEIPT_TYP = "sess-closing-receipt+jwt";
|
|
5
|
+
/** A closing receipt is at most 8,192 bytes (its archival object's bound, closing-receipt-v1 §7). */
|
|
6
|
+
export declare const MAX_CLOSING_RECEIPT_BYTES = 8192;
|
|
7
|
+
declare const CAUSES: readonly ["completed_by_owner", "completed_by_ask_rule", "final_expiry", "revoked"];
|
|
8
|
+
/** How a Session ended, as its closing receipt signs it (closing-receipt-v1 §4). */
|
|
9
|
+
export type ClosingCause = (typeof CAUSES)[number];
|
|
10
|
+
/** A verified closing receipt's claims (closing-receipt-v1 §2): every member, no other, no `exp`. */
|
|
11
|
+
export interface ClosingReceiptClaims {
|
|
12
|
+
sess_closing_receipt: 1;
|
|
13
|
+
iss: string;
|
|
14
|
+
/** The Session's workspace, equal to `workspace_id`. */
|
|
15
|
+
aud: string;
|
|
16
|
+
/** The closure ID (`cls_…`). */
|
|
17
|
+
jti: string;
|
|
18
|
+
iat: number;
|
|
19
|
+
workspace_id: string;
|
|
20
|
+
session_id: string;
|
|
21
|
+
terminal: {
|
|
22
|
+
/** The Event that ended the Session; null only for `revoked`. */
|
|
23
|
+
event_id: string | null;
|
|
24
|
+
cause: ClosingCause;
|
|
25
|
+
/** `sess` for `final_expiry`, else `owner`: derived from the cause. */
|
|
26
|
+
actor_class: 'owner' | 'sess';
|
|
27
|
+
};
|
|
28
|
+
effective_end_at: string;
|
|
29
|
+
recorded_at: string;
|
|
30
|
+
issued_at: string;
|
|
31
|
+
/** Ordered by scope. Version 1 has `accepted_rounds`; a scope this release does not know is refused as newer. */
|
|
32
|
+
commitments: {
|
|
33
|
+
scope: string;
|
|
34
|
+
count: number;
|
|
35
|
+
commitment: string;
|
|
36
|
+
}[];
|
|
37
|
+
}
|
|
38
|
+
export interface VerifyClosingReceiptInput {
|
|
39
|
+
/** The closing receipt's compact JWS (`closing.receipt` beside a Session's Events). */
|
|
40
|
+
receipt: string;
|
|
41
|
+
/** Trusted protocol identity, independently configured. */
|
|
42
|
+
issuer: string;
|
|
43
|
+
/** Trusted workspace, never read from an unverified receipt. */
|
|
44
|
+
audience: string;
|
|
45
|
+
/** Optional bindings the receipt must name: the Session and the closure (`closing.closure_id`). */
|
|
46
|
+
expected?: {
|
|
47
|
+
sessionId?: string;
|
|
48
|
+
closureId?: string;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Optional: the accepted rounds' receipts, in their Event order. When given, the signed
|
|
52
|
+
* `accepted_rounds` count and commitment must be exactly these receipts' bytes, in this order;
|
|
53
|
+
* any other set is refused with `CLOSING_ROUNDS_MISMATCH`. Each round receipt is verified on its
|
|
54
|
+
* own (`receipts.verifyResponse`); this checks only that the set is the one the receipt signs.
|
|
55
|
+
*/
|
|
56
|
+
rounds?: readonly string[];
|
|
57
|
+
keys?: ReceiptKeySet;
|
|
58
|
+
keyResolver?: ReceiptKeyResolver;
|
|
59
|
+
}
|
|
60
|
+
export interface VerifyClosingReceiptOptions {
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
}
|
|
63
|
+
/** The commitment over round receipts' exact bytes, in order (closing-receipt-v1 §3). */
|
|
64
|
+
export declare function closingCommitmentOf(receipts: readonly string[]): string;
|
|
65
|
+
/**
|
|
66
|
+
* Verifies a Session's closing receipt (closing-receipt-v1 §6) under the keys you trust for the
|
|
67
|
+
* issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys. It returns the
|
|
68
|
+
* verified claims, deeply frozen, or throws a `SessError`; nothing is returned with a refusal.
|
|
69
|
+
*
|
|
70
|
+
* In order: a compact JWS of at most 8,192 bytes; `alg` exactly `EdDSA`; a `kid` you trust;
|
|
71
|
+
* `typ` exactly `sess-closing-receipt+jwt` (a round receipt is refused here with
|
|
72
|
+
* `UNSUPPORTED_TYPE`); the header exactly `alg`, `kid` and `typ`; the Ed25519 signature; the
|
|
73
|
+
* issuer and workspace; the format version; the strict claims, with no `exp`; RFC 8785 canonical
|
|
74
|
+
* JSON; then the optional Session, closure and round-set bindings. A format version above 1, or a
|
|
75
|
+
* commitment scope this release does not know, is newer: kind `receipt_newer`, code
|
|
76
|
+
* `RECEIPT_NEWER`, never a verification failure.
|
|
77
|
+
*
|
|
78
|
+
* A valid closing receipt says only that these are the final accepted rounds Sess signed for the
|
|
79
|
+
* Session, and how it ended; it is not a receipt for any one answer.
|
|
80
|
+
*/
|
|
81
|
+
export declare function verifyClosingReceipt(input: VerifyClosingReceiptInput, options?: VerifyClosingReceiptOptions): Promise<DeepReadonly<ClosingReceiptClaims>>;
|
|
82
|
+
export {};
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { compactVerify, importJWK } from 'jose';
|
|
3
|
+
import { abortError, canonicalJson, checkedInstant, deepFreeze, exactKeys, isRecord, newerReceiptError, snapshotJson, verificationError, waitWithSignal, } from './json.js';
|
|
4
|
+
import { decodeSegment, identifier, trustedKeyLookup, validateKeySet, } from './verify.js';
|
|
5
|
+
/** Protected `typ` of a closing receipt (closing-receipt-v1 §1); never a round receipt's. */
|
|
6
|
+
export const CLOSING_RECEIPT_TYP = 'sess-closing-receipt+jwt';
|
|
7
|
+
/** A closing receipt is at most 8,192 bytes (its archival object's bound, closing-receipt-v1 §7). */
|
|
8
|
+
export const MAX_CLOSING_RECEIPT_BYTES = 8192;
|
|
9
|
+
/** The receipt key ID grammar (verify.ts, bundle.ts). */
|
|
10
|
+
const KID = /^[A-Za-z0-9._-]{1,64}$/;
|
|
11
|
+
/** A round receipt entering the commitment is at most 32,768 bytes (closing-receipt-v1 §3). */
|
|
12
|
+
const MAX_ROUND_RECEIPT_BYTES = 32_768;
|
|
13
|
+
const COMPACT_JWS = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
14
|
+
/** Three segments; an empty signature (`alg: none`) is refused by its algorithm, not its shape. */
|
|
15
|
+
const JWS_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;
|
|
16
|
+
/** The one scope of version 1, and so the only one this release knows. */
|
|
17
|
+
const ACCEPTED_ROUNDS = 'accepted_rounds';
|
|
18
|
+
const SCOPE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
19
|
+
/** A 32-byte SHA-256 as base64url without padding: 43 characters, the last canonical. */
|
|
20
|
+
const COMMITMENT = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
|
|
21
|
+
const COMMITMENTS_MAX = 16;
|
|
22
|
+
const ROUNDS_MAX = 100_000;
|
|
23
|
+
const DOMAIN = 'sess.closing-commitment/v1/accepted_rounds';
|
|
24
|
+
const CAUSES = ['completed_by_owner', 'completed_by_ask_rule', 'final_expiry', 'revoked'];
|
|
25
|
+
/** The commitment over round receipts' exact bytes, in order (closing-receipt-v1 §3). */
|
|
26
|
+
export function closingCommitmentOf(receipts) {
|
|
27
|
+
const hash = createHash('sha256');
|
|
28
|
+
hash.update(Buffer.from(DOMAIN, 'utf8'));
|
|
29
|
+
hash.update(Buffer.from([0]));
|
|
30
|
+
const count = Buffer.alloc(4);
|
|
31
|
+
count.writeUInt32BE(receipts.length);
|
|
32
|
+
hash.update(count);
|
|
33
|
+
for (const receipt of receipts)
|
|
34
|
+
hash.update(createHash('sha256').update(receipt, 'ascii').digest());
|
|
35
|
+
return hash.digest('base64url');
|
|
36
|
+
}
|
|
37
|
+
function actorClassOf(cause) {
|
|
38
|
+
return cause === 'final_expiry' ? 'sess' : 'owner';
|
|
39
|
+
}
|
|
40
|
+
const TOP = [
|
|
41
|
+
'sess_closing_receipt',
|
|
42
|
+
'iss',
|
|
43
|
+
'aud',
|
|
44
|
+
'jti',
|
|
45
|
+
'iat',
|
|
46
|
+
'workspace_id',
|
|
47
|
+
'session_id',
|
|
48
|
+
'terminal',
|
|
49
|
+
'effective_end_at',
|
|
50
|
+
'recorded_at',
|
|
51
|
+
'issued_at',
|
|
52
|
+
'commitments',
|
|
53
|
+
];
|
|
54
|
+
const invalidClaims = () => verificationError('INVALID_CLAIMS', 'The closing receipt claims do not match the supported format.');
|
|
55
|
+
/** The commitments list's own rules; returns whether it carries a scope this release does not know. */
|
|
56
|
+
function unknownScope(value) {
|
|
57
|
+
if (!Array.isArray(value) || value.length < 1 || value.length > COMMITMENTS_MAX)
|
|
58
|
+
throw invalidClaims();
|
|
59
|
+
let previous = '';
|
|
60
|
+
let unknown = false;
|
|
61
|
+
let rounds = false;
|
|
62
|
+
for (const entry of value) {
|
|
63
|
+
if (!isRecord(entry) ||
|
|
64
|
+
!exactKeys(entry, ['scope', 'count', 'commitment']) ||
|
|
65
|
+
typeof entry.scope !== 'string' ||
|
|
66
|
+
!SCOPE.test(entry.scope) ||
|
|
67
|
+
entry.scope <= previous ||
|
|
68
|
+
!Number.isSafeInteger(entry.count) ||
|
|
69
|
+
entry.count < 0 ||
|
|
70
|
+
typeof entry.commitment !== 'string' ||
|
|
71
|
+
!COMMITMENT.test(entry.commitment))
|
|
72
|
+
throw invalidClaims();
|
|
73
|
+
previous = entry.scope;
|
|
74
|
+
if (entry.scope === ACCEPTED_ROUNDS) {
|
|
75
|
+
if (entry.count < 1 || entry.count > ROUNDS_MAX)
|
|
76
|
+
throw invalidClaims();
|
|
77
|
+
rounds = true;
|
|
78
|
+
}
|
|
79
|
+
else
|
|
80
|
+
unknown = true;
|
|
81
|
+
}
|
|
82
|
+
if (!rounds)
|
|
83
|
+
throw invalidClaims();
|
|
84
|
+
return unknown;
|
|
85
|
+
}
|
|
86
|
+
/** Strict claims (closing-receipt-v1 §6); the format version is decided by the caller first. */
|
|
87
|
+
function claimsOf(raw) {
|
|
88
|
+
if (!exactKeys(raw, TOP))
|
|
89
|
+
throw invalidClaims();
|
|
90
|
+
const newer = unknownScope(raw.commitments);
|
|
91
|
+
const t = raw.terminal;
|
|
92
|
+
const effective = checkedInstant(raw.effective_end_at);
|
|
93
|
+
const recorded = checkedInstant(raw.recorded_at);
|
|
94
|
+
const issued = checkedInstant(raw.issued_at);
|
|
95
|
+
if (![raw.iss, raw.aud, raw.jti, raw.workspace_id, raw.session_id].every(identifier) ||
|
|
96
|
+
raw.aud !== raw.workspace_id ||
|
|
97
|
+
!Number.isSafeInteger(raw.iat) ||
|
|
98
|
+
effective === undefined ||
|
|
99
|
+
recorded === undefined ||
|
|
100
|
+
issued === undefined ||
|
|
101
|
+
effective > recorded ||
|
|
102
|
+
recorded > issued ||
|
|
103
|
+
Math.floor(issued / 1000) !== raw.iat ||
|
|
104
|
+
!isRecord(t) ||
|
|
105
|
+
!exactKeys(t, ['event_id', 'cause', 'actor_class']) ||
|
|
106
|
+
typeof t.cause !== 'string' ||
|
|
107
|
+
!CAUSES.includes(t.cause) ||
|
|
108
|
+
t.actor_class !== actorClassOf(t.cause) ||
|
|
109
|
+
(t.cause === 'revoked' ? t.event_id !== null : !identifier(t.event_id)))
|
|
110
|
+
throw invalidClaims();
|
|
111
|
+
return { claims: raw, newer };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Verifies a Session's closing receipt (closing-receipt-v1 §6) under the keys you trust for the
|
|
115
|
+
* issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys. It returns the
|
|
116
|
+
* verified claims, deeply frozen, or throws a `SessError`; nothing is returned with a refusal.
|
|
117
|
+
*
|
|
118
|
+
* In order: a compact JWS of at most 8,192 bytes; `alg` exactly `EdDSA`; a `kid` you trust;
|
|
119
|
+
* `typ` exactly `sess-closing-receipt+jwt` (a round receipt is refused here with
|
|
120
|
+
* `UNSUPPORTED_TYPE`); the header exactly `alg`, `kid` and `typ`; the Ed25519 signature; the
|
|
121
|
+
* issuer and workspace; the format version; the strict claims, with no `exp`; RFC 8785 canonical
|
|
122
|
+
* JSON; then the optional Session, closure and round-set bindings. A format version above 1, or a
|
|
123
|
+
* commitment scope this release does not know, is newer: kind `receipt_newer`, code
|
|
124
|
+
* `RECEIPT_NEWER`, never a verification failure.
|
|
125
|
+
*
|
|
126
|
+
* A valid closing receipt says only that these are the final accepted rounds Sess signed for the
|
|
127
|
+
* Session, and how it ended; it is not a receipt for any one answer.
|
|
128
|
+
*/
|
|
129
|
+
export async function verifyClosingReceipt(input, options = {}) {
|
|
130
|
+
// Capture all caller-owned data before a resolver can yield control.
|
|
131
|
+
const receipt = input?.receipt;
|
|
132
|
+
if (typeof receipt !== 'string' || receipt.length > MAX_CLOSING_RECEIPT_BYTES || !JWS_SHAPE.test(receipt))
|
|
133
|
+
throw verificationError('MALFORMED_RECEIPT', 'The closing receipt is malformed or exceeds its 8,192-byte limit.');
|
|
134
|
+
const issuer = input.issuer;
|
|
135
|
+
const audience = input.audience;
|
|
136
|
+
if (!identifier(issuer) || !identifier(audience))
|
|
137
|
+
throw verificationError('VERIFICATION_CONTEXT_MISSING', 'A trusted issuer and expected resource workspace are required.');
|
|
138
|
+
const expected = input.expected === undefined ? {} : snapshotJson(input.expected);
|
|
139
|
+
const rounds = input.rounds === undefined ? undefined : snapshotJson(input.rounds);
|
|
140
|
+
if (!isRecord(expected) ||
|
|
141
|
+
!exactKeys(expected, ['sessionId', 'closureId'].filter((k) => Object.hasOwn(expected, k))) ||
|
|
142
|
+
(expected.sessionId !== undefined && !identifier(expected.sessionId)) ||
|
|
143
|
+
(expected.closureId !== undefined && !identifier(expected.closureId)) ||
|
|
144
|
+
(rounds !== undefined &&
|
|
145
|
+
(!Array.isArray(rounds) ||
|
|
146
|
+
rounds.length < 1 ||
|
|
147
|
+
rounds.length > ROUNDS_MAX ||
|
|
148
|
+
rounds.some((r) => typeof r !== 'string' || r.length > MAX_ROUND_RECEIPT_BYTES || !COMPACT_JWS.test(r)))))
|
|
149
|
+
throw verificationError('INVALID_VERIFICATION_INPUT', 'Expected bindings must be identifiers, and rounds one or more compact round receipts.');
|
|
150
|
+
const resolver = input.keyResolver;
|
|
151
|
+
const keys = input.keys === undefined ? undefined : validateKeySet(input.keys);
|
|
152
|
+
if ((keys === undefined) === (resolver === undefined) ||
|
|
153
|
+
(resolver !== undefined && typeof resolver !== 'function'))
|
|
154
|
+
throw verificationError('VERIFICATION_CONTEXT_MISSING', 'Provide exactly one trusted public key set or key resolver.');
|
|
155
|
+
const signal = options.signal;
|
|
156
|
+
if (signal?.aborted)
|
|
157
|
+
throw abortError(signal);
|
|
158
|
+
const parts = receipt.split('.');
|
|
159
|
+
let header;
|
|
160
|
+
const headerText = decodeSegment(parts[0]);
|
|
161
|
+
try {
|
|
162
|
+
header = JSON.parse(headerText);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
throw verificationError('MALFORMED_RECEIPT', 'The closing receipt protected header is not JSON.');
|
|
166
|
+
}
|
|
167
|
+
if (!isRecord(header))
|
|
168
|
+
throw verificationError('MALFORMED_RECEIPT', 'The closing receipt protected header is not JSON.');
|
|
169
|
+
if (header.alg !== 'EdDSA')
|
|
170
|
+
throw verificationError('UNSUPPORTED_ALGORITHM', 'The closing receipt must use the supported EdDSA algorithm.');
|
|
171
|
+
if (typeof header.kid !== 'string' || header.kid.length === 0)
|
|
172
|
+
throw verificationError('UNSUPPORTED_HEADER', 'The closing receipt names no signing key.');
|
|
173
|
+
// The whole header is checked before any key is looked up: an application's
|
|
174
|
+
// key resolver only ever sees a key ID of the receipt key grammar from a header of exactly
|
|
175
|
+
// {alg, kid, typ}, each a string and each once (six string tokens are then three names and
|
|
176
|
+
// three values).
|
|
177
|
+
const strings = headerText.match(/"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/g);
|
|
178
|
+
if (!exactKeys(header, ['alg', 'kid', 'typ']) ||
|
|
179
|
+
typeof header.typ !== 'string' ||
|
|
180
|
+
strings?.length !== 6 ||
|
|
181
|
+
!KID.test(header.kid))
|
|
182
|
+
throw verificationError('UNSUPPORTED_HEADER', 'The closing receipt protected header has missing or unsupported fields.');
|
|
183
|
+
const kid = header.kid;
|
|
184
|
+
const publicKey = await trustedKeyLookup(keys, resolver, issuer, signal)(kid);
|
|
185
|
+
if (!publicKey)
|
|
186
|
+
throw verificationError('UNKNOWN_KEY_ID', 'The closing receipt signing key is not in the trusted key set.');
|
|
187
|
+
// A round receipt (or any other format) offered as a closing receipt stops here: after the key,
|
|
188
|
+
// as the specification's first-failure order has it (closing-receipt-v1 §6: unknown_kid, then
|
|
189
|
+
// type) and Sess's own verifier does.
|
|
190
|
+
if (header.typ !== CLOSING_RECEIPT_TYP)
|
|
191
|
+
throw verificationError('UNSUPPORTED_TYPE', 'This is not a closing receipt.');
|
|
192
|
+
try {
|
|
193
|
+
const key = await waitWithSignal(importJWK({ ...publicKey, key_ops: ['verify'], ext: false }, 'EdDSA'), signal);
|
|
194
|
+
await waitWithSignal(compactVerify(receipt, key, { algorithms: ['EdDSA'] }), signal);
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
if (signal?.aborted)
|
|
198
|
+
throw abortError(signal);
|
|
199
|
+
throw verificationError('INVALID_SIGNATURE', 'The closing receipt signature did not verify with the trusted Ed25519 key.');
|
|
200
|
+
}
|
|
201
|
+
const payloadText = decodeSegment(parts[1]);
|
|
202
|
+
let parsed;
|
|
203
|
+
try {
|
|
204
|
+
parsed = JSON.parse(payloadText);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
throw verificationError('MALFORMED_RECEIPT', 'The closing receipt payload is not JSON.');
|
|
208
|
+
}
|
|
209
|
+
const raw = snapshotJson(parsed);
|
|
210
|
+
if (!isRecord(raw))
|
|
211
|
+
throw verificationError('MALFORMED_RECEIPT', 'The closing receipt payload is not a JSON object.');
|
|
212
|
+
if (raw.iss !== issuer)
|
|
213
|
+
throw verificationError('ISSUER_MISMATCH', 'The closing receipt issuer does not match the trusted issuer.');
|
|
214
|
+
if (raw.aud !== audience)
|
|
215
|
+
throw verificationError('AUDIENCE_MISMATCH', 'The closing receipt does not belong to the expected resource workspace.');
|
|
216
|
+
const version = raw.sess_closing_receipt;
|
|
217
|
+
// A later version may constrain what version 1 would release: nothing is released.
|
|
218
|
+
if (Number.isSafeInteger(version) && version > 1)
|
|
219
|
+
throw newerReceiptError();
|
|
220
|
+
if (version !== 1)
|
|
221
|
+
throw verificationError('UNSUPPORTED_RECEIPT_VERSION', 'The closing receipt format version is not supported (version 1 is).');
|
|
222
|
+
const { claims, newer } = claimsOf(raw);
|
|
223
|
+
if (canonicalJson(claims) !== payloadText)
|
|
224
|
+
throw verificationError('NON_CANONICAL_PAYLOAD', 'The signed closing receipt payload must be RFC 8785 canonical JSON.');
|
|
225
|
+
// Only after every other check: an unknown signed scope makes the whole receipt newer.
|
|
226
|
+
if (newer)
|
|
227
|
+
throw newerReceiptError();
|
|
228
|
+
if ((expected.sessionId !== undefined && claims.session_id !== expected.sessionId) ||
|
|
229
|
+
(expected.closureId !== undefined && claims.jti !== expected.closureId))
|
|
230
|
+
throw verificationError('RECORD_BINDING_MISMATCH', 'The closing receipt does not name the expected Session and closure.');
|
|
231
|
+
if (rounds !== undefined) {
|
|
232
|
+
const signed = claims.commitments.find((c) => c.scope === ACCEPTED_ROUNDS);
|
|
233
|
+
if (signed.count !== rounds.length || signed.commitment !== closingCommitmentOf(rounds))
|
|
234
|
+
throw verificationError('CLOSING_ROUNDS_MISMATCH', 'These round receipts are not exactly the accepted rounds the closing receipt signs.');
|
|
235
|
+
}
|
|
236
|
+
return deepFreeze(claims);
|
|
237
|
+
}
|
package/dist/receipts/index.d.ts
CHANGED
|
@@ -6,4 +6,6 @@ export type { ReceiptClaims, ReceiptClaimsV1, ReceiptClaimsV2, ReceiptPublicKey,
|
|
|
6
6
|
export type { DeepReadonly } from './json.js';
|
|
7
7
|
export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
|
|
8
8
|
export type { BundleContextField, BundleJwk, BundleRejection, DecisionBundle, DecisionBundleV1, DecisionBundleV2, DecisionBundleVerification, ExpectedBundleContext, VerifiedReceiptSummary, VerifyDecisionBundleOptions, } from './bundle.js';
|
|
9
|
-
export type { ReceiptResource, VerifyResponseInput, VerifiedResponse, VerificationRequestOptions, } from './resource.js';
|
|
9
|
+
export type { ReceiptResource, VerifyClosingInput, VerifiedClosing, VerifyResponseInput, VerifiedResponse, VerificationRequestOptions, } from './resource.js';
|
|
10
|
+
export { verifyClosingReceipt } from './closing.js';
|
|
11
|
+
export type { ClosingCause, ClosingReceiptClaims, VerifyClosingReceiptInput, VerifyClosingReceiptOptions, } from './closing.js';
|
package/dist/receipts/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
export { verifyDecisionReceipt, verifyRendererIdentities } from './verify.js';
|
|
2
2
|
export { BUNDLED_RENDERER_IDENTITIES, BUNDLED_RENDERER_LIST, newerRendererList } from './renderers.js';
|
|
3
3
|
export { verifyDecisionBundle, BUNDLE_LIMITS } from './bundle.js';
|
|
4
|
+
export { verifyClosingReceipt } from './closing.js';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { AcceptedResponse, ApiResult, InteractiveSurfaceRevision, Session, SurfaceRevision, VersionedResult } from '../types.js';
|
|
1
|
+
import type { AcceptedResponse, ApiResult, InteractiveSurfaceRevision, Session, SessionClosing, SessionEvents, SurfaceRevision, VersionedResult } from '../types.js';
|
|
2
|
+
import { type ClosingReceiptClaims } from './closing.js';
|
|
2
3
|
import { type DeepReadonly } from './json.js';
|
|
3
4
|
import { type ReceiptClaims } from './verify.js';
|
|
4
5
|
export interface VerificationRequestOptions {
|
|
@@ -18,6 +19,18 @@ interface Context {
|
|
|
18
19
|
publicGet: (path: string, options: VerificationRequestOptions & {
|
|
19
20
|
maxResponseBytes: number;
|
|
20
21
|
}) => Promise<ApiResult<unknown>>;
|
|
22
|
+
/** The Session's Event log, read for closing receipt verification. */
|
|
23
|
+
listEvents?: (id: string, options: VerificationRequestOptions) => Promise<ApiResult<SessionEvents>>;
|
|
24
|
+
}
|
|
25
|
+
export interface VerifyClosingInput {
|
|
26
|
+
sessionId: string;
|
|
27
|
+
/** `closing` from `sessions.listEvents()`. */
|
|
28
|
+
closing: SessionClosing;
|
|
29
|
+
expectedWorkspaceId?: string;
|
|
30
|
+
}
|
|
31
|
+
export interface VerifiedClosing {
|
|
32
|
+
claims: DeepReadonly<ClosingReceiptClaims>;
|
|
33
|
+
closing: DeepReadonly<SessionClosing>;
|
|
21
34
|
}
|
|
22
35
|
export interface VerifyResponseInput {
|
|
23
36
|
sessionId: string;
|
|
@@ -32,6 +45,14 @@ export interface VerifiedResponse {
|
|
|
32
45
|
export interface ReceiptResource {
|
|
33
46
|
/** Full receipt verification with authorized current context and exact immutable revision. */
|
|
34
47
|
verifyResponse(input: VerifyResponseInput, options?: VerificationRequestOptions): Promise<DeepReadonly<VerifiedResponse>>;
|
|
48
|
+
/**
|
|
49
|
+
* Verifies a Session's closing receipt against the authorized Event log: the supplied `closing`
|
|
50
|
+
* must be the one Sess serves now, its receipt must verify under the issuer's published keys
|
|
51
|
+
* (closing-receipt-v1), name this Session, closure, cause, end and count, and commit to exactly
|
|
52
|
+
* the served accepted answers' receipts, in order. Each answer's own receipt is verified with
|
|
53
|
+
* `verifyResponse`.
|
|
54
|
+
*/
|
|
55
|
+
verifyClosing(input: VerifyClosingInput, options?: VerificationRequestOptions): Promise<DeepReadonly<VerifiedClosing>>;
|
|
35
56
|
}
|
|
36
57
|
/** Internal bridge: all HTTP is supplied by the client's ordinary bounded transport. */
|
|
37
58
|
export declare function createReceiptResource(context: Context): ReceiptResource;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { SessError } from '../errors.js';
|
|
2
2
|
import { isInteractiveSurface } from '../types.js';
|
|
3
|
+
import { verifyClosingReceipt } from './closing.js';
|
|
3
4
|
import { ReceiptKeyCache } from './key-cache.js';
|
|
4
5
|
import { abortError, canonicalJson, deepFreeze, snapshotJson, verificationError, waitWithSignal, } from './json.js';
|
|
5
6
|
import { BUNDLED_RENDERER_IDENTITIES, MAX_RENDERER_IDENTITIES_BYTES, RENDERER_IDENTITIES_PATH, } from './renderers.js';
|
|
@@ -18,6 +19,43 @@ function namedRenderer(receipt) {
|
|
|
18
19
|
return undefined;
|
|
19
20
|
}
|
|
20
21
|
}
|
|
22
|
+
/** One operation's overall deadline and cancellation, as each verification method uses. */
|
|
23
|
+
function deadline(budget, options) {
|
|
24
|
+
if (!Number.isSafeInteger(budget) || budget <= 0 || budget > 2_147_483_647) {
|
|
25
|
+
throw new SessError('configuration', 'Receipt verification requires a finite positive operation timeout.');
|
|
26
|
+
}
|
|
27
|
+
const { timeoutMs, maxRetries, signal: originalSignal } = options;
|
|
28
|
+
if (originalSignal?.aborted)
|
|
29
|
+
throw abortError(originalSignal);
|
|
30
|
+
const controller = new AbortController();
|
|
31
|
+
const abort = () => controller.abort(originalSignal?.reason);
|
|
32
|
+
originalSignal?.addEventListener('abort', abort, { once: true });
|
|
33
|
+
const started = performance.now();
|
|
34
|
+
const expired = () => controller.abort(new SessError('timeout', 'Receipt verification exceeded its overall deadline.'));
|
|
35
|
+
const timer = setTimeout(expired, budget);
|
|
36
|
+
return {
|
|
37
|
+
signal: controller.signal,
|
|
38
|
+
requestOptions() {
|
|
39
|
+
if (controller.signal.aborted)
|
|
40
|
+
throw abortError(controller.signal);
|
|
41
|
+
const remaining = Math.floor(budget - (performance.now() - started));
|
|
42
|
+
if (remaining <= 0) {
|
|
43
|
+
expired();
|
|
44
|
+
throw abortError(controller.signal);
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
signal: controller.signal,
|
|
48
|
+
operationTimeoutMs: remaining,
|
|
49
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
50
|
+
...(maxRetries !== undefined ? { maxRetries } : {}),
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
done() {
|
|
54
|
+
clearTimeout(timer);
|
|
55
|
+
originalSignal?.removeEventListener('abort', abort);
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
}
|
|
21
59
|
/** Internal bridge: all HTTP is supplied by the client's ordinary bounded transport. */
|
|
22
60
|
export function createReceiptResource(context) {
|
|
23
61
|
// Copy configuration/callbacks; mutation of an application-owned config object has no effect.
|
|
@@ -27,6 +65,7 @@ export function createReceiptResource(context) {
|
|
|
27
65
|
const retrieve = context.retrieveSession;
|
|
28
66
|
const surfaceRead = context.retrieveSurface;
|
|
29
67
|
const publicGet = context.publicGet;
|
|
68
|
+
const eventsRead = context.listEvents;
|
|
30
69
|
const keyPath = '/.well-known/sess-receipt-keys.json';
|
|
31
70
|
const cache = new ReceiptKeyCache({
|
|
32
71
|
issuer,
|
|
@@ -144,5 +183,57 @@ export function createReceiptResource(context) {
|
|
|
144
183
|
originalSignal?.removeEventListener('abort', abort);
|
|
145
184
|
}
|
|
146
185
|
},
|
|
186
|
+
async verifyClosing(input, options = {}) {
|
|
187
|
+
const sessionId = input?.sessionId;
|
|
188
|
+
const supplied = input?.closing == null ? undefined : snapshotJson(input.closing);
|
|
189
|
+
const requestedWorkspace = input?.expectedWorkspaceId;
|
|
190
|
+
const { timeoutMs, maxRetries } = options;
|
|
191
|
+
if (typeof eventsRead !== 'function')
|
|
192
|
+
throw new SessError('configuration', 'Closing receipt verification needs the Session Event log.');
|
|
193
|
+
if (supplied === undefined || typeof supplied.receipt !== 'string')
|
|
194
|
+
throw verificationError('CLOSING_RECEIPT_UNAVAILABLE', 'This Session has no closing receipt yet: it has not ended with an accepted answer, or its receipt is not signed yet.');
|
|
195
|
+
if (requestedWorkspace && configuredWorkspace && requestedWorkspace !== configuredWorkspace)
|
|
196
|
+
throw verificationError('AUDIENCE_MISMATCH', 'The supplied workspace differs from this client’s trusted workspace.');
|
|
197
|
+
const run = deadline(options.operationTimeoutMs ?? defaultBudget, options);
|
|
198
|
+
try {
|
|
199
|
+
const read = snapshotJson(await waitWithSignal(eventsRead(sessionId, run.requestOptions()), run.signal));
|
|
200
|
+
const trustedWorkspace = requestedWorkspace ?? configuredWorkspace ?? read.meta.workspaceId;
|
|
201
|
+
if (typeof trustedWorkspace !== 'string' || trustedWorkspace.length === 0)
|
|
202
|
+
throw verificationError('VERIFICATION_CONTEXT_MISSING', 'Provide expectedWorkspaceId or use a runtime that returns authenticated Sess-Workspace-Id context.');
|
|
203
|
+
if (read.meta.workspaceId !== undefined && read.meta.workspaceId !== trustedWorkspace)
|
|
204
|
+
throw verificationError('AUDIENCE_MISMATCH', 'The authorized resource belongs to a different workspace.');
|
|
205
|
+
const served = read.data.closing;
|
|
206
|
+
if (read.data.id !== sessionId ||
|
|
207
|
+
served === undefined ||
|
|
208
|
+
canonicalJson(served) !== canonicalJson(supplied))
|
|
209
|
+
throw verificationError('RECORD_BINDING_MISMATCH', 'The supplied closing receipt is not the one the authorized Event log carries.');
|
|
210
|
+
const rounds = read.data.events
|
|
211
|
+
.filter((event) => event.type === 'response.accepted')
|
|
212
|
+
.map((event) => event.receipt);
|
|
213
|
+
if (rounds.some((receipt) => typeof receipt !== 'string'))
|
|
214
|
+
throw verificationError('CLOSING_ROUNDS_MISMATCH', 'An accepted answer in the Event log has no receipt, so it cannot match the closing receipt.');
|
|
215
|
+
const claims = await verifyClosingReceipt({
|
|
216
|
+
receipt: served.receipt,
|
|
217
|
+
issuer,
|
|
218
|
+
audience: trustedWorkspace,
|
|
219
|
+
expected: { sessionId, closureId: served.closure_id },
|
|
220
|
+
rounds: rounds,
|
|
221
|
+
keyResolver: (resolverContext) => cache.resolve({
|
|
222
|
+
...resolverContext,
|
|
223
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
224
|
+
...(maxRetries !== undefined ? { maxRetries } : {}),
|
|
225
|
+
}),
|
|
226
|
+
}, { signal: run.signal });
|
|
227
|
+
// The facts served beside the receipt are the ones it signs.
|
|
228
|
+
if (claims.terminal.cause !== served.cause ||
|
|
229
|
+
claims.terminal.event_id !== served.terminal_event_id ||
|
|
230
|
+
claims.commitments.find((c) => c.scope === 'accepted_rounds')?.count !== served.accepted_rounds)
|
|
231
|
+
throw verificationError('RECORD_BINDING_MISMATCH', 'The closing receipt does not sign the cause, end and count served beside it.');
|
|
232
|
+
return deepFreeze({ claims, closing: served });
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
run.done();
|
|
236
|
+
}
|
|
237
|
+
},
|
|
147
238
|
});
|
|
148
239
|
}
|
|
@@ -114,8 +114,10 @@ export interface VerifyDecisionReceiptOptions {
|
|
|
114
114
|
issuedAtToleranceSeconds?: number;
|
|
115
115
|
signal?: AbortSignal;
|
|
116
116
|
}
|
|
117
|
+
export declare function identifier(value: unknown): value is string;
|
|
117
118
|
/** Validates and copies the whole set, not merely the key selected by the token. */
|
|
118
119
|
export declare function validateKeySet(raw: unknown): ReceiptKeySet;
|
|
120
|
+
export declare function decodeSegment(segment: string): string;
|
|
119
121
|
/**
|
|
120
122
|
* Fully verifies a receipt and its exact accepted record. Explicit keys make this function
|
|
121
123
|
* entirely offline. A valid receipt attests the accepted record, not business authority.
|
|
@@ -133,6 +135,8 @@ export declare function validateKeySet(raw: unknown): ReceiptKeySet;
|
|
|
133
135
|
* `receipt_newer` and code `RECEIPT_NEWER`, never as a verification failure; nothing is returned.
|
|
134
136
|
*/
|
|
135
137
|
export declare function verifyDecisionReceipt(input: VerifyDecisionReceiptInput, options?: VerifyDecisionReceiptOptions): Promise<DeepReadonly<ReceiptClaims>>;
|
|
138
|
+
/** Resolves a kid to a trusted key: from the explicit set, or the trusted resolver (validated). */
|
|
139
|
+
export declare function trustedKeyLookup(keys: ReceiptKeySet | undefined, resolver: ReceiptKeyResolver | undefined, issuer: string, signal: AbortSignal | undefined): (kid: string) => Promise<ReceiptPublicKey | undefined>;
|
|
136
140
|
/**
|
|
137
141
|
* Verifies an issuer's signed renderer-identity list (Decision 0009 Amendment 13) under the keys
|
|
138
142
|
* you trust for that issuer: exactly one of `keys` or `keyResolver`. Offline with explicit keys.
|
package/dist/receipts/verify.js
CHANGED
|
@@ -14,7 +14,7 @@ const DIGEST = /^sha256:[0-9a-f]{64}$/;
|
|
|
14
14
|
const RECEIPT_TYP_V1 = 'sess-receipt+jwt';
|
|
15
15
|
/** Protected `typ` of a receipt v2 (receipt-v2); it names version 2 only. */
|
|
16
16
|
const RECEIPT_TYP_V2 = 'sess-receipt-2+jwt';
|
|
17
|
-
function identifier(value) {
|
|
17
|
+
export function identifier(value) {
|
|
18
18
|
return (typeof value === 'string' &&
|
|
19
19
|
value.length > 0 &&
|
|
20
20
|
value.length <= 200 &&
|
|
@@ -56,7 +56,7 @@ export function validateKeySet(raw) {
|
|
|
56
56
|
}
|
|
57
57
|
return deepFreeze(value);
|
|
58
58
|
}
|
|
59
|
-
function decodeSegment(segment) {
|
|
59
|
+
export function decodeSegment(segment) {
|
|
60
60
|
const bytes = Buffer.from(segment, 'base64url');
|
|
61
61
|
if (bytes.toString('base64url') !== segment)
|
|
62
62
|
throw verificationError('MALFORMED_RECEIPT', 'The receipt is not canonical base64url.');
|
|
@@ -363,7 +363,7 @@ function checkRevisionEnvelope(claims, supplied) {
|
|
|
363
363
|
throw verificationError('REVISION_ENVELOPE_MISMATCH', 'The revision envelope names another Session, revision, Surface or renderer.');
|
|
364
364
|
}
|
|
365
365
|
/** Resolves a kid to a trusted key: from the explicit set, or the trusted resolver (validated). */
|
|
366
|
-
function trustedKeyLookup(keys, resolver, issuer, signal) {
|
|
366
|
+
export function trustedKeyLookup(keys, resolver, issuer, signal) {
|
|
367
367
|
return async (kid) => {
|
|
368
368
|
let trusted = keys;
|
|
369
369
|
if (!trusted && resolver) {
|