@sess.si/sdk 0.1.0-rc.8 → 0.1.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 (139) hide show
  1. package/CHANGELOG.md +66 -9
  2. package/NOTICE +1 -1
  3. package/README.md +92 -16
  4. package/dist/ask.d.ts +0 -1
  5. package/dist/ask.js +0 -1
  6. package/dist/cli/main.d.ts +0 -1
  7. package/dist/cli/main.js +0 -1
  8. package/dist/cli/verify.d.ts +0 -1
  9. package/dist/cli/verify.js +0 -1
  10. package/dist/client.d.ts +0 -1
  11. package/dist/client.js +0 -1
  12. package/dist/commerce/builders.d.ts +99 -0
  13. package/dist/commerce/builders.js +208 -0
  14. package/dist/commerce/currency.d.ts +4 -0
  15. package/dist/commerce/currency.js +25 -0
  16. package/dist/commerce/items.d.ts +119 -0
  17. package/dist/commerce/items.js +280 -0
  18. package/dist/commerce/lint.d.ts +16 -0
  19. package/dist/commerce/lint.js +56 -0
  20. package/dist/errors.d.ts +5 -2
  21. package/dist/errors.js +15 -25
  22. package/dist/generated/openapi.d.ts +12 -13
  23. package/dist/generated/openapi.js +0 -1
  24. package/dist/index.d.ts +6 -1
  25. package/dist/index.js +3 -1
  26. package/dist/internal/decode.d.ts +0 -1
  27. package/dist/internal/decode.js +9 -2
  28. package/dist/internal/json.d.ts +0 -1
  29. package/dist/internal/json.js +0 -1
  30. package/dist/internal/time.d.ts +0 -1
  31. package/dist/internal/time.js +0 -1
  32. package/dist/internal/version.d.ts +2 -0
  33. package/dist/internal/version.js +2 -0
  34. package/dist/polling.d.ts +0 -1
  35. package/dist/polling.js +0 -1
  36. package/dist/qr/encoder.d.ts +0 -1
  37. package/dist/qr/encoder.js +0 -1
  38. package/dist/qr/index.d.ts +0 -1
  39. package/dist/qr/index.js +0 -1
  40. package/dist/receipts/bundle.d.ts +0 -1
  41. package/dist/receipts/bundle.js +0 -1
  42. package/dist/receipts/index.d.ts +0 -1
  43. package/dist/receipts/index.js +0 -1
  44. package/dist/receipts/json.d.ts +0 -1
  45. package/dist/receipts/json.js +0 -1
  46. package/dist/receipts/key-cache.d.ts +0 -1
  47. package/dist/receipts/key-cache.js +0 -1
  48. package/dist/receipts/renderers.d.ts +0 -1
  49. package/dist/receipts/renderers.js +1 -2
  50. package/dist/receipts/resource.d.ts +0 -1
  51. package/dist/receipts/resource.js +0 -1
  52. package/dist/receipts/verify.d.ts +0 -1
  53. package/dist/receipts/verify.js +0 -1
  54. package/dist/sessions.d.ts +0 -1
  55. package/dist/sessions.js +0 -1
  56. package/dist/transport.d.ts +0 -1
  57. package/dist/transport.js +35 -5
  58. package/dist/types.d.ts +56 -2
  59. package/dist/types.js +0 -1
  60. package/dist/webhook-resource.d.ts +0 -1
  61. package/dist/webhook-resource.js +0 -1
  62. package/dist/webhooks/index.d.ts +0 -1
  63. package/dist/webhooks/index.js +0 -1
  64. package/package.json +8 -3
  65. package/dist/ask.d.ts.map +0 -1
  66. package/dist/ask.js.map +0 -1
  67. package/dist/cli/main.d.ts.map +0 -1
  68. package/dist/cli/main.js.map +0 -1
  69. package/dist/cli/verify.d.ts.map +0 -1
  70. package/dist/cli/verify.js.map +0 -1
  71. package/dist/client.d.ts.map +0 -1
  72. package/dist/client.js.map +0 -1
  73. package/dist/errors.d.ts.map +0 -1
  74. package/dist/errors.js.map +0 -1
  75. package/dist/generated/openapi.d.ts.map +0 -1
  76. package/dist/generated/openapi.js.map +0 -1
  77. package/dist/index.d.ts.map +0 -1
  78. package/dist/index.js.map +0 -1
  79. package/dist/internal/decode.d.ts.map +0 -1
  80. package/dist/internal/decode.js.map +0 -1
  81. package/dist/internal/json.d.ts.map +0 -1
  82. package/dist/internal/json.js.map +0 -1
  83. package/dist/internal/time.d.ts.map +0 -1
  84. package/dist/internal/time.js.map +0 -1
  85. package/dist/polling.d.ts.map +0 -1
  86. package/dist/polling.js.map +0 -1
  87. package/dist/qr/encoder.d.ts.map +0 -1
  88. package/dist/qr/encoder.js.map +0 -1
  89. package/dist/qr/index.d.ts.map +0 -1
  90. package/dist/qr/index.js.map +0 -1
  91. package/dist/receipts/bundle.d.ts.map +0 -1
  92. package/dist/receipts/bundle.js.map +0 -1
  93. package/dist/receipts/index.d.ts.map +0 -1
  94. package/dist/receipts/index.js.map +0 -1
  95. package/dist/receipts/json.d.ts.map +0 -1
  96. package/dist/receipts/json.js.map +0 -1
  97. package/dist/receipts/key-cache.d.ts.map +0 -1
  98. package/dist/receipts/key-cache.js.map +0 -1
  99. package/dist/receipts/renderers.d.ts.map +0 -1
  100. package/dist/receipts/renderers.js.map +0 -1
  101. package/dist/receipts/resource.d.ts.map +0 -1
  102. package/dist/receipts/resource.js.map +0 -1
  103. package/dist/receipts/verify.d.ts.map +0 -1
  104. package/dist/receipts/verify.js.map +0 -1
  105. package/dist/sessions.d.ts.map +0 -1
  106. package/dist/sessions.js.map +0 -1
  107. package/dist/transport.d.ts.map +0 -1
  108. package/dist/transport.js.map +0 -1
  109. package/dist/types.d.ts.map +0 -1
  110. package/dist/types.js.map +0 -1
  111. package/dist/webhook-resource.d.ts.map +0 -1
  112. package/dist/webhook-resource.js.map +0 -1
  113. package/dist/webhooks/index.d.ts.map +0 -1
  114. package/dist/webhooks/index.js.map +0 -1
  115. package/src/ask.ts +0 -683
  116. package/src/cli/main.ts +0 -8
  117. package/src/cli/verify.ts +0 -349
  118. package/src/client.ts +0 -55
  119. package/src/errors.ts +0 -127
  120. package/src/generated/openapi.ts +0 -8586
  121. package/src/index.ts +0 -5
  122. package/src/internal/decode.ts +0 -348
  123. package/src/internal/json.ts +0 -64
  124. package/src/internal/time.ts +0 -85
  125. package/src/polling.ts +0 -173
  126. package/src/qr/encoder.ts +0 -345
  127. package/src/qr/index.ts +0 -203
  128. package/src/receipts/bundle.ts +0 -547
  129. package/src/receipts/index.ts +0 -29
  130. package/src/receipts/json.ts +0 -168
  131. package/src/receipts/key-cache.ts +0 -143
  132. package/src/receipts/renderers.ts +0 -220
  133. package/src/receipts/resource.ts +0 -264
  134. package/src/receipts/verify.ts +0 -554
  135. package/src/sessions.ts +0 -238
  136. package/src/transport.ts +0 -566
  137. package/src/types.ts +0 -219
  138. package/src/webhook-resource.ts +0 -81
  139. package/src/webhooks/index.ts +0 -246
