@c1m-public/channel-client 0.1.0 → 0.2.1

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/README.md CHANGED
@@ -29,7 +29,26 @@ asset requests.
29
29
  - API failures throw `ChannelAPIError` with safe status, code, and request ID.
30
30
  - Assets remain tokenless and are normalized with `assetUrl()`.
31
31
 
32
- ## Private release
32
+ ## Webhooks
33
+
34
+ Verify webhook requests before parsing or acting on their payload:
35
+
36
+ ```ts
37
+ import { parseChannelWebhookEvent } from "@c1m-public/channel-client";
38
+
39
+ const event = await parseChannelWebhookEvent(request, {
40
+ secret: process.env.C1M_CHANNEL_WEBHOOK_SECRET!,
41
+ });
42
+ ```
43
+
44
+ The verifier authenticates the raw body and `X-C1M-Timestamp` with the
45
+ `X-C1M-Signature` HMAC using a timing-safe comparison. It rejects timestamps
46
+ outside a five-minute window by default, including future timestamps. Keep the
47
+ raw request body intact, return a non-success response on verification failure,
48
+ and make event handling idempotent: the timestamp window limits replay exposure
49
+ but does not provide single-delivery semantics.
50
+
51
+ ## Release
33
52
 
34
53
  Build and inspect before publishing:
35
54
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import "server-only";
2
2
  export * from "./webhooks.js";
