@tokenoftrust/cli 6.14.5 → 6.15.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.
@@ -0,0 +1,58 @@
1
+ // Retry policy shared by the API client and the token client: bounded
2
+ // exponential backoff with full jitter, and `Retry-After` honored exactly.
3
+
4
+ export const DEFAULT_RETRY_POLICY = Object.freeze({
5
+ /** Total attempts, including the first. */
6
+ maxAttempts: 5,
7
+ /** First backoff ceiling; doubles per attempt. */
8
+ baseDelayMs: 250,
9
+ /** Largest backoff the kit computes itself. */
10
+ maxDelayMs: 20_000,
11
+ /** Largest `Retry-After` the kit waits in-process. A longer one is returned to the caller to schedule. */
12
+ maxRetryAfterMs: 120_000,
13
+ });
14
+
15
+ /** Statuses where the same request can succeed later. */
16
+ export const RETRYABLE_STATUS = new Set([408, 429, 502, 503, 504]);
17
+
18
+ export function retryPolicy(overrides = {}) {
19
+ const policy = { ...DEFAULT_RETRY_POLICY, ...overrides };
20
+ for (const [key, value] of Object.entries(policy)) {
21
+ if (!Number.isFinite(value) || value < 0) throw new TypeError(`retry.${key} must be a non-negative number`);
22
+ }
23
+ if (policy.maxAttempts < 1) throw new TypeError('retry.maxAttempts must be at least 1');
24
+ return policy;
25
+ }
26
+
27
+ /**
28
+ * `Retry-After` in milliseconds: delta-seconds or an HTTP-date (RFC 9110
29
+ * section 10.2.3). Undefined when absent or unreadable.
30
+ */
31
+ export function parseRetryAfter(value, nowMs = Date.now()) {
32
+ if (value === null || value === undefined) return undefined;
33
+ const text = String(value).trim();
34
+ if (/^\d+$/.test(text)) return Number(text) * 1000;
35
+ const at = Date.parse(text);
36
+ if (Number.isNaN(at)) return undefined;
37
+ return Math.max(0, at - nowMs);
38
+ }
39
+
40
+ /** Full-jitter backoff for the given 1-based attempt that just failed. */
41
+ export function backoffDelay(attempt, policy, random = Math.random) {
42
+ const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (attempt - 1));
43
+ return Math.floor(random() * ceiling);
44
+ }
45
+
46
+ export const defaultSleep = (ms, signal) =>
47
+ new Promise((resolve, reject) => {
48
+ if (signal?.aborted) return reject(signal.reason);
49
+ const timer = setTimeout(resolve, ms);
50
+ signal?.addEventListener(
51
+ 'abort',
52
+ () => {
53
+ clearTimeout(timer);
54
+ reject(signal.reason);
55
+ },
56
+ { once: true },
57
+ );
58
+ });
@@ -0,0 +1,167 @@
1
+ // Minimal RFC 8941 Structured Field Values parser: just enough to read the
2
+ // Dictionary-valued headers RFC 9421 (Signature-Input, Signature) and
3
+ // RFC 9530 (Content-Digest) use. Every member keeps its raw text so the
4
+ // verifier can rebuild "@signature-params" exactly as the signer serialized it.
5
+ import { base64Decode } from './encoding.js';
6
+
7
+ export class StructuredFieldError extends Error {}
8
+
9
+ const KEY_START = /[a-z*]/;
10
+ const KEY_CHAR = /[a-z0-9_\-.*]/;
11
+ const TOKEN_START = /[A-Za-z*]/;
12
+ const TOKEN_CHAR = /[A-Za-z0-9!#$%&'*+\-.^_`|~:/]/;
13
+
14
+ export function parseDictionary(text) {
15
+ const p = { s: String(text ?? ''), i: 0 };
16
+ const out = new Map();
17
+ skipSP(p);
18
+ if (p.i >= p.s.length) throw new StructuredFieldError('empty dictionary');
19
+ while (p.i < p.s.length) {
20
+ const start = p.i;
21
+ const key = parseKey(p);
22
+ let member;
23
+ if (p.s[p.i] === '=') {
24
+ p.i++;
25
+ member = parseItemOrInnerList(p);
26
+ } else {
27
+ member = { value: true, params: parseParams(p) };
28
+ }
29
+ member.raw = p.s.slice(start + key.length + 1, p.i);
30
+ out.set(key, member);
31
+ skipOWS(p);
32
+ if (p.i >= p.s.length) break;
33
+ if (p.s[p.i] !== ',') throw new StructuredFieldError(`unexpected "${p.s[p.i]}"`);
34
+ p.i++;
35
+ skipOWS(p);
36
+ if (p.i >= p.s.length) throw new StructuredFieldError('trailing comma');
37
+ }
38
+ return out;
39
+ }
40
+
41
+ function parseItemOrInnerList(p) {
42
+ if (p.s[p.i] === '(') return parseInnerList(p);
43
+ const value = parseBareItem(p);
44
+ return { value, params: parseParams(p) };
45
+ }
46
+
47
+ function parseInnerList(p) {
48
+ p.i++;
49
+ const items = [];
50
+ for (;;) {
51
+ skipSP(p);
52
+ if (p.s[p.i] === ')') {
53
+ p.i++;
54
+ return { value: items, innerList: true, params: parseParams(p) };
55
+ }
56
+ if (p.i >= p.s.length) throw new StructuredFieldError('unterminated inner list');
57
+ const value = parseBareItem(p);
58
+ items.push({ value, params: parseParams(p) });
59
+ if (p.s[p.i] !== ' ' && p.s[p.i] !== ')') throw new StructuredFieldError('bad inner list');
60
+ }
61
+ }
62
+
63
+ function parseParams(p) {
64
+ const params = new Map();
65
+ while (p.s[p.i] === ';') {
66
+ p.i++;
67
+ skipSP(p);
68
+ const key = parseKey(p);
69
+ let value = true;
70
+ if (p.s[p.i] === '=') {
71
+ p.i++;
72
+ value = parseBareItem(p);
73
+ }
74
+ params.set(key, value);
75
+ }
76
+ return params;
77
+ }
78
+
79
+ function parseKey(p) {
80
+ if (!KEY_START.test(p.s[p.i] ?? '')) throw new StructuredFieldError('bad key');
81
+ const start = p.i;
82
+ while (p.i < p.s.length && KEY_CHAR.test(p.s[p.i])) p.i++;
83
+ return p.s.slice(start, p.i);
84
+ }
85
+
86
+ function parseBareItem(p) {
87
+ const c = p.s[p.i];
88
+ if (c === '"') return parseString(p);
89
+ if (c === ':') return parseBytes(p);
90
+ if (c === '?') return parseBoolean(p);
91
+ if (c === '-' || /[0-9]/.test(c ?? '')) return parseNumber(p);
92
+ if (TOKEN_START.test(c ?? '')) return parseToken(p);
93
+ throw new StructuredFieldError('bad item');
94
+ }
95
+
96
+ function parseString(p) {
97
+ p.i++;
98
+ let out = '';
99
+ while (p.i < p.s.length) {
100
+ const c = p.s[p.i++];
101
+ if (c === '\\') {
102
+ const n = p.s[p.i++];
103
+ if (n !== '"' && n !== '\\') throw new StructuredFieldError('bad escape');
104
+ out += n;
105
+ } else if (c === '"') {
106
+ return out;
107
+ } else {
108
+ const code = c.charCodeAt(0);
109
+ if (code < 0x20 || code > 0x7e) throw new StructuredFieldError('bad string char');
110
+ out += c;
111
+ }
112
+ }
113
+ throw new StructuredFieldError('unterminated string');
114
+ }
115
+
116
+ function parseBytes(p) {
117
+ p.i++;
118
+ const end = p.s.indexOf(':', p.i);
119
+ if (end < 0) throw new StructuredFieldError('unterminated byte sequence');
120
+ const b64 = p.s.slice(p.i, end);
121
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 !== 0) throw new StructuredFieldError('bad base64');
122
+ p.i = end + 1;
123
+ try {
124
+ return { bytes: base64Decode(b64) };
125
+ } catch {
126
+ throw new StructuredFieldError('bad base64');
127
+ }
128
+ }
129
+
130
+ function parseBoolean(p) {
131
+ const v = p.s[p.i + 1];
132
+ if (v !== '0' && v !== '1') throw new StructuredFieldError('bad boolean');
133
+ p.i += 2;
134
+ return v === '1';
135
+ }
136
+
137
+ // RFC 8941 §4.2.4: an Integer (up to 15 digits) or a Decimal (up to 12
138
+ // integer and 1-3 fractional digits). Decimals parse so that unrelated members
139
+ // carrying one never make the whole dictionary unreadable; the verifier only
140
+ // reads the Integer parameters it needs.
141
+ function parseNumber(p) {
142
+ const rest = p.s.slice(p.i);
143
+ const decimal = /^-?[0-9]{1,12}\.[0-9]{1,3}/.exec(rest);
144
+ if (decimal && !/[0-9.]/.test(rest[decimal[0].length] ?? '')) {
145
+ p.i += decimal[0].length;
146
+ return { decimal: Number(decimal[0]) };
147
+ }
148
+ const m = /^-?[0-9]{1,15}/.exec(rest);
149
+ if (!m || /[0-9.]/.test(rest[m[0].length] ?? '')) throw new StructuredFieldError('bad number');
150
+ p.i += m[0].length;
151
+ return Number(m[0]);
152
+ }
153
+
154
+ function parseToken(p) {
155
+ const start = p.i;
156
+ p.i++;
157
+ while (p.i < p.s.length && TOKEN_CHAR.test(p.s[p.i])) p.i++;
158
+ return { token: p.s.slice(start, p.i) };
159
+ }
160
+
161
+ function skipSP(p) {
162
+ while (p.s[p.i] === ' ') p.i++;
163
+ }
164
+
165
+ function skipOWS(p) {
166
+ while (p.s[p.i] === ' ' || p.s[p.i] === '\t') p.i++;
167
+ }
@@ -0,0 +1,239 @@
1
+ // Webhook receiver. The order follows apps/private/webhooks-and-api.md: raw
2
+ // body, Content-Digest, RFC 9421 signature (with a created/expires window and
3
+ // keyid resolution against the published `webhook_signing_keys`), CloudEvents
4
+ // envelope, then a replay guard on the event id through an injectable store.
5
+ // Only an event that passed every step reaches application code.
6
+ import { toBytes } from './encoding.js';
7
+ import { verifyContentDigest, verifyMessageSignature } from './http-signature.js';
8
+
9
+ export const DEFAULT_MAX_BODY_BYTES = 1024 * 1024;
10
+ export const EVENT_TYPE_PREFIX = 'com.tokenoftrust.storefront.';
11
+ const ENVELOPE_REQUIRED = ['specversion', 'id', 'source', 'type', 'time', 'datacontenttype', 'tenantid', 'appinstallid', 'dataschemaversion', 'data'];
12
+ const SEVEN_DAYS_SECONDS = 7 * 24 * 60 * 60;
13
+
14
+ /** HTTP status for each refusal code. */
15
+ export const WEBHOOK_REFUSALS = Object.freeze({
16
+ method_not_allowed: 405,
17
+ body_too_large: 413,
18
+ digest_missing: 400,
19
+ digest_malformed: 400,
20
+ digest_unsupported: 400,
21
+ digest_mismatch: 400,
22
+ signature_missing: 401,
23
+ signature_malformed: 401,
24
+ signature_coverage: 401,
25
+ unsupported_alg: 401,
26
+ signature_expired: 401,
27
+ unknown_key: 401,
28
+ signature_invalid: 401,
29
+ body_not_json: 400,
30
+ envelope_invalid: 400,
31
+ // A replay is acknowledged with 200 so the sender stops, and never reaches the application.
32
+ replayed_event: 200,
33
+ });
34
+
35
+ /**
36
+ * In-memory seen-event store, bounded by entry count and TTL. It does not
37
+ * survive a restart or span instances: production receivers implement the same
38
+ * two methods over durable storage (a unique-key insert with an expiry).
39
+ */
40
+ export class MemorySeenEventStore {
41
+ constructor({ maxEntries = 100_000, now = () => Date.now() } = {}) {
42
+ this.maxEntries = maxEntries;
43
+ this.now = now;
44
+ this.entries = new Map();
45
+ }
46
+
47
+ /** Record `key` as seen. Resolves true when it was new, false when already present and unexpired. */
48
+ async claim(key, ttlSeconds) {
49
+ const at = this.now();
50
+ const expiresAt = this.entries.get(key);
51
+ if (expiresAt !== undefined && expiresAt > at) return false;
52
+ this.entries.delete(key);
53
+ this.entries.set(key, at + ttlSeconds * 1000);
54
+ while (this.entries.size > this.maxEntries) this.entries.delete(this.entries.keys().next().value);
55
+ return true;
56
+ }
57
+
58
+ /** Forget `key` so a redelivery is processed (the application failed to handle it). */
59
+ async release(key) {
60
+ this.entries.delete(key);
61
+ }
62
+ }
63
+
64
+ /** Lowercased, single-string header map from a Headers object, a plain object, or entry pairs. */
65
+ export function normalizeHeaders(headers) {
66
+ const out = {};
67
+ if (!headers) return out;
68
+ const entries = typeof headers.entries === 'function' && !Array.isArray(headers) ? headers.entries() : Array.isArray(headers) ? headers : Object.entries(headers);
69
+ for (const [name, value] of entries) {
70
+ if (value === undefined || value === null) continue;
71
+ out[String(name).toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);
72
+ }
73
+ return out;
74
+ }
75
+
76
+ function envelopeProblem(event) {
77
+ if (!event || typeof event !== 'object' || Array.isArray(event)) return 'not an object';
78
+ for (const key of ENVELOPE_REQUIRED) if (!(key in event)) return `missing ${key}`;
79
+ if (event.specversion !== '1.0') return 'specversion';
80
+ for (const key of ['id', 'source', 'type', 'tenantid', 'appinstallid']) {
81
+ if (typeof event[key] !== 'string' || event[key] === '') return key;
82
+ }
83
+ if (!event.type.startsWith(EVENT_TYPE_PREFIX)) return 'type';
84
+ if (!event.data || typeof event.data !== 'object' || Array.isArray(event.data)) return 'data';
85
+ return null;
86
+ }
87
+
88
+ export class WebhookReceiver {
89
+ /**
90
+ * @param {object} options
91
+ * @param {string} options.endpoint The webhook endpoint exactly as registered in tot-app.json (the signed `@target-uri`).
92
+ * @param {{ resolveSigningKey(keyid: string): Promise<CryptoKey|null> }} options.keys AuthorizationMetadata or StaticSigningKeys.
93
+ * @param {{ claim(key: string, ttlSeconds: number): Promise<boolean>, release(key: string): Promise<void> }} [options.seenEvents]
94
+ * @param {number} [options.maxAgeSeconds] Oldest acceptable signature `created` (default 300).
95
+ * @param {number} [options.maxClockSkewSeconds] Furthest-future acceptable `created` (default 60).
96
+ * @param {number} [options.replayTtlSeconds] How long an event id is remembered (default 7 days).
97
+ * @param {number} [options.maxBodyBytes] Largest accepted body (default 1 MiB).
98
+ * @param {() => number} [options.now] Milliseconds since the epoch.
99
+ */
100
+ constructor({
101
+ endpoint,
102
+ keys,
103
+ seenEvents = new MemorySeenEventStore(),
104
+ maxAgeSeconds = 300,
105
+ maxClockSkewSeconds = 60,
106
+ replayTtlSeconds = SEVEN_DAYS_SECONDS,
107
+ maxBodyBytes = DEFAULT_MAX_BODY_BYTES,
108
+ now = () => Date.now(),
109
+ }) {
110
+ // The registered string is kept verbatim: it is signed character for character.
111
+ if (typeof endpoint !== 'string' || !URL.canParse(endpoint)) {
112
+ throw new TypeError('endpoint must be the absolute webhook URL registered in tot-app.json');
113
+ }
114
+ if (!keys || typeof keys.resolveSigningKey !== 'function') throw new TypeError('keys must provide resolveSigningKey(keyid)');
115
+ if (!seenEvents || typeof seenEvents.claim !== 'function' || typeof seenEvents.release !== 'function') {
116
+ throw new TypeError('seenEvents must provide claim(key, ttlSeconds) and release(key)');
117
+ }
118
+ this.endpoint = endpoint;
119
+ this.keys = keys;
120
+ this.seenEvents = seenEvents;
121
+ this.maxAgeSeconds = maxAgeSeconds;
122
+ this.maxClockSkewSeconds = maxClockSkewSeconds;
123
+ this.replayTtlSeconds = replayTtlSeconds;
124
+ this.maxBodyBytes = maxBodyBytes;
125
+ this.now = now;
126
+ }
127
+
128
+ /**
129
+ * Verify one delivery and claim its event id.
130
+ *
131
+ * Resolves `{ ok: true, event, keyid, created, replayKey }`, or
132
+ * `{ ok: false, status, code }` where `status` is the HTTP status to answer.
133
+ * After `ok: true` the id is claimed: call `release(replayKey)` if the event
134
+ * could not be handled, so the sender's retry is processed.
135
+ *
136
+ * @param {object} delivery
137
+ * @param {string} delivery.method
138
+ * @param {Headers|Record<string, string|string[]>} delivery.headers
139
+ * @param {Uint8Array|ArrayBuffer|string} delivery.body The exact raw body bytes.
140
+ */
141
+ async verify({ method, headers, body }) {
142
+ const refuse = (code) => ({ ok: false, status: WEBHOOK_REFUSALS[code], code });
143
+ if (String(method).toUpperCase() !== 'POST') return refuse('method_not_allowed');
144
+ const bytes = toBytes(body);
145
+ if (bytes.length > this.maxBodyBytes) return refuse('body_too_large');
146
+ const h = normalizeHeaders(headers);
147
+
148
+ const digest = await verifyContentDigest(h['content-digest'], bytes);
149
+ if (!digest.ok) return refuse(digest.code);
150
+
151
+ const signature = await verifyMessageSignature({
152
+ method: 'POST',
153
+ targetUri: this.endpoint,
154
+ headers: h,
155
+ resolveKey: (keyid) => this.keys.resolveSigningKey(keyid),
156
+ now: this.now(),
157
+ maxAgeSeconds: this.maxAgeSeconds,
158
+ maxClockSkewSeconds: this.maxClockSkewSeconds,
159
+ });
160
+ if (!signature.ok) return refuse(signature.code);
161
+
162
+ let event;
163
+ try {
164
+ event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
165
+ } catch {
166
+ return refuse('body_not_json');
167
+ }
168
+ if (envelopeProblem(event)) return refuse('envelope_invalid');
169
+
170
+ const replayKey = `${event.tenantid}/${event.id}`;
171
+ if (!(await this.seenEvents.claim(replayKey, this.replayTtlSeconds))) return refuse('replayed_event');
172
+ return { ok: true, event, keyid: signature.keyid, created: signature.created, replayKey };
173
+ }
174
+
175
+ /** Forget a claimed event id so its redelivery is processed. */
176
+ release(replayKey) {
177
+ return this.seenEvents.release(replayKey);
178
+ }
179
+
180
+ /**
181
+ * Verify, then run `onEvent(event, context)`. Answers 202 once the handler
182
+ * resolves, 200 for a replay, the refusal status otherwise, and 500 (with the
183
+ * id released, so the sender retries) when the handler throws.
184
+ *
185
+ * @returns {Promise<{ status: number, body: object, error?: unknown }>}
186
+ */
187
+ async receive(delivery, onEvent) {
188
+ const result = await this.verify(delivery);
189
+ if (!result.ok) {
190
+ return { status: result.status, body: result.code === 'replayed_event' ? { accepted: true, duplicate: true } : { accepted: false, code: result.code } };
191
+ }
192
+ try {
193
+ await onEvent(result.event, { keyid: result.keyid, created: result.created });
194
+ } catch (error) {
195
+ await this.release(result.replayKey);
196
+ return { status: 500, body: { accepted: false, code: 'handler_failed' }, error };
197
+ }
198
+ return { status: 202, body: { accepted: true } };
199
+ }
200
+
201
+ /** `receive` for a fetch-style Request; resolves a Response. */
202
+ async handleRequest(request, onEvent) {
203
+ const body = await readCapped(request, this.maxBodyBytes);
204
+ const result = body === null
205
+ ? { status: 413, body: { accepted: false, code: 'body_too_large' } }
206
+ : await this.receive({ method: request.method, headers: request.headers, body }, onEvent);
207
+ return new Response(JSON.stringify(result.body), {
208
+ status: result.status,
209
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
210
+ });
211
+ }
212
+ }
213
+
214
+ /** The request body, or null once it exceeds maxBytes (declared or streamed); never buffers past the cap. */
215
+ async function readCapped(request, maxBytes) {
216
+ const declared = Number(request.headers.get('content-length'));
217
+ if (request.headers.has('content-length') && Number.isFinite(declared) && declared > maxBytes) return null;
218
+ if (!request.body) return new Uint8Array(0);
219
+ const reader = request.body.getReader();
220
+ const chunks = [];
221
+ let size = 0;
222
+ for (;;) {
223
+ const { done, value } = await reader.read();
224
+ if (done) break;
225
+ size += value.byteLength;
226
+ if (size > maxBytes) {
227
+ await reader.cancel().catch(() => {});
228
+ return null;
229
+ }
230
+ chunks.push(value);
231
+ }
232
+ const out = new Uint8Array(size);
233
+ let offset = 0;
234
+ for (const chunk of chunks) {
235
+ out.set(chunk, offset);
236
+ offset += chunk.byteLength;
237
+ }
238
+ return out;
239
+ }
@@ -4,11 +4,16 @@
4
4
  # Port the stub webhook receiver (server.js) listens on.