@@ -1,168 +0,0 @@
1
- import canonicalize from 'canonicalize';
2
- import { createHash } from 'node:crypto';
3
- import { SessError } from '../errors.js';
4
-
5
- /** JSON-shaped values returned by a verifier are copies, protected at every depth. */
6
- export type DeepReadonly<T> = T extends readonly (infer U)[]
7
- ? readonly DeepReadonly<U>[]
8
- : T extends object
9
- ? { readonly [P in keyof T]: DeepReadonly<T[P]> }
10
- : T;
11
-
12
- export function verificationError(code: string, message: string): SessError {
13
- return new SessError('receipt_verification', message, { code });
14
- }
15
-
16
- export function isRecord(value: unknown): value is Record<string, unknown> {
17
- return value !== null && typeof value === 'object' && !Array.isArray(value);
18
- }
19
-
20
- export function wellFormedUnicode(value: string): boolean {
21
- for (let index = 0; index < value.length; index += 1) {
22
- const code = value.charCodeAt(index);
23
- if (code >= 0xd800 && code <= 0xdbff) {
24
- const next = value.charCodeAt(++index);
25
- if (!(next >= 0xdc00 && next <= 0xdfff)) return false;
26
- } else if (code >= 0xdc00 && code <= 0xdfff) return false;
27
- }
28
- return true;
29
- }
30
-
31
- export function exactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
32
- return Object.keys(value).length === keys.length && keys.every((key) => Object.hasOwn(value, key));
33
- }
34
-
35
- /**
36
- * Copy data without invoking accessors/toJSON or coercing non-JSON business values.
37
- * This helper intentionally does not freeze data owned by the application.
38
- */
39
- export function snapshotJson<T>(input: T): T {
40
- const ancestors = new Set<object>();
41
- let remaining = 200_000;
42
- const visit = (value: unknown, depth: number): unknown => {
43
- if (--remaining < 0 || depth > 128) {
44
- throw verificationError('INVALID_JSON', 'Verification data exceeds the supported JSON complexity.');
45
- }
46
- if (value === null || typeof value === 'boolean') return value;
47
- if (typeof value === 'string') {
48
- if (!wellFormedUnicode(value))
49
- throw verificationError('INVALID_JSON', 'Verification data must contain well-formed Unicode.');
50
- return value;
51
- }
52
- if (typeof value === 'number' && Number.isFinite(value)) return value;
53
- if (typeof value !== 'object' || value === null) {
54
- throw verificationError('INVALID_JSON', 'Verification data must be JSON without coercion.');
55
- }
56
- if (ancestors.has(value) || Object.getOwnPropertySymbols(value).length !== 0) {
57
- throw verificationError('INVALID_JSON', 'Verification data must be acyclic JSON.');
58
- }
59
- const array = Array.isArray(value);
60
- const prototype = Object.getPrototypeOf(value);
61
- if (array && prototype !== Array.prototype) {
62
- throw verificationError('INVALID_JSON', 'Verification arrays must have ordinary JSON array semantics.');
63
- }
64
- if (!array && prototype !== Object.prototype && prototype !== null) {
65
- throw verificationError('INVALID_JSON', 'Verification data must contain only plain JSON objects.');
66
- }
67
- ancestors.add(value);
68
- try {
69
- if (array) {
70
- const descriptors = Object.getOwnPropertyDescriptors(value);
71
- if (Object.keys(descriptors).some((key) => key !== 'length' && !/^(?:0|[1-9][0-9]*)$/.test(key))) {
72
- throw verificationError('INVALID_JSON', 'Verification arrays cannot have named properties.');
73
- }
74
- return Array.from({ length: value.length }, (_, index) => {
75
- const descriptor = descriptors[String(index)];
76
- if (!descriptor || !('value' in descriptor)) {
77
- throw verificationError(
78
- 'INVALID_JSON',
79
- 'Verification arrays cannot be sparse or contain accessors.',
80
- );
81
- }
82
- return visit(descriptor.value, depth + 1);
83
- });
84
- }
85
- const result: Record<string, unknown> = {};
86
- for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
87
- if (!wellFormedUnicode(key) || !descriptor.enumerable || !('value' in descriptor)) {
88
- throw verificationError(
89
- 'INVALID_JSON',
90
- 'Verification objects cannot contain accessors or hidden properties.',
91
- );
92
- }
93
- Object.defineProperty(result, key, {
94
- value: visit(descriptor.value, depth + 1),
95
- enumerable: true,
96
- configurable: true,
97
- writable: true,
98
- });
99
- }
100
- return result;
101
- } finally {
102
- ancestors.delete(value);
103
- }
104
- };
105
- return visit(input, 0) as T;
106
- }
107
-
108
- export function deepFreeze<T>(value: T): DeepReadonly<T> {
109
- if (value !== null && typeof value === 'object') {
110
- for (const child of Object.values(value)) deepFreeze(child);
111
- Object.freeze(value);
112
- }
113
- return value as DeepReadonly<T>;
114
- }
115
-
116
- export function canonicalJson(value: unknown): string {
117
- try {
118
- const result = canonicalize(value);
119
- if (result !== undefined) return result;
120
- } catch {
121
- // Dependencies' exceptions may contain caller data; expose only a fixed explanation.
122
- }
123
- throw verificationError('INVALID_JSON', 'Verification data is not canonicalizable JSON.');
124
- }
125
-
126
- export function jsonDigest(value: unknown): string {
127
- return `sha256:${createHash('sha256').update(canonicalJson(value), 'utf8').digest('hex')}`;
128
- }
129
-
130
- export function checkedInstant(value: unknown): number | undefined {
131
- if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(value))
132
- return undefined;
133
- const millis = Date.parse(value);
134
- return Number.isFinite(millis) && new Date(millis).toISOString() === value ? millis : undefined;
135
- }
136
-
137
- export function abortError(signal: AbortSignal): SessError {
138
- return signal.reason instanceof SessError && signal.reason.kind === 'timeout'
139
- ? new SessError('timeout', 'Verification exceeded its deadline.')
140
- : new SessError('aborted', 'Verification was cancelled.');
141
- }
142
-
143
- /** Race a promise without cancelling shared work; always remove this waiter's listener. */
144
- export async function waitWithSignal<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
145
- if (!signal) return promise;
146
- if (signal.aborted) {
147
- void promise.catch(() => {});
148
- throw abortError(signal);
149
- }
150
- return new Promise<T>((resolve, reject) => {
151
- const aborted = () => {
152
- cleanup();
153
- reject(abortError(signal));
154
- };
155
- const cleanup = () => signal.removeEventListener('abort', aborted);
156
- signal.addEventListener('abort', aborted, { once: true });
157
- promise.then(
158
- (result) => {
159
- cleanup();
160
- resolve(result);
161
- },
162
- (error: unknown) => {
163
- cleanup();
164
- reject(error);
165
- },
166
- );
167
- });
168
- }
@@ -1,143 +0,0 @@
1
- import { SessError } from '../errors.js';
2
- import { abortError, verificationError, waitWithSignal } from './json.js';
3
- import { validateKeySet, type ReceiptKeySet } from './verify.js';
4
-
5
- export interface ReceiptKeyCacheOptions {
6
- issuer: string;
7
- /** Identifies the configured trusted source. It is never derived from a receipt. */
8
- keySource: string;
9
- load: (options: {
10
- signal: AbortSignal;
11
- operationTimeoutMs: number;
12
- timeoutMs?: number;
13
- maxRetries?: number;
14
- }) => Promise<unknown>;
15
- ttlMs?: number;
16
- refreshCooldownMs?: number;
17
- requestTimeoutMs?: number;
18
- }
19
-
20
- interface Flight {
21
- controller: AbortController;
22
- promise: Promise<ReceiptKeySet>;
23
- waiters: number;
24
- }
25
-
26
- /** One bounded, issuer/source-scoped cache per client; no global `kid` cache. */
27
- export class ReceiptKeyCache {
28
- readonly #issuer: string;
29
- readonly #keySource: string;
30
- readonly #load: ReceiptKeyCacheOptions['load'];
31
- readonly #ttl: number;
32
- readonly #cooldown: number;
33
- readonly #requestTimeout: number;
34
- #keys?: ReceiptKeySet;
35
- #loadedAt = 0;
36
- #attemptedAt = -Infinity;
37
- #lastFailure?: unknown;
38
- #flight?: Flight;
39
-
40
- constructor(options: ReceiptKeyCacheOptions) {
41
- this.#issuer = options.issuer;
42
- this.#keySource = options.keySource;
43
- this.#load = options.load;
44
- this.#ttl = options.ttlMs ?? 5 * 60_000;
45
- this.#cooldown = options.refreshCooldownMs ?? 10_000;
46
- this.#requestTimeout = options.requestTimeoutMs ?? 5_000;
47
- if (
48
- !this.#issuer ||
49
- !this.#keySource ||
50
- typeof this.#load !== 'function' ||
51
- !Number.isFinite(this.#ttl) ||
52
- this.#ttl < 1 ||
53
- this.#ttl > 5 * 60_000 ||
54
- !Number.isFinite(this.#cooldown) ||
55
- this.#cooldown < 1 ||
56
- this.#cooldown > 60_000 ||
57
- !Number.isFinite(this.#requestTimeout) ||
58
- this.#requestTimeout < 1 ||
59
- this.#requestTimeout > 10_000
60
- ) {
61
- throw new SessError('configuration', 'Invalid receipt key-cache configuration.');
62
- }
63
- }
64
-
65
- async resolve(context: {
66
- kid: string;
67
- issuer: string;
68
- signal?: AbortSignal;
69
- timeoutMs?: number;
70
- maxRetries?: number;
71
- }): Promise<ReceiptKeySet> {
72
- if (context.issuer !== this.#issuer) {
73
- throw verificationError('ISSUER_MISMATCH', 'The key cache belongs to a different trusted issuer.');
74
- }
75
- if (context.signal?.aborted) throw abortError(context.signal);
76
- const fresh = this.#keys !== undefined && Date.now() - this.#loadedAt < this.#ttl;
77
- if (fresh && this.#keys?.keys.some((key) => key.kid === context.kid)) return this.#keys;
78
- if (this.#flight) return this.#join(this.#flight, context.signal);
79
- // Every unknown key can trigger at most one shared refresh in this cooldown, including
80
- // failures. Cold-start misses use the initial fetch, never an immediate redundant fetch.
81
- if (Date.now() - this.#attemptedAt < this.#cooldown) {
82
- if (fresh && this.#keys) return this.#keys;
83
- if (this.#lastFailure instanceof SessError) throw this.#lastFailure;
84
- throw verificationError(
85
- 'KEY_FETCH_COOLDOWN',
86
- 'Receipt-key refresh is cooling down after a recent attempt.',
87
- );
88
- }
89
- return this.#join(this.#start(context), context.signal);
90
- }
91
-
92
- #start(options: { timeoutMs?: number; maxRetries?: number }): Flight {
93
- const controller = new AbortController();
94
- this.#attemptedAt = Date.now();
95
- const timer = setTimeout(
96
- () => controller.abort(new SessError('timeout', 'Receipt-key retrieval exceeded its deadline.')),
97
- this.#requestTimeout,
98
- );
99
- const flight: Flight = { controller, waiters: 0, promise: Promise.resolve({ keys: [] }) };
100
- const load = Promise.resolve().then(() =>
101
- this.#load({
102
- signal: controller.signal,
103
- operationTimeoutMs: this.#requestTimeout,
104
- ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
105
- ...(options.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),
106
- }),
107
- );
108
- flight.promise = waitWithSignal(load, controller.signal)
109
- .then((raw) => {
110
- const keys = validateKeySet(raw);
111
- this.#keys = keys;
112
- this.#loadedAt = Date.now();
113
- this.#lastFailure = undefined;
114
- return keys;
115
- })
116
- .catch((error: unknown) => {
117
- if (this.#flight === flight) this.#lastFailure = error;
118
- throw error;
119
- })
120
- .finally(() => {
121
- clearTimeout(timer);
122
- if (this.#flight === flight) this.#flight = undefined;
123
- });
124
- this.#flight = flight;
125
- return flight;
126
- }
127
-
128
- async #join(flight: Flight, signal?: AbortSignal): Promise<ReceiptKeySet> {
129
- flight.waiters += 1;
130
- try {
131
- return await waitWithSignal(flight.promise, signal);
132
- } finally {
133
- flight.waiters -= 1;
134
- // One cancelled caller must not cancel another caller's shared fetch. When everyone
135
- // leaves, release the underlying transport and its timer promptly.
136
- if (flight.waiters === 0 && this.#flight === flight) {
137
- this.#flight = undefined;
138
- this.#attemptedAt = -Infinity;
139
- flight.controller.abort(new SessError('aborted', 'Receipt-key retrieval has no remaining waiters.'));
140
- }
141
- }
142
- }
143
- }
@@ -1,220 +0,0 @@
1
- // Decision 0009 Amendment 13: the renderer identities a receipt's `surface.renderer_version` may
2
- // name. A receipt verifies when its identity is one this release bundles, or is on a list signed
3
- // with the issuer's trusted receipt keys, so a future Sess page change needs no SDK update.
4
- //
5
- // The issuer publishes the list at `<issuer>/.well-known/sess-renderer-identities.json`
6
- // (DOCS/spec/receipt-v1.md §10): one JWS in the RFC 7515 flattened JSON serialization
7
- // {"protected", "payload", "signature"}, protected header {"alg": "EdDSA", "kid",
8
- // "typ": "sess-renderer-identities+jwt"}, payload the RFC 8785 canonical JSON
9
- // {"iat", "identities": [{"renderer_version", "since"}, …], "iss", "seq",
10
- // "sess_renderer_identities": 1}. `seq` is the list's edition (higher in every later published
11
- // edition; a copy re-signed unchanged keeps it) and `iat` when that copy was signed (NumericDate);
12
- // the signature covers both. The list only grows; a list is trusted only through its signature,
13
- // never because it was supplied beside a receipt. Authentic lists are ordered by `seq`, with
14
- // containment as the cross-check (newerRendererList); an older list proves the identities it
15
- // holds and never their absence.
16
- import { compactVerify, importJWK } from 'jose';
17
- import {
18
- abortError,
19
- canonicalJson,
20
- exactKeys,
21
- isRecord,
22
- snapshotJson,
23
- verificationError,
24
- waitWithSignal,
25
- } from './json.js';
26
- import type { ReceiptPublicKey } from './verify.js';
27
-
28
- /** One listed identity and the UTC date it was added. */
29
- export interface RendererIdentity {
30
- renderer_version: string;
31
- since: string;
32
- }
33
-
34
- /** A verified list: its edition, when that copy was signed, and its identities in order. */
35
- export interface RendererList {
36
- seq: number;
37
- iat: number;
38
- identities: readonly RendererIdentity[];
39
- }
40
-
41
- /**
42
- * The issuer's list as published when this SDK was released (edition 1). Its identities are
43
- * always accepted for their issuer's receipts; a fetched or supplied list is cross-checked
44
- * against it.
45
- */
46
- export const BUNDLED_RENDERER_LIST: Readonly<{ seq: number; identities: readonly RendererIdentity[] }> =
47
- Object.freeze({
48
- seq: 1,
49
- identities: Object.freeze([
50
- Object.freeze({ renderer_version: 'sess-html-form-1', since: '2026-10-09' }),
51
- Object.freeze({ renderer_version: 'sess-html-form-2', since: '2026-10-18' }),
52
- ]),
53
- });
54
-
55
- /** The identities known when this SDK was released; always accepted for their issuer's receipts. */
56
- export const BUNDLED_RENDERER_IDENTITIES: readonly string[] = Object.freeze(
57
- BUNDLED_RENDERER_LIST.identities.map((i) => i.renderer_version),
58
- );
59
-
60
- /** Where an issuer publishes its signed list (application/json). */
61
- export const RENDERER_IDENTITIES_PATH = '/.well-known/sess-renderer-identities.json';
62
- export const MAX_RENDERER_IDENTITIES_BYTES = 64 * 1024;
63
-
64
- /** The published document: the signed list, as a flattened JWS JSON serialization. */
65
- export interface RendererIdentitiesDocument {
66
- protected: string;
67
- payload: string;
68
- signature: string;
69
- }
70
-
71
- const PART = /^[A-Za-z0-9_-]+$/;
72
- const KID = /^[A-Za-z0-9._-]{1,64}$/;
73
- const IDENTITY = /^[a-z0-9][a-z0-9.-]{0,63}$/;
74
- const DAY = /^\d{4}-\d{2}-\d{2}$/;
75
- const TYP = 'sess-renderer-identities+jwt';
76
-
77
- const invalid = (message: string) => verificationError('INVALID_RENDERER_LIST', message);
78
-
79
- function decode(segment: string): string {
80
- const bytes = Buffer.from(segment, 'base64url');
81
- if (bytes.toString('base64url') !== segment) throw invalid('The renderer list is not canonical base64url.');
82
- try {
83
- return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
84
- } catch {
85
- throw invalid('The renderer list does not contain valid UTF-8 JSON.');
86
- }
87
- }
88
-
89
- function json(text: string): unknown {
90
- try {
91
- return JSON.parse(text);
92
- } catch {
93
- throw invalid('The renderer list is not JSON.');
94
- }
95
- }
96
-
97
- /**
98
- * Verifies a signed renderer-identity list under the issuer's trusted keys. `keyFor` resolves the
99
- * list's kid to a trusted public key (undefined: not trusted). Returns the verified edition: its
100
- * seq, its iat and its identities, in order. It must agree with the bundled list
101
- * (newerRendererList), or it is refused.
102
- */
103
- export async function verifyRendererList(
104
- document: unknown,
105
- context: {
106
- issuer: string;
107
- keyFor: (kid: string) => Promise<ReceiptPublicKey | undefined>;
108
- signal?: AbortSignal;
109
- },
110
- ): Promise<RendererList> {
111
- const value = snapshotJson(document);
112
- if (
113
- !isRecord(value) ||
114
- !exactKeys(value, ['protected', 'payload', 'signature']) ||
115
- ![value.protected, value.payload, value.signature].every((p) => typeof p === 'string' && PART.test(p)) ||
116
- Buffer.byteLength(canonicalJson(value), 'utf8') > MAX_RENDERER_IDENTITIES_BYTES
117
- ) {
118
- throw invalid('The renderer list is not a signed renderer-identity document.');
119
- }
120
- const { protected: protectedHeader, payload, signature } = value as unknown as RendererIdentitiesDocument;
121
- const header = json(decode(protectedHeader));
122
- if (
123
- !isRecord(header) ||
124
- !exactKeys(header, ['alg', 'kid', 'typ']) ||
125
- header.alg !== 'EdDSA' ||
126
- header.typ !== TYP ||
127
- typeof header.kid !== 'string' ||
128
- !KID.test(header.kid)
129
- ) {
130
- throw invalid('The renderer list has an unsupported protected header.');
131
- }
132
- const signal = context.signal;
133
- const publicKey = await context.keyFor(header.kid);
134
- if (!publicKey) throw invalid('The renderer list is not signed with a trusted key.');
135
- try {
136
- const key = await waitWithSignal(
137
- importJWK({ ...publicKey, key_ops: ['verify'], ext: false }, 'EdDSA'),
138
- signal,
139
- );
140
- await waitWithSignal(
141
- compactVerify(`${protectedHeader}.${payload}.${signature}`, key, { algorithms: ['EdDSA'] }),
142
- signal,
143
- );
144
- } catch {
145
- if (signal?.aborted) throw abortError(signal);
146
- throw invalid('The renderer list signature did not verify with the trusted key.');
147
- }
148
- const text = decode(payload);
149
- const claims = json(text);
150
- if (canonicalJson(claims) !== text) throw invalid('The renderer list payload is not canonical JSON.');
151
- if (
152
- !isRecord(claims) ||
153
- !exactKeys(claims, ['iat', 'identities', 'iss', 'seq', 'sess_renderer_identities']) ||
154
- claims.sess_renderer_identities !== 1 ||
155
- !positiveInteger(claims.seq) ||
156
- !positiveInteger(claims.iat) ||
157
- !Array.isArray(claims.identities) ||
158
- claims.identities.length === 0
159
- ) {
160
- throw invalid('The renderer list payload has an unsupported shape.');
161
- }
162
- if (claims.iss !== context.issuer) throw invalid('The renderer list is from another issuer.');
163
- const seen = new Set<string>();
164
- for (const item of claims.identities) {
165
- if (
166
- !isRecord(item) ||
167
- !exactKeys(item, ['renderer_version', 'since']) ||
168
- typeof item.renderer_version !== 'string' ||
169
- !IDENTITY.test(item.renderer_version) ||
170
- seen.has(item.renderer_version) ||
171
- typeof item.since !== 'string' ||
172
- !DAY.test(item.since) ||
173
- !Number.isFinite(Date.parse(`${item.since}T00:00:00Z`)) ||
174
- new Date(`${item.since}T00:00:00Z`).toISOString().slice(0, 10) !== item.since
175
- ) {
176
- throw invalid('The renderer list has a malformed or repeated identity.');
177
- }
178
- seen.add(item.renderer_version);
179
- }
180
- const list: RendererList = Object.freeze({
181
- seq: claims.seq as number,
182
- iat: claims.iat as number,
183
- identities: Object.freeze(
184
- (claims.identities as RendererIdentity[]).map((i) =>
185
- Object.freeze({ renderer_version: i.renderer_version, since: i.since }),
186
- ),
187
- ),
188
- });
189
- // An authentic list that disagrees with the edition this release bundles is refused.
190
- newerRendererList(BUNDLED_RENDERER_LIST, list);
191
- return list;
192
- }
193
-
194
- const positiveInteger = (v: unknown): v is number =>
195
- typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
196
-
197
- /**
198
- * Of two authentic lists of one issuer, the newer edition (the higher seq; for one seq, either:
199
- * they list the same identities). Containment is the cross-check: the newer list must begin with
200
- * every identity of the older, in order and with the same dates, and two lists of one seq must
201
- * list the same identities. Lists that disagree are refused with INVALID_RENDERER_LIST, never
202
- * merged.
203
- */
204
- export function newerRendererList<
205
- A extends { seq: number; identities: readonly RendererIdentity[] },
206
- B extends { seq: number; identities: readonly RendererIdentity[] },
207
- >(a: A, b: B): A | B {
208
- const [older, newer]: [A | B, A | B] = b.seq < a.seq ? [b, a] : [a, b];
209
- const prefix =
210
- newer.identities.length >= older.identities.length &&
211
- older.identities.every(
212
- (o, i) =>
213
- newer.identities[i]?.renderer_version === o.renderer_version &&
214
- newer.identities[i]?.since === o.since,
215
- );
216
- if (!prefix || (older.seq === newer.seq && newer.identities.length !== older.identities.length)) {
217
- throw invalid('The renderer lists disagree.');
218
- }
219
- return newer;
220
- }