3
- export type { BlogPost, BlogPostResponse, LeadResponse, LightInitResponse, ListResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, SiteGatedDocument, SiteResolvedDocument, ThemeResponse, } from "./types";
4
- import type { BlogPostResponse, LeadResponse, LightInitResponse, ListResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, ThemeResponse } from "./types";
3
+ export type { BlogPost, BlogPostResponse, Customer, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, Order, OrderSummary, SendCodeResponse, LightInitResponse, ListResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, Menu, MenuItem, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, SiteGatedDocument, SiteResolvedDocument, ThemeResponse, } from "./types";
4
+ import type { BlogPostResponse, CustomerResponse, CustomerSession, CustomerSignupResponse, LeadResponse, LightInitResponse, ListResponse, Order, OrderSummary, SendCodeResponse, Product, ProductAsset, PublicPage, PublicPageSummary, PublicSubmitReviewInput, PublicWorkspaceInit, MenuResponse, Review, ReviewSummaryResponse, SiteDocument, ThemeResponse } from "./types";
5
5
  export type ChannelCachePolicy = "no-store" | {
6
6
  revalidate: number;
7
7
  tags?: string[];
@@ -83,6 +83,52 @@ export declare function createChannelClient(options: CreateChannelClientOptions)
83
83
  readonly blog: {
84
84
  readonly get: (slug: string) => Promise<BlogPostResponse>;
85
85
  };
86
+ readonly auth: {
87
+ readonly check: (email: string) => Promise<{
88
+ exists: boolean;
89
+ }>;
90
+ readonly signup: (input: {
91
+ email: string;
92
+ name: string;
93
+ phone?: string;
94
+ }) => Promise<CustomerSignupResponse>;
95
+ readonly sendCode: (email: string) => Promise<SendCodeResponse>;
96
+ readonly verifyCode: (input: {
97
+ email: string;
98
+ code: string;
99
+ }) => Promise<CustomerSession>;
100
+ readonly refresh: (refreshToken: string) => Promise<CustomerSession>;
101
+ };
102
+ /**
103
+ * Scope calls to a signed-in customer.
104
+ *
105
+ * The session is passed here rather than stored on the client, so it cannot
106
+ * leak between requests: on a server rendering for many visitors at once, a
107
+ * mutable "current customer" is a cross-customer data leak waiting to
108
+ * happen. Each request carries the session it was given, or none.
109
+ *
110
+ * Orders are scoped server-side to this customer's own email within the
111
+ * channel's workspace — another customer's order id returns 404.
112
+ */
113
+ readonly withCustomer: (session: string) => {
114
+ readonly me: () => Promise<CustomerResponse>;
115
+ readonly updateProfile: (input: {
116
+ name?: string;
117
+ phone?: string;
118
+ }) => Promise<CustomerResponse>;
119
+ readonly logout: () => Promise<{
120
+ status?: string;
121
+ }>;
122
+ readonly orders: {
123
+ readonly list: (params?: ChannelListParams) => Promise<ListResponse<Order>>;
124
+ readonly summary: () => Promise<{
125
+ summary: OrderSummary;
126
+ }>;
127
+ readonly get: (orderId: string) => Promise<{
128
+ order: Order;
129
+ }>;
130
+ };
131
+ };
86
132
  readonly leads: {
87
133
  readonly create: (input: ChannelLeadInput, mutation?: ChannelMutationOptions) => Promise<{
88
134
  lead: LeadResponse;
package/dist/index.js CHANGED
@@ -69,14 +69,24 @@ export function createChannelClient(options) {
69
69
  }
70
70
  const retryAttempts = configuredRetryAttempts;
71
71
  const maxRetryDelayMs = positiveNumber(options.retry === false ? 2_000 : options.retry?.maxDelayMs ?? 2_000, "retry.maxDelayMs");
72
- async function request(path, init = {}) {
72
+ async function request(path, init = {}, session) {
73
73
  const method = (init.method ?? "GET").toUpperCase();
74
74
  const headers = new Headers(init.headers);
75
+ // The channel token authenticates the APP. A customer is a SECOND,
76
+ // separate credential — Authorization is already spoken for, so the
77
+ // customer's session rides in its own header.
75
78
  headers.set("Authorization", `Bearer ${token}`);
79
+ if (session)
80
+ headers.set("X-End-User-Token", session);
76
81
  if (init.body !== undefined && !headers.has("Content-Type"))
77
82
  headers.set("Content-Type", "application/json");
78
83
  const requestInit = { ...init, method, headers };
79
- if (method === "GET" && cachePolicy !== "no-store") {
84
+ // A customer-scoped read is NEVER cached, whatever cache policy the client
85
+ // was built with. These responses belong to one signed-in person: caching
86
+ // `/account/orders` under a shared revalidate+tag would serve one customer's
87
+ // orders from another's render. The guarantee lives here, in the library, so
88
+ // an app cannot lose it by constructing the client the obvious way.
89
+ if (method === "GET" && !session && cachePolicy !== "no-store") {
80
90
  requestInit.next = { revalidate: cachePolicy.revalidate, ...(cachePolicy.tags ? { tags: cachePolicy.tags } : {}) };
81
91
  }
82
92
  else {
@@ -158,6 +168,38 @@ export function createChannelClient(options) {
158
168
  blog: {
159
169
  get: (slug) => request(`/blog/posts/${encodePath(slug)}`),
160
170
  },
171
+ // Customer sign-in. These are anonymous calls — they CREATE a session.
172
+ auth: {
173
+ check: (email) => request("/auth/check", { method: "POST", body: JSON.stringify({ email }) }),
174
+ signup: (input) => request("/auth/signup", { method: "POST", body: JSON.stringify(input) }),
175
+ sendCode: (email) => request("/auth/send-code", { method: "POST", body: JSON.stringify({ email }) }),
176
+ verifyCode: (input) => request("/auth/verify-code", { method: "POST", body: JSON.stringify(input) }),
177
+ refresh: (refreshToken) => request("/auth/refresh", { method: "POST", body: JSON.stringify({ refresh_token: refreshToken }) }),
178
+ },
179
+ /**
180
+ * Scope calls to a signed-in customer.
181
+ *
182
+ * The session is passed here rather than stored on the client, so it cannot
183
+ * leak between requests: on a server rendering for many visitors at once, a
184
+ * mutable "current customer" is a cross-customer data leak waiting to
185
+ * happen. Each request carries the session it was given, or none.
186
+ *
187
+ * Orders are scoped server-side to this customer's own email within the
188
+ * channel's workspace — another customer's order id returns 404.
189
+ */
190
+ withCustomer(session) {
191
+ const customerSession = required(session, "session");
192
+ return {
193
+ me: () => request("/auth/me", {}, customerSession),
194
+ updateProfile: (input) => request("/auth/me", { method: "PUT", body: JSON.stringify(input) }, customerSession),
195
+ logout: () => request("/auth/logout", { method: "POST" }, customerSession),
196
+ orders: {
197
+ list: (params = {}) => request(appendQuery("/account/orders", params), {}, customerSession),
198
+ summary: () => request("/account/orders/summary", {}, customerSession),
199
+ get: (orderId) => request(`/account/orders/${encodePath(orderId)}`, {}, customerSession),
200
+ },
201
+ };
202
+ },
161
203
  leads: {
162
204
  create: (input, mutation) => request("/leads", {
163
205
  method: "POST", headers: mutationHeaders(mutation), body: JSON.stringify(input),
package/dist/types.d.ts CHANGED
@@ -222,3 +222,46 @@ export interface BlogPostResponse {
222
222
  export interface ThemeResponse {
223
223
  theme: Record<string, unknown> | null;
224
224
  }
225
+ export interface Customer {
226
+ id: string;
227
+ email: string;
228
+ name: string;
229
+ email_verified?: boolean;
230
+ is_active?: boolean;
231
+ [key: string]: unknown;
232
+ }
233
+ /** Returned by verify-code and refresh. `access_token` is the session. */
234
+ export interface CustomerSession {
235
+ access_token: string;
236
+ refresh_token: string;
237
+ token_type: string;
238
+ expires_at: string;
239
+ end_user: Customer;
240
+ }
241
+ export interface CustomerSignupResponse {
242
+ end_user: Customer;
243
+ created: boolean;
244
+ requires_email_verification: boolean;
245
+ }
246
+ export interface SendCodeResponse {
247
+ status: string;
248
+ purpose: string;
249
+ }
250
+ export interface CustomerResponse {
251
+ end_user: Customer;
252
+ }
253
+ export interface Order {
254
+ id: string;
255
+ order_number: string;
256
+ status: string;
257
+ payment_status: string;
258
+ currency: string;
259
+ total_cents: number;
260
+ created_at: string;
261
+ [key: string]: unknown;
262
+ }
263
+ export interface OrderSummary {
264
+ base_currency: string;
265
+ total_orders: number;
266
+ [key: string]: unknown;
267
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c1m-public/channel-client",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Server-only TypeScript client for the MML headless Channel API",
@@ -12,9 +12,16 @@
12
12
  "default": "./dist/index.js"
13
13
  }
14
14
  },
15
- "files": ["dist", "README.md"],
16
- "engines": { "node": ">=20" },
17
- "publishConfig": { "access": "public" },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
18
25
  "scripts": {
19
26
  "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
20
27
  "build": "pnpm clean && tsc -p tsconfig.build.json",
@@ -23,7 +30,9 @@
23
30
  "test:run": "vitest run",
24
31
  "type-check": "tsc -p tsconfig.json --noEmit"
25
32
  },
26
- "dependencies": { "server-only": "0.0.1" },
33
+ "dependencies": {
34
+ "server-only": "0.0.1"
35
+ },
27
36
  "devDependencies": {
28
37
  "typescript": "5.9.3",
29
38
  "vitest": "^4.1.4"