@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.
- package/bin/tot.mjs +5 -0
- package/package.json +1 -1
- package/src/app-scaffold.mjs +14 -5
- package/src/commands/app/admin.mjs +69 -2
- package/src/commands/app/index.mjs +4 -1
- package/src/vendor/connector-kit/PIN.json +18 -0
- package/src/vendor/connector-kit/api.js +271 -0
- package/src/vendor/connector-kit/auth.js +233 -0
- package/src/vendor/connector-kit/encoding.js +57 -0
- package/src/vendor/connector-kit/errors.js +76 -0
- package/src/vendor/connector-kit/http-signature.js +130 -0
- package/src/vendor/connector-kit/index.js +21 -0
- package/src/vendor/connector-kit/metadata.js +137 -0
- package/src/vendor/connector-kit/retry.js +58 -0
- package/src/vendor/connector-kit/structured-fields.js +167 -0
- package/src/vendor/connector-kit/webhook.js +239 -0
- package/template/private-app/.env.example +10 -5
- package/template/private-app/README.md +21 -10
- package/template/private-app/connector.js +81 -0
- package/template/private-app/package.json +12 -0
- package/template/private-app/server.js +42 -86
- package/template/private-app/tests/connector.spec.js +93 -0
|
@@ -1,98 +1,54 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
3
|
+
* Webhook receiver for a Storefront Private App. The connector-kit's
|
|
4
|
+
* WebhookReceiver verifies the Content-Digest, the RFC 9421 signature, the
|
|
5
|
+
* `created` window and the replay guard BEFORE your handler sees an event;
|
|
6
|
+
* edit `handleEvent` in connector.js, keep the verification.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* published JWKS/signing-key metadata instead — see the Devkit's
|
|
12
|
-
* https://github.com/tokenoftrust/storefront-devkit/tree/main/apps/private
|
|
13
|
-
* (`examples/hello-inventory`, `recipes/inventory-sync-wms`,
|
|
14
|
-
* `recipes/fulfillment-label-station`, `recipes/dropship-multi-supplier`).
|
|
8
|
+
* Local mode (no TOT_STOREFRONT_ORIGIN) trusts the key `tot app dev` wrote to
|
|
9
|
+
* .tot/dev-keys.json. With TOT_STOREFRONT_ORIGIN set, keys come from the
|
|
10
|
+
* store's published authorization metadata. See connector.js and README.md.
|
|
15
11
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* 2. `tot app install --tenant <tenant> --env test --app .`
|
|
19
|
-
* 3. `POST /api/apps/admin/test-orders` (synthetic preview orders bound to `test` install)
|
|
20
|
-
* 4. `POST /api/apps/admin/candidates` (`private_key_jwt`, `pending_approval`) ->
|
|
21
|
-
* 1-click Store Owner approval in `/admin#integrations` (`POST /api/apps/admin/candidates/decide`)
|
|
12
|
+
* The replay guard defaults to per-process memory; give WebhookReceiver a
|
|
13
|
+
* durable `seenEvents` store before running more than one instance.
|
|
22
14
|
*/
|
|
23
15
|
import { createServer } from "node:http";
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
16
|
+
import { Readable } from "node:stream";
|
|
17
|
+
import { realpathSync } from "node:fs";
|
|
18
|
+
import { fileURLToPath } from "node:url";
|
|
19
|
+
import { createConnector } from "./connector.js";
|
|
20
|
+
|
|
21
|
+
/** Adapt a Node request to the fetch-style Request the receiver reads. */
|
|
22
|
+
function toRequest(req, port) {
|
|
23
|
+
const host = req.headers.host || `localhost:${port}`;
|
|
24
|
+
const hasBody = req.method !== "GET" && req.method !== "HEAD";
|
|
25
|
+
return new Request(new URL(req.url, `http://${host}`), {
|
|
26
|
+
method: req.method,
|
|
27
|
+
headers: req.headers,
|
|
28
|
+
...(hasBody ? { body: Readable.toWeb(req), duplex: "half" } : {}),
|
|
29
|
+
});
|
|
35
30
|
}
|
|
36
31
|
|
|
37
|
-
function
|
|
38
|
-
return
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
32
|
+
export function createWebhookServer(connector, port = Number(process.env.PORT || 8787)) {
|
|
33
|
+
return createServer(async (req, res) => {
|
|
34
|
+
const requestId = req.headers["tot-request-id"] || "(none)";
|
|
35
|
+
try {
|
|
36
|
+
const response = await connector.handleRequest(toRequest(req, port));
|
|
37
|
+
if (response.status >= 400 && response.status !== 405) console.error(`[${requestId}] delivery refused: ${response.status}`);
|
|
38
|
+
res.writeHead(response.status, Object.fromEntries(response.headers)).end(await response.text());
|
|
39
|
+
} catch (error) {
|
|
40
|
+
console.error(`[${requestId}] receiver error: ${error?.code ?? "unexpected"}`);
|
|
41
|
+
res.writeHead(500, { "content-type": "application/json" }).end(JSON.stringify({ accepted: false, code: "receiver_error" }));
|
|
42
|
+
}
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const body = await readBody(req);
|
|
54
|
-
const publicKey = await loadDevPublicKey();
|
|
55
|
-
if (!publicKey) {
|
|
56
|
-
console.error(`[${requestId}] no .tot/dev-keys.json — run \`tot app dev emit\` first`);
|
|
57
|
-
res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "no trusted key on file" }));
|
|
58
|
-
return;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const proto = req.headers["x-forwarded-proto"] || "http";
|
|
62
|
-
const host = req.headers["x-forwarded-host"] || req.headers.host || `localhost:${PORT}`;
|
|
63
|
-
const targetUrl = process.env.WEBHOOK_PUBLIC_URL
|
|
64
|
-
? new URL(req.url, process.env.WEBHOOK_PUBLIC_URL).toString()
|
|
65
|
-
: `${proto}://${host}${req.url}`;
|
|
66
|
-
|
|
67
|
-
const result = await verifyWebhookSignature({
|
|
68
|
-
method: req.method,
|
|
69
|
-
url: targetUrl,
|
|
70
|
-
body,
|
|
71
|
-
headers: {
|
|
72
|
-
"content-digest": req.headers["content-digest"],
|
|
73
|
-
"signature-input": req.headers["signature-input"],
|
|
74
|
-
signature: req.headers["signature"],
|
|
75
|
-
},
|
|
76
|
-
publicKey,
|
|
46
|
+
const entry = process.argv[1] ? realpathSync(process.argv[1]) : null;
|
|
47
|
+
const self = realpathSync(fileURLToPath(import.meta.url));
|
|
48
|
+
if (entry === self) {
|
|
49
|
+
const port = Number(process.env.PORT || 8787);
|
|
50
|
+
const connector = createConnector(process.env);
|
|
51
|
+
createWebhookServer(connector, port).listen(port, () => {
|
|
52
|
+
console.log(`webhook receiver listening on http://localhost:${port} (POST ${connector.endpoint} — see tot-app.json webhooks.endpoint)`);
|
|
77
53
|
});
|
|
78
|
-
|
|
79
|
-
if (!result.ok) {
|
|
80
|
-
console.error(`[${requestId}] signature verification FAILED: ${result.code} — ${result.reason}`);
|
|
81
|
-
res.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify(result));
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
console.log(`[${requestId}] verified delivery (keyid=${result.keyid}, created=${result.created})`);
|
|
86
|
-
// ── Handle the event (multi-tenant ready: route by tenantid + appinstallid) ─
|
|
87
|
-
const event = JSON.parse(body);
|
|
88
|
-
console.log(
|
|
89
|
-
`[${requestId}] ${event.type} for tenant ${event.tenantid} (install=${event.appinstallid}, eventId=${event.id})`,
|
|
90
|
-
);
|
|
91
|
-
// ─────────────────────────────────────────────────────────────────────────
|
|
92
|
-
|
|
93
|
-
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ ok: true }));
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
server.listen(PORT, () => {
|
|
97
|
-
console.log(`webhook receiver listening on http://localhost:${PORT} (POST here — see tot-app.json webhooks.endpoint)`);
|
|
98
|
-
});
|
|
54
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Runs offline: `npm test`. Signs fixtures with the dev-only signer in lib/ and
|
|
2
|
+
// checks that connector.js, built on the vendored connector-kit, accepts a
|
|
3
|
+
// good delivery, refuses a tampered or replayed one, and sends API calls with
|
|
4
|
+
// an installation token and an Idempotency-Key.
|
|
5
|
+
import { test } from "node:test";
|
|
6
|
+
import assert from "node:assert/strict";
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
8
|
+
import { generateDevRs256KeyPair, signWebhookRequest } from "../lib/private-apps-devkit.mjs";
|
|
9
|
+
import { createConnector } from "../connector.js";
|
|
10
|
+
|
|
11
|
+
const ENDPOINT = "https://connector.example.com/webhooks/tot";
|
|
12
|
+
const KID = "test-key-1";
|
|
13
|
+
const fixture = () => readFileSync(new URL("../fixtures/order.created.cloudevent.json", import.meta.url), "utf8");
|
|
14
|
+
|
|
15
|
+
async function setup(extraEnv = {}, overrides = {}) {
|
|
16
|
+
const { privateKey, publicKey } = await generateDevRs256KeyPair();
|
|
17
|
+
const publicKeyJwk = await crypto.subtle.exportKey("jwk", publicKey);
|
|
18
|
+
const events = [];
|
|
19
|
+
const connector = createConnector(
|
|
20
|
+
{ WEBHOOK_ENDPOINT: ENDPOINT, ...extraEnv },
|
|
21
|
+
{
|
|
22
|
+
keys: { resolveSigningKey: async (keyid) => (keyid === KID ? await crypto.subtle.importKey("jwk", { kty: "RSA", n: publicKeyJwk.n, e: publicKeyJwk.e, alg: "RS256", ext: true }, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["verify"]) : null) },
|
|
23
|
+
onEvent: async (event) => events.push(event.id),
|
|
24
|
+
...overrides,
|
|
25
|
+
},
|
|
26
|
+
);
|
|
27
|
+
const deliver = async (body, tamper = (b) => b) => {
|
|
28
|
+
const { headers } = await signWebhookRequest({ method: "POST", url: ENDPOINT, body, key: privateKey, kid: KID });
|
|
29
|
+
return connector.handleRequest(new Request(ENDPOINT, { method: "POST", headers, body: tamper(body) }));
|
|
30
|
+
};
|
|
31
|
+
return { connector, events, deliver };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
test("a signed delivery is verified and reaches the handler once", async () => {
|
|
35
|
+
const { events, deliver } = await setup();
|
|
36
|
+
const first = await deliver(fixture());
|
|
37
|
+
assert.equal(first.status, 202);
|
|
38
|
+
assert.equal(events.length, 1);
|
|
39
|
+
const replay = await deliver(fixture());
|
|
40
|
+
assert.equal(replay.status, 200);
|
|
41
|
+
assert.deepEqual(await replay.json(), { accepted: true, duplicate: true });
|
|
42
|
+
assert.equal(events.length, 1, "a replayed event id never reaches the handler");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("a tampered body is refused before the handler runs", async () => {
|
|
46
|
+
const { events, deliver } = await setup();
|
|
47
|
+
const res = await deliver(fixture(), (b) => b.replace('"total": 91.35', '"total": 1.00'));
|
|
48
|
+
assert.equal(res.status, 400);
|
|
49
|
+
assert.deepEqual(await res.json(), { accepted: false, code: "digest_mismatch" });
|
|
50
|
+
assert.equal(events.length, 0);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("an unknown signing key is refused", async () => {
|
|
54
|
+
const { privateKey } = await generateDevRs256KeyPair();
|
|
55
|
+
const { connector, events } = await setup();
|
|
56
|
+
const { headers } = await signWebhookRequest({ method: "POST", url: ENDPOINT, body: fixture(), key: privateKey, kid: "other-key" });
|
|
57
|
+
const res = await connector.handleRequest(new Request(ENDPOINT, { method: "POST", headers, body: fixture() }));
|
|
58
|
+
assert.equal(res.status, 401);
|
|
59
|
+
assert.equal(events.length, 0);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("API writes carry an installation token and a reused Idempotency-Key", async () => {
|
|
63
|
+
const calls = [];
|
|
64
|
+
let writes = 0;
|
|
65
|
+
const fetch = async (url, init = {}) => {
|
|
66
|
+
calls.push({ url: String(url), headers: new Headers(init.headers), method: init.method });
|
|
67
|
+
if (String(url).endsWith("/api/apps/oauth/token")) {
|
|
68
|
+
return Response.json({ access_token: "tok-1", token_type: "Bearer", expires_in: 3600, scope: "inventory:write" });
|
|
69
|
+
}
|
|
70
|
+
if (++writes === 1) return new Response("{}", { status: 503, headers: { "retry-after": "0" } });
|
|
71
|
+
return Response.json({ ok: true });
|
|
72
|
+
};
|
|
73
|
+
const { connector } = await setup(
|
|
74
|
+
{ TOT_STOREFRONT_ORIGIN: "https://acme.example.com", TOT_CLIENT_ID: "client-1", TOT_CLIENT_SECRET: "secret-1" },
|
|
75
|
+
{ fetch },
|
|
76
|
+
);
|
|
77
|
+
assert.ok(connector.api, "api client exists once the origin and credentials are set");
|
|
78
|
+
const res = await connector.api.post("/inventory/movements", { sku: "SKU-1", quantityDelta: -1 });
|
|
79
|
+
assert.equal(res.status, 200);
|
|
80
|
+
|
|
81
|
+
const token = calls.find((c) => c.url.endsWith("/api/apps/oauth/token"));
|
|
82
|
+
assert.match(token.headers.get("authorization"), /^Basic /);
|
|
83
|
+
const posts = calls.filter((c) => c.url.endsWith("/api/apps/v1/inventory/movements"));
|
|
84
|
+
assert.equal(posts.length, 2, "the 503 was retried");
|
|
85
|
+
assert.equal(posts[0].headers.get("authorization"), "Bearer tok-1");
|
|
86
|
+
assert.ok(posts[0].headers.get("idempotency-key"));
|
|
87
|
+
assert.equal(posts[0].headers.get("idempotency-key"), posts[1].headers.get("idempotency-key"));
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("without credentials there is no API client", async () => {
|
|
91
|
+
const { connector } = await setup();
|
|
92
|
+
assert.equal(connector.api, null);
|
|
93
|
+
});
|