5
5
  PORT=8787
6
6
 
7
- # Optional externally visible webhook origin (without trailing slash) when running
8
- # behind a local preview tunnel (cloudflared, Microsoft devtunnel, ngrok) or
9
- # reverse-proxied container host so RFC 9421 @target-uri verification matches
10
- # the HTTPS URL Storefront signed.
11
- # WEBHOOK_PUBLIC_URL=https://random-words.trycloudflare.com
7
+ # Your registered webhooks.endpoint, character for character: it is the signed
8
+ # @target-uri, so a local tunnel or reverse proxy must be named here, not guessed
9
+ # from request headers. Defaults to http://localhost:$PORT/webhooks.
10
+ # WEBHOOK_ENDPOINT=https://random-words.trycloudflare.com/webhooks
11
+
12
+ # Set these to leave local mode: webhook keys then come from the store's
13
+ # published metadata and the connector gets an API client (connector.js).
14
+ # TOT_STOREFRONT_ORIGIN=https://acme.tokenoftrust.store
15
+ # TOT_CLIENT_ID=
16
+ # TOT_CLIENT_SECRET=
12
17
 
13
18
  # Must match tot-app.json's webhooks.signatureKeyId. `tot app dev` writes the
14
19
  # matching public key alongside this app at .tot/dev-keys.json for local runs
@@ -19,12 +19,20 @@ are the stable human and LLM entry points.
19
19
  [`apps/private/contract/examples/`](https://github.com/tokenoftrust/storefront-devkit/tree/main/apps/private/contract/examples/))
20
20
  you can sign and deliver to your own receiver locally, before you have a
21
21
  real install. Add one fixture per topic you subscribe to.
22
- - **`server.js`** — a minimal Node HTTP receiver for `webhooks.endpoint`. It
23
- verifies the RFC 9421 HTTP Message Signature + RFC 9530 Content-Digest on
24
- every inbound request before trusting the body — replace the handler logic,
25
- keep the verification. Supports `WEBHOOK_PUBLIC_URL` (or `X-Forwarded-Proto`
26
- / `X-Forwarded-Host`) for local tunnels and reverse-proxied container hosts,
27
- and logs `event.tenantid` + `event.appinstallid` for multi-tenant routing.
22
+ - **`vendor/connector-kit/`** — the Devkit's
23
+ [connector-kit](https://github.com/tokenoftrust/storefront-devkit/tree/main/packages/connector-kit),
24
+ vendored as source and pinned to a Devkit commit in `vendor/connector-kit/PIN.json`. It gives
25
+ you `WebhookReceiver` (Content-Digest, RFC 9421 signature, `created` window, published-key
26
+ lookup, replay guard), `ConnectorAuthClient` (installation tokens) and `ApiClient`
27
+ (`Idempotency-Key` reused on retry, `Retry-After`, pagination). Treat it as read-only; to upgrade,
28
+ replace the directory with a newer copy and read the Devkit changelog.
29
+ - **`connector.js`** — wires the kit from the environment and holds `handleEvent`, where your
30
+ logic goes. A delivery is a notification: read current state through `api` before acting.
31
+ - **`server.js`** — a minimal Node HTTP server in front of the receiver. Nothing reaches
32
+ `handleEvent` unverified. Set `WEBHOOK_ENDPOINT` to your registered `webhooks.endpoint`
33
+ (it is the signed `@target-uri`; the default is `http://localhost:$PORT/webhooks`).
34
+ - **`tests/`** — `npm test` runs offline: signed delivery accepted once, tampered and unknown-key
35
+ deliveries refused, API writes sent with a token and a stable `Idempotency-Key`.
28
36
  - **`Dockerfile`** — portable Node 22 Alpine container for self-hosted
29
37
  container platforms (Google Cloud Run, Azure Container Apps, Fly.io, Render,
30
38
  Railway, AWS ECS) or optional `installMode: "hosted"`.
@@ -35,7 +43,8 @@ are the stable human and LLM entry points.
35
43
  ```
36
44
  # lint tot-app.json against the contract
37
45
  tot app dev validate
38
- # start the stub receiver
46
+ # run the connector's tests, then start the receiver
47
+ npm test
39
48
  node server.js &
40
49
  # sign a fixture CloudEvent and POST it in
41
50
  tot app dev emit order.created
@@ -144,9 +153,11 @@ curl -s https://storefront.tokenoftrust.store/<tenant>/api/apps/v1/<path> \
144
153
 
145
154
  ## Going live (`private_key_jwt` candidate staging & 1-click Owner approval)
146
155
 
147
- 1. Point `webhooks.endpoint` at your real, publicly reachable HTTPS receiver and swap the dev-only
148
- signature verification in `server.js` for the platform's published JWKS/signing-key metadata
149
- (see the Devkit's
156
+ 1. Point `webhooks.endpoint` at your real, publicly reachable HTTPS receiver, set
157
+ `WEBHOOK_ENDPOINT` to that exact URL, and set `TOT_STOREFRONT_ORIGIN`, `TOT_CLIENT_ID` and
158
+ `TOT_CLIENT_SECRET` so the connector verifies against the platform's published signing keys
159
+ and gets its API client. Replace the in-memory replay guard with a durable store if you run more
160
+ than one instance (see the Devkit's
150
161
  [`webhooks-and-api.md`](https://github.com/tokenoftrust/storefront-devkit/blob/main/apps/private/webhooks-and-api.md)).
151
162
  2. **Stage a `private_key_jwt` `production` candidate (`pending_approval`):**
152
163
  Run `tot app candidate --jwks-uri https://...` (or `--jwks <file>` with `{ keys: [ <publicKeyJwk> ] }`;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The connector's wiring: webhook verification, installation auth and API
3
+ * calls, all from the vendored connector-kit (`vendor/connector-kit/`, pinned
4
+ * by `vendor/connector-kit/PIN.json`; read its README in the Devkit at
5
+ * `packages/connector-kit`). Treat the vendored directory as read-only — upgrade by
6
+ * replacing it. Put your business logic in `handleEvent`.
7
+ *
8
+ * Environment (see `.env.example`):
9
+ * TOT_STOREFRONT_ORIGIN the store's origin, e.g. https://acme.tokenoftrust.store.
10
+ * Set -> webhook keys come from the store's published
11
+ * metadata, and the API client is created when
12
+ * the credentials below are also set.
13
+ * Unset -> local mode: webhooks are checked against the
14
+ * throwaway key `tot app dev` wrote to .tot/dev-keys.json.
15
+ * TOT_CLIENT_ID, TOT_CLIENT_SECRET installation credentials (client_secret_basic).
16
+ * WEBHOOK_ENDPOINT your registered `webhooks.endpoint`, character for
17
+ * character. It is the signed @target-uri.
18
+ * TOT_DEV_KEYS path to the dev key file (default .tot/dev-keys.json).
19
+ */
20
+ import { existsSync, readFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import {
23
+ ApiClient,
24
+ AuthorizationMetadata,
25
+ ConnectorAuthClient,
26
+ StaticSigningKeys,
27
+ WebhookReceiver,
28
+ } from "./vendor/connector-kit/index.js";
29
+
30
+ /** Local-mode keys: the public half of `tot app dev`'s key, re-read on every lookup. */
31
+ export function devSigningKeys(path) {
32
+ return {
33
+ async resolveSigningKey(keyid) {
34
+ if (!existsSync(path)) return null;
35
+ const { kid, publicKeyJwk } = JSON.parse(readFileSync(path, "utf8"));
36
+ const keys = new StaticSigningKeys({ keys: [{ ...publicKeyJwk, kid, alg: "RS256", use: "sig" }] });
37
+ return keys.resolveSigningKey(keyid);
38
+ },
39
+ };
40
+ }
41
+
42
+ /** Reconcile here: a delivery is a notification, so read current state through `api` before acting. */
43
+ export async function handleEvent(event, { keyid, created }, { log = console.log, api = null } = {}) {
44
+ log(`verified delivery (keyid=${keyid}, created=${created})`);
45
+ log(`${event.type.replace("com.tokenoftrust.storefront.", "")} for tenant ${event.tenantid} (install=${event.appinstallid}, eventId=${event.id})`);
46
+ }
47
+
48
+ /**
49
+ * @param {Record<string, string | undefined>} env
50
+ * @param {{ fetch?: typeof fetch, keys?: { resolveSigningKey(keyid: string): Promise<unknown> }, now?: () => number, onEvent?: Function }} [overrides]
51
+ */
52
+ export function createConnector(env = process.env, overrides = {}) {
53
+ const origin = env.TOT_STOREFRONT_ORIGIN || null;
54
+ const port = Number(env.PORT || 8787);
55
+ const endpoint = env.WEBHOOK_ENDPOINT || `http://localhost:${port}/webhooks`;
56
+ const fetchImpl = overrides.fetch;
57
+ const clock = overrides.now ? { now: overrides.now } : {};
58
+
59
+ const keys =
60
+ overrides.keys ??
61
+ (origin
62
+ ? new AuthorizationMetadata({ origin, ...(fetchImpl ? { fetch: fetchImpl } : {}), ...clock })
63
+ : devSigningKeys(env.TOT_DEV_KEYS || join(process.cwd(), ".tot", "dev-keys.json")));
64
+ const receiver = new WebhookReceiver({ endpoint, keys, ...clock });
65
+
66
+ let auth = null;
67
+ let api = null;
68
+ if (origin && env.TOT_CLIENT_ID && env.TOT_CLIENT_SECRET) {
69
+ auth = new ConnectorAuthClient({
70
+ origin,
71
+ clientId: env.TOT_CLIENT_ID,
72
+ clientSecret: env.TOT_CLIENT_SECRET,
73
+ ...(fetchImpl ? { fetch: fetchImpl } : {}),
74
+ ...clock,
75
+ });
76
+ api = new ApiClient({ origin, auth, ...(fetchImpl ? { fetch: fetchImpl } : {}), ...clock });
77
+ }
78
+
79
+ const onEvent = overrides.onEvent ?? ((event, info) => handleEvent(event, info, { api }));
80
+ return { endpoint, receiver, auth, api, onEvent, handleRequest: (request) => receiver.handleRequest(request, onEvent) };
81
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "my-app",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "A Storefront Private App connector.",
7
+ "engines": { "node": ">=20" },
8
+ "scripts": {
9
+ "start": "node server.js",
10
+ "test": "node --test tests/*.spec.js"
11
+ }
12
+ }