@asstio-dev/storefront 0.46.0 → 0.48.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/README.md +28 -2
- package/dist/account/browser.d.ts +65 -3
- package/dist/account/browser.js +79 -5
- package/dist/account/cookies.d.ts +10 -0
- package/dist/account/cookies.js +7 -0
- package/dist/account/index.d.ts +7 -1
- package/dist/account/index.js +9 -8
- package/dist/account/next.d.ts +123 -2
- package/dist/account/next.js +289 -4
- package/dist/analytics/events.d.ts +8 -2
- package/dist/analytics/events.js +7 -2
- package/dist/cart-codes.d.ts +38 -0
- package/dist/cart-codes.js +28 -0
- package/dist/consent/codec.d.ts +141 -0
- package/dist/consent/codec.js +239 -0
- package/dist/consent/coordinator.d.ts +107 -0
- package/dist/consent/coordinator.js +608 -0
- package/dist/consent/index.d.ts +8 -0
- package/dist/consent/index.js +8 -0
- package/dist/consent/notice.d.ts +10 -0
- package/dist/consent/notice.js +11 -0
- package/dist/consent/server.d.ts +36 -0
- package/dist/consent/server.js +45 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/schema.d.ts +3706 -428
- package/dist/shopper/index.d.ts +54 -0
- package/dist/shopper/index.js +36 -0
- package/package.json +17 -3
- package/src/schema.d.ts +3706 -428
package/README.md
CHANGED
|
@@ -368,8 +368,8 @@ hreflang sets are only as reciprocal as the API's `alternates`; the SDK renders
|
|
|
368
368
|
|
|
369
369
|
`trackSearchEvents(client, events, { consent })` posts search exposures, product clicks and add-to-carts to
|
|
370
370
|
`POST /v1/events`, for measuring search quality. It sends **nothing** unless `consent === true`: the storefront stores
|
|
371
|
-
no PII and cannot verify consent, so the frontend decides
|
|
372
|
-
|
|
371
|
+
no PII and cannot verify consent, so the frontend decides (`coordinator.effective().measurement`, see "Favorites and
|
|
372
|
+
consent"). `sessionId` is deprecated: the API still accepts it and discards it, and the SDK issues none.
|
|
373
373
|
|
|
374
374
|
```ts
|
|
375
375
|
const exposure = { type: "search_exposure", occurredAt: new Date().toISOString(), resultId: listing.search!.resultId, query, page: 1, productIds };
|
|
@@ -789,6 +789,32 @@ export async function beginSignedInCheckout(savedCart: string) {
|
|
|
789
789
|
}
|
|
790
790
|
```
|
|
791
791
|
|
|
792
|
+
### Favorites, stock watches and consent
|
|
793
|
+
|
|
794
|
+
Guest favorites, stock watches and the device's consent live in five entries (shopper-state spec):
|
|
795
|
+
|
|
796
|
+
- `@asstio-dev/storefront/account/next` — `shopperActions(config)`: favorites, stock watches (`watches.create`, `list`,
|
|
797
|
+
`cancel(id)`, `stopAll()` — the last one signed in only), the shopper's own state (read, erase), consent (read, history,
|
|
798
|
+
put) and `adopt()`. Signed in they use `/v1/me/*`, as a guest the `/v1/shopper/*` relay. A
|
|
799
|
+
guest's first write mints a shopper token into the HttpOnly `__Host-sf_shopper` cookie; no result ever carries it.
|
|
800
|
+
Node runtime only: the module loads `node:crypto`.
|
|
801
|
+
- `@asstio-dev/storefront/account/browser` — `withShopperLock(actions)`: wrap your `"use server"` shopper actions in
|
|
802
|
+
the browser so tabs never race the token cookie (two first adds would mint two tokens; a late answer could renew an
|
|
803
|
+
erased token). Wrap your sign-out action too, and call `coordinator.beforeSignOut()` before it, outside the lock.
|
|
804
|
+
Each action holds the lock until it settles. Without Web Locks they run unserialized. An action's `shopper.owner`
|
|
805
|
+
is `null` when the account lookup failed: keep your current owner (`coordinator.setOwner(null)` ignores it).
|
|
806
|
+
- `@asstio-dev/storefront/consent` — `createConsentCoordinator({ site, owner, transport })`, the browser's one writer of
|
|
807
|
+
the consent cookies: a withdrawal takes effect at once, a grant only after the server recorded it. Its transport is
|
|
808
|
+
`{ put: locked.consent.put }`. Gate every measurement or personalization on `coordinator.effective()`.
|
|
809
|
+
- `@asstio-dev/storefront/consent/server` — `readConsentCookie(cookies)` (the same answer for SSR) and
|
|
810
|
+
`consentOwner(cookies, session)`.
|
|
811
|
+
- `@asstio-dev/storefront/shopper` — the watch types `ShopperWatch` (owner projection) and `RecipientWatch`, the union
|
|
812
|
+
`Watch` narrowed by `projection`, and `cancelWatchByToken(client, token, "watch" | "all", { shopperIp? })` for the mail's
|
|
813
|
+
cancel page. In the browser pass the publishable-key client from `createStorefrontClient`; on the server pass a
|
|
814
|
+
server-key client and the shopper's IP (`createShopperClient({ serverKey, shopperIp })`, or `{ shopperIp }` here), so the
|
|
815
|
+
rate limit is the shopper's and never one bucket for everyone behind your server. It never sends a session or shopper
|
|
816
|
+
token, and the API answers `204` whatever the token is, so show a fixed text.
|
|
817
|
+
|
|
792
818
|
## Headers
|
|
793
819
|
|
|
794
820
|
The client sets `X-Site-Key` and the context it was built with: `X-Market`, `X-Country` and `X-Locale`, from `market`,
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@asstio-dev/storefront/account/browser` — the
|
|
3
|
-
* travels in the URL fragment, so no access log or mail scanner
|
|
4
|
-
* once, strips it from the address bar, and posts it through a server action.
|
|
2
|
+
* `@asstio-dev/storefront/account/browser` — the browser-side pieces of accounts and the shopper token:
|
|
3
|
+
* - `readLinkFragment` (accounts spec §6.2): the sign-in link's secret travels in the URL fragment, so no access log or mail scanner
|
|
4
|
+
* sees it. The landing page's client component reads it once, strips it from the address bar, and posts it through a server action.
|
|
5
|
+
* - `withShopperLock`: serializes the shopper-token server actions across tabs (shopper-state S1).
|
|
5
6
|
*/
|
|
7
|
+
import type { ShopperActions, SignOutResult } from "./next.js";
|
|
6
8
|
/** The parts of `window` this module touches (a fake in tests). */
|
|
7
9
|
export interface LinkWindow {
|
|
8
10
|
location: {
|
|
@@ -20,3 +22,63 @@ export interface LinkWindow {
|
|
|
20
22
|
* a reload, a shared screenshot or a second call never sees it again. Any other fragment is left alone.
|
|
21
23
|
*/
|
|
22
24
|
export declare function readLinkFragment(win?: LinkWindow | undefined): string | null;
|
|
25
|
+
/** The Web Lock that serializes shopper-token actions across this origin's tabs. Not `sf-consent` (see `withShopperLock`). */
|
|
26
|
+
export declare const SHOPPER_LOCK = "sf-shopper";
|
|
27
|
+
type Actions = ShopperActions;
|
|
28
|
+
type ConsentPut = Actions["consent"]["put"];
|
|
29
|
+
/**
|
|
30
|
+
* The frontend's own `"use server"` wrappers around `shopperActions(config)` (any subset, same signatures). Server actions cannot be
|
|
31
|
+
* nested in an object handed to the browser, so the page builds this object from its imported action functions.
|
|
32
|
+
*/
|
|
33
|
+
export type ShopperActionsInput = {
|
|
34
|
+
favorites?: Partial<Actions["favorites"]>;
|
|
35
|
+
shopperState?: Partial<Actions["shopperState"]>;
|
|
36
|
+
consent?: Partial<Actions["consent"]>;
|
|
37
|
+
adopt?: Actions["adopt"];
|
|
38
|
+
owner?: Actions["owner"];
|
|
39
|
+
/** Your wrapper around `signOutAction(config, opts)`: it clears the shopper cookie too, so it runs under the lock. */
|
|
40
|
+
signOut?: (opts?: {
|
|
41
|
+
everywhere?: boolean;
|
|
42
|
+
}) => Promise<SignOutResult>;
|
|
43
|
+
};
|
|
44
|
+
/** `consent.put` through the lock: usable as the consent coordinator's `ConsentTransport.put`; `signal` is not sent to the server. */
|
|
45
|
+
export type LockedConsentPut = (body: Parameters<ConsentPut>[0], owner: string, opts?: {
|
|
46
|
+
mayMint?: boolean;
|
|
47
|
+
signal?: AbortSignal;
|
|
48
|
+
}) => ReturnType<ConsentPut>;
|
|
49
|
+
export type WithShopperLock<A> = {
|
|
50
|
+
[K in keyof A]: K extends "consent" ? {
|
|
51
|
+
[M in keyof A[K]]: M extends "put" ? LockedConsentPut : A[K][M];
|
|
52
|
+
} : A[K];
|
|
53
|
+
};
|
|
54
|
+
export type ShopperLockOptions = {
|
|
55
|
+
/** Defaults to `navigator.locks`; null = no Web Locks (the actions run unserialized). */
|
|
56
|
+
locks?: LockManager | null;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Runs every shopper action that can mint, renew, replace or clear the HttpOnly shopper-token cookie inside the exclusive
|
|
60
|
+
* `sf-shopper` Web Lock, one at a time across this origin's tabs: `favorites.*`, `shopperState.*`, `consent.read`/`history` and
|
|
61
|
+
* `consent.put` for a guest owner (`t.…` or `none`; an `a.…` put never touches the shopper cookie and runs unlocked), `adopt` and
|
|
62
|
+
* `signOut`. `owner()` runs as given.
|
|
63
|
+
*
|
|
64
|
+
* Why: a server action sees only the cookies its request carried, and the browser applies its `Set-Cookie` when the response
|
|
65
|
+
* arrives. Unserialized, two tabs' first adds both mint (one list becomes unreachable), and a delayed answer for an erased token can
|
|
66
|
+
* renew it over its replacement or clear the replacement. Under the lock the next action starts only after the previous one's answer
|
|
67
|
+
* (and its cookie) has arrived, so it reuses a minted token and never races an erasure or a sign-out.
|
|
68
|
+
*
|
|
69
|
+
* - **Held until settled.** The lock is released only when the action's promise settles (by then its `Set-Cookie` has been applied),
|
|
70
|
+
* however long that takes: releasing earlier would let a late answer renew an erased token over its replacement (review 2 #1). A
|
|
71
|
+
* caller may stop waiting on its own (the consent coordinator's 30 s timeout does); the action keeps the lock until it settles.
|
|
72
|
+
* - **Sign-out.** `await coordinator.beforeSignOut()` first, **outside** the lock (its replays go through `consent.put`, which takes
|
|
73
|
+
* `sf-shopper` itself), then `await locked.signOut()`. Never call `beforeSignOut` from inside a wrapped action.
|
|
74
|
+
* - **Lock order.** `sf-shopper` callbacks run one server action (network) and never request `sf-consent`; the consent coordinator's
|
|
75
|
+
* `sf-consent` callbacks do cookie I/O only and never request `sf-shopper` (it sends outside its lock). Never nest the two: call
|
|
76
|
+
* coordinator methods after a wrapped action resolves, not inside one. So the two locks cannot deadlock.
|
|
77
|
+
* - **Consent transport.** Pass `{ put: locked.consent.put }` as the coordinator's transport: the coordinator's `signal` aborts the
|
|
78
|
+
* wait for the lock at its timeout (the put then never runs) and is not forwarded to the server action; once the put runs, the
|
|
79
|
+
* signal no longer releases anything.
|
|
80
|
+
* - **Residual.** Without Web Locks (or when a lock request is rejected) the actions run unserialized, as before. A server action
|
|
81
|
+
* that never settles holds the lock for the page's life (the tab closing releases it).
|
|
82
|
+
*/
|
|
83
|
+
export declare function withShopperLock<A extends ShopperActionsInput>(actions: A, opts?: ShopperLockOptions): WithShopperLock<A>;
|
|
84
|
+
export {};
|
package/dist/account/browser.js
CHANGED
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `@asstio-dev/storefront/account/browser` — the one browser-side piece of sign-in (accounts spec §6.2): the link's secret
|
|
3
|
-
* travels in the URL fragment, so no access log or mail scanner sees it. The landing page's client component reads it
|
|
4
|
-
* once, strips it from the address bar, and posts it through a server action.
|
|
5
|
-
*/
|
|
6
1
|
const PREFIX = "#sfl_";
|
|
7
2
|
/**
|
|
8
3
|
* The link token `sfl_{challengeId}.{secret}` from `location.hash`, or null; pass it as `link` (it carries its challenge id). The fragment is removed with `history.replaceState` before returning, so
|
|
@@ -17,3 +12,82 @@ export function readLinkFragment(win = globalThis.window) {
|
|
|
17
12
|
win.history.replaceState(win.history.state, "", win.location.pathname + win.location.search);
|
|
18
13
|
return hash.slice(1);
|
|
19
14
|
}
|
|
15
|
+
// ---- the shopper token's lifecycle across tabs (shopper-state S1, Codex code review 1 #3) --------------------------------------
|
|
16
|
+
/** The Web Lock that serializes shopper-token actions across this origin's tabs. Not `sf-consent` (see `withShopperLock`). */
|
|
17
|
+
export const SHOPPER_LOCK = "sf-shopper";
|
|
18
|
+
/**
|
|
19
|
+
* Runs every shopper action that can mint, renew, replace or clear the HttpOnly shopper-token cookie inside the exclusive
|
|
20
|
+
* `sf-shopper` Web Lock, one at a time across this origin's tabs: `favorites.*`, `shopperState.*`, `consent.read`/`history` and
|
|
21
|
+
* `consent.put` for a guest owner (`t.…` or `none`; an `a.…` put never touches the shopper cookie and runs unlocked), `adopt` and
|
|
22
|
+
* `signOut`. `owner()` runs as given.
|
|
23
|
+
*
|
|
24
|
+
* Why: a server action sees only the cookies its request carried, and the browser applies its `Set-Cookie` when the response
|
|
25
|
+
* arrives. Unserialized, two tabs' first adds both mint (one list becomes unreachable), and a delayed answer for an erased token can
|
|
26
|
+
* renew it over its replacement or clear the replacement. Under the lock the next action starts only after the previous one's answer
|
|
27
|
+
* (and its cookie) has arrived, so it reuses a minted token and never races an erasure or a sign-out.
|
|
28
|
+
*
|
|
29
|
+
* - **Held until settled.** The lock is released only when the action's promise settles (by then its `Set-Cookie` has been applied),
|
|
30
|
+
* however long that takes: releasing earlier would let a late answer renew an erased token over its replacement (review 2 #1). A
|
|
31
|
+
* caller may stop waiting on its own (the consent coordinator's 30 s timeout does); the action keeps the lock until it settles.
|
|
32
|
+
* - **Sign-out.** `await coordinator.beforeSignOut()` first, **outside** the lock (its replays go through `consent.put`, which takes
|
|
33
|
+
* `sf-shopper` itself), then `await locked.signOut()`. Never call `beforeSignOut` from inside a wrapped action.
|
|
34
|
+
* - **Lock order.** `sf-shopper` callbacks run one server action (network) and never request `sf-consent`; the consent coordinator's
|
|
35
|
+
* `sf-consent` callbacks do cookie I/O only and never request `sf-shopper` (it sends outside its lock). Never nest the two: call
|
|
36
|
+
* coordinator methods after a wrapped action resolves, not inside one. So the two locks cannot deadlock.
|
|
37
|
+
* - **Consent transport.** Pass `{ put: locked.consent.put }` as the coordinator's transport: the coordinator's `signal` aborts the
|
|
38
|
+
* wait for the lock at its timeout (the put then never runs) and is not forwarded to the server action; once the put runs, the
|
|
39
|
+
* signal no longer releases anything.
|
|
40
|
+
* - **Residual.** Without Web Locks (or when a lock request is rejected) the actions run unserialized, as before. A server action
|
|
41
|
+
* that never settles holds the lock for the page's life (the tab closing releases it).
|
|
42
|
+
*/
|
|
43
|
+
export function withShopperLock(actions, opts = {}) {
|
|
44
|
+
const locks = opts.locks !== undefined ? opts.locks : (globalThis.navigator?.locks ?? null);
|
|
45
|
+
const run = (fn, signal) => {
|
|
46
|
+
if (!locks)
|
|
47
|
+
return Promise.resolve().then(fn);
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
let entered = false;
|
|
50
|
+
locks.request(SHOPPER_LOCK, signal ? { mode: "exclusive", signal } : { mode: "exclusive" }, () => {
|
|
51
|
+
entered = true;
|
|
52
|
+
const action = Promise.resolve().then(fn);
|
|
53
|
+
action.then(resolve, reject);
|
|
54
|
+
// Held until the answer (and its Set-Cookie) has arrived: never released earlier.
|
|
55
|
+
return action.then(() => { }, () => { });
|
|
56
|
+
}).catch((error) => {
|
|
57
|
+
if (entered)
|
|
58
|
+
return;
|
|
59
|
+
if (signal?.aborted)
|
|
60
|
+
reject(signal.reason ?? error);
|
|
61
|
+
else
|
|
62
|
+
Promise.resolve().then(fn).then(resolve, reject); // a rejected lock request: unserialized, as without Web Locks
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
const wrap = (f) => f && ((...args) => run(() => f(...args)));
|
|
67
|
+
const group = (g) => g && Object.fromEntries(Object.entries(g).map(([k, f]) => [k, wrap(f)]));
|
|
68
|
+
const out = { ...actions };
|
|
69
|
+
if (actions.favorites)
|
|
70
|
+
out.favorites = group(actions.favorites);
|
|
71
|
+
if (actions.shopperState)
|
|
72
|
+
out.shopperState = group(actions.shopperState);
|
|
73
|
+
if (actions.adopt)
|
|
74
|
+
out.adopt = wrap(actions.adopt);
|
|
75
|
+
if (actions.signOut)
|
|
76
|
+
out.signOut = wrap(actions.signOut);
|
|
77
|
+
if (actions.consent) {
|
|
78
|
+
const consent = { ...actions.consent, read: wrap(actions.consent.read), history: wrap(actions.consent.history) };
|
|
79
|
+
const put = actions.consent.put;
|
|
80
|
+
if (put) {
|
|
81
|
+
const locked = (body, owner, o = {}) => {
|
|
82
|
+
const call = () => put(body, owner, o.mayMint === undefined ? {} : { mayMint: o.mayMint });
|
|
83
|
+
return owner.startsWith("a.") ? call() : run(call, o.signal);
|
|
84
|
+
};
|
|
85
|
+
consent.put = locked;
|
|
86
|
+
}
|
|
87
|
+
for (const k of Object.keys(consent))
|
|
88
|
+
if (consent[k] === undefined)
|
|
89
|
+
delete consent[k];
|
|
90
|
+
out.consent = consent;
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
@@ -59,6 +59,16 @@ interface BrowserCartCookie {
|
|
|
59
59
|
cookieName(opts: CookieSecurity): string;
|
|
60
60
|
}
|
|
61
61
|
export declare const browserCartCookie: BrowserCartCookie;
|
|
62
|
+
interface ShopperCookie {
|
|
63
|
+
/**
|
|
64
|
+
* The guest shopper token (`sft_…`, shopper-state spec §4.2, §9.4): HttpOnly, 12 months, set from a minting answer and re-set
|
|
65
|
+
* (renewed) by every other successful guest write. It identifies the shopper's own favorites and consent record and nothing else.
|
|
66
|
+
*/
|
|
67
|
+
(token: string, opts: CookieSecurity): CookieSpec;
|
|
68
|
+
clear(opts: CookieSecurity): CookieSpec;
|
|
69
|
+
cookieName(opts: CookieSecurity): string;
|
|
70
|
+
}
|
|
71
|
+
export declare const shopperCookie: ShopperCookie;
|
|
62
72
|
/** A `Set-Cookie` header value for a route handler or middleware. */
|
|
63
73
|
export declare function serializeCookie(c: CookieSpec): string;
|
|
64
74
|
export {};
|
package/dist/account/cookies.js
CHANGED
|
@@ -12,6 +12,9 @@ const BROWSER_CART = "sf_browser_cart";
|
|
|
12
12
|
const BROWSER_CART_SECONDS = 1800;
|
|
13
13
|
/** A cart's sliding expiry on the API: 30 days after its last change. */
|
|
14
14
|
const CART_SECONDS = 30 * 24 * 3600;
|
|
15
|
+
const SHOPPER = "sf_shopper";
|
|
16
|
+
/** Shopper-state spec §4.2: the guest shopper token lives 12 months after its last write. */
|
|
17
|
+
const SHOPPER_SECONDS = 365 * 24 * 3600;
|
|
15
18
|
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
16
19
|
/** The cookie security of the frontend's own origin: `{ secure: false }` only for `http://localhost` (and its loopback forms). */
|
|
17
20
|
export function cookieSecurity(origin) {
|
|
@@ -50,6 +53,10 @@ export const browserCartCookie = Object.assign((token, opts) => spec(named(BROWS
|
|
|
50
53
|
clear: (opts) => spec(named(BROWSER_CART, opts), "", 0, opts),
|
|
51
54
|
cookieName: (opts) => named(BROWSER_CART, opts),
|
|
52
55
|
});
|
|
56
|
+
export const shopperCookie = Object.assign((token, opts) => spec(named(SHOPPER, opts), token, SHOPPER_SECONDS, opts), {
|
|
57
|
+
clear: (opts) => spec(named(SHOPPER, opts), "", 0, opts),
|
|
58
|
+
cookieName: (opts) => named(SHOPPER, opts),
|
|
59
|
+
});
|
|
53
60
|
/** A `Set-Cookie` header value for a route handler or middleware. */
|
|
54
61
|
export function serializeCookie(c) {
|
|
55
62
|
return `${c.name}=${encodeURIComponent(c.value)}; Path=${c.path}; Max-Age=${c.maxAge}; HttpOnly${c.secure ? "; Secure" : ""}; SameSite=Lax`;
|
package/dist/account/index.d.ts
CHANGED
|
@@ -92,6 +92,12 @@ export declare function getSession(client: ShopperClient): Promise<AccountResult
|
|
|
92
92
|
export declare function getMe(client: ShopperClient): Promise<AccountResult<AccountDto>>;
|
|
93
93
|
/** `GET /v1/me/company`: `403 PRINCIPAL_NOT_AVAILABLE` while the principal is the consumer. */
|
|
94
94
|
export declare function getMyCompany(client: ShopperClient): Promise<AccountResult<MyCompanyDto>>;
|
|
95
|
+
/** An openapi-fetch answer in the repo's result shape: the data of a 2xx with a body, else the status and the problem. */
|
|
96
|
+
export declare function accountResult<T>(r: {
|
|
97
|
+
data?: T;
|
|
98
|
+
error?: unknown;
|
|
99
|
+
response: Response;
|
|
100
|
+
}): AccountResult<T>;
|
|
95
101
|
export { cartTotals, copyBrowserCart, copyKey, CopyBrowserCartError, type CartTotals, type CopyBrowserCartResult } from "./cart.js";
|
|
96
|
-
export { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, signInCookie, type CookieSecurity, type CookieSpec, type SignInCookieValue, } from "./cookies.js";
|
|
102
|
+
export { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, shopperCookie, signInCookie, type CookieSecurity, type CookieSpec, type SignInCookieValue, } from "./cookies.js";
|
|
97
103
|
export { assertSameOrigin, CrossOriginError, safeReturnPath, shopperIpFrom, type HeadersLike } from "./security.js";
|
package/dist/account/index.js
CHANGED
|
@@ -39,7 +39,7 @@ export function createShopperClient(opts) {
|
|
|
39
39
|
/** `POST /v1/auth/sign-in`. The 202 is the same whether or not the address may sign in; keep `binding` in the sign-in cookie
|
|
40
40
|
* (`signInCookie`) and never show it. An unsafe `returnPath` is dropped by the API. */
|
|
41
41
|
export async function startSignIn(client, email, returnPath) {
|
|
42
|
-
return
|
|
42
|
+
return accountResult(await client.POST("/v1/auth/sign-in", { body: { email, returnPath: returnPath ?? null } }));
|
|
43
43
|
}
|
|
44
44
|
/** The link token of a whole sign-in URL or a bare token: the part after the last '#', as the API reads it. */
|
|
45
45
|
export function linkToken(link) {
|
|
@@ -65,7 +65,7 @@ export async function verifySignIn(client, input, cartToken) {
|
|
|
65
65
|
const challengeId = input.link ? linkChallengeId(input.link) : input.challengeId || null;
|
|
66
66
|
if (!input.link && !challengeId)
|
|
67
67
|
return localFailure("SIGN_IN_CHALLENGE_MISSING", "A code needs the challenge id of its sign-in start.");
|
|
68
|
-
return
|
|
68
|
+
return accountResult(await client.POST("/v1/auth/sign-in/verify", {
|
|
69
69
|
body: { challengeId, code: input.code ?? null, link: input.link ? linkToken(input.link) : null, binding: input.binding ?? null, confirm: input.confirm ?? null },
|
|
70
70
|
headers: cartToken ? { "X-Cart-Token": cartToken } : {},
|
|
71
71
|
}));
|
|
@@ -79,21 +79,22 @@ export async function signOut(client, opts = {}) {
|
|
|
79
79
|
}
|
|
80
80
|
/** `PUT /v1/session/principal`: `"consumer"` or a membership id. The answer carries a rotated token: store it at once. */
|
|
81
81
|
export async function switchPrincipal(client, principal) {
|
|
82
|
-
return
|
|
82
|
+
return accountResult(await client.PUT("/v1/session/principal", { body: { principal } }));
|
|
83
83
|
}
|
|
84
84
|
/** `GET /v1/session`. `401 SESSION_INVALID` means signed out: render so, and clear the cookie in the next action. */
|
|
85
85
|
export async function getSession(client) {
|
|
86
|
-
return
|
|
86
|
+
return accountResult(await client.GET("/v1/session"));
|
|
87
87
|
}
|
|
88
88
|
/** `GET /v1/me`. */
|
|
89
89
|
export async function getMe(client) {
|
|
90
|
-
return
|
|
90
|
+
return accountResult(await client.GET("/v1/me"));
|
|
91
91
|
}
|
|
92
92
|
/** `GET /v1/me/company`: `403 PRINCIPAL_NOT_AVAILABLE` while the principal is the consumer. */
|
|
93
93
|
export async function getMyCompany(client) {
|
|
94
|
-
return
|
|
94
|
+
return accountResult(await client.GET("/v1/me/company"));
|
|
95
95
|
}
|
|
96
|
-
|
|
96
|
+
/** An openapi-fetch answer in the repo's result shape: the data of a 2xx with a body, else the status and the problem. */
|
|
97
|
+
export function accountResult(r) {
|
|
97
98
|
if (r.response.ok && r.data !== undefined && r.data !== null && r.error === undefined)
|
|
98
99
|
return { ok: true, data: r.data };
|
|
99
100
|
return failure(r.response, r.error);
|
|
@@ -111,5 +112,5 @@ function isProblem(value) {
|
|
|
111
112
|
return typeof value === "object" && value !== null && typeof value.code === "string";
|
|
112
113
|
}
|
|
113
114
|
export { cartTotals, copyBrowserCart, copyKey, CopyBrowserCartError } from "./cart.js";
|
|
114
|
-
export { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, signInCookie, } from "./cookies.js";
|
|
115
|
+
export { browserCartCookie, cartCookie, cookieSecurity, readSignInCookie, serializeCookie, sessionCookie, shopperCookie, signInCookie, } from "./cookies.js";
|
|
115
116
|
export { assertSameOrigin, CrossOriginError, safeReturnPath, shopperIpFrom } from "./security.js";
|
package/dist/account/next.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type AccountResult, type PrincipalDto, type ShopperClient } from "./index.js";
|
|
2
|
+
import type { components } from "../schema";
|
|
2
3
|
import type { CommerceContextOptions } from "../context.js";
|
|
3
4
|
import { type CopyBrowserCartResult } from "./cart.js";
|
|
5
|
+
import type { CreateWatchInput, WatchAnswer, WatchList } from "../shopper/index.js";
|
|
4
6
|
export type AccountActionConfig = {
|
|
5
7
|
/** e.g. https://api.storefront.asstio.com */
|
|
6
8
|
baseUrl: string;
|
|
@@ -80,8 +82,10 @@ export declare function verifySignInAction(config: AccountActionConfig, input: V
|
|
|
80
82
|
*/
|
|
81
83
|
export declare function switchPrincipalAction(config: AccountActionConfig, principal: string): Promise<SessionTransition<SignedInView>>;
|
|
82
84
|
/**
|
|
83
|
-
* Signs out (`everywhere` ends every session of the account). The session cookie, the sign-in cookie, the cart cookie
|
|
84
|
-
* browser-cart cookie
|
|
85
|
+
* Signs out (`everywhere` ends every session of the account). The session cookie, the sign-in cookie, the cart cookie, the
|
|
86
|
+
* browser-cart cookie and the guest shopper cookie (`__Host-sf_shopper`) are cleared whatever the API answered; the consent cookies
|
|
87
|
+
* are the browser's and stay (shopper-state spec §7.4: they survive sign-in and sign-out). Replay a pending consent withdrawal for
|
|
88
|
+
* the shopper token before calling this (S36). The cookies are cleared and also when it cannot be reached (`{ ok: false, status: 0, problem.code: "NETWORK" }`)
|
|
85
89
|
* — a session already gone is still a sign-out for this browser. So every answer says `dropPrivateData: true`.
|
|
86
90
|
*/
|
|
87
91
|
export declare function signOutAction(config: AccountActionConfig, opts?: {
|
|
@@ -98,3 +102,120 @@ export declare function copyBrowserCartAction(config: AccountActionConfig): Prom
|
|
|
98
102
|
* sets a cookie: a render cannot.
|
|
99
103
|
*/
|
|
100
104
|
export declare function shopperClient(config: AccountActionConfig): Promise<ShopperClient>;
|
|
105
|
+
type Schemas = components["schemas"];
|
|
106
|
+
export type FavoritesDto = Schemas["FavoritesDto"];
|
|
107
|
+
export type FavoriteItemAnswerDto = Schemas["FavoriteItemAnswerDto"];
|
|
108
|
+
export type AddFavoriteRequest = Schemas["AddFavoriteRequest"];
|
|
109
|
+
export type ShopperStateDto = Schemas["ShopperStateDto"];
|
|
110
|
+
export type ConsentPutRequest = Schemas["ConsentPutRequest"];
|
|
111
|
+
export type ConsentAnswerDto = Schemas["ConsentAnswerDto"];
|
|
112
|
+
export type ConsentReadDto = Schemas["ConsentReadDto"];
|
|
113
|
+
export type ConsentHistoryPageDto = Schemas["ConsentHistoryPageDto"];
|
|
114
|
+
export type AdoptionDto = Schemas["AdoptionDto"];
|
|
115
|
+
/**
|
|
116
|
+
* What the browser learns about the shopper token: the consent owner (PL9) and, after a mint, the token's expiry. Never the token.
|
|
117
|
+
* `owner: null` = unresolved (a signed-in write succeeded but the account lookup failed): keep your current owner —
|
|
118
|
+
* `coordinator.setOwner(null)` is a no-op.
|
|
119
|
+
*/
|
|
120
|
+
export type BrowserShopper = {
|
|
121
|
+
owner: string | null;
|
|
122
|
+
expiresAt: string | null;
|
|
123
|
+
};
|
|
124
|
+
/** An answer whose `shopper` member is replaced by the browser-safe projection (PL8): the minted token stays in the HttpOnly cookie. */
|
|
125
|
+
export type ShopperActionResult<T> = AccountResult<Omit<T, "shopper"> & {
|
|
126
|
+
shopper: BrowserShopper;
|
|
127
|
+
}>;
|
|
128
|
+
/** A consent submission whose owner is not this request's credential: nothing was sent (PL9). */
|
|
129
|
+
export type OwnerMismatch = {
|
|
130
|
+
ok: false;
|
|
131
|
+
local: "owner_mismatch";
|
|
132
|
+
};
|
|
133
|
+
export type ConsentPutResult = ShopperActionResult<ConsentAnswerDto> | OwnerMismatch;
|
|
134
|
+
/** `GET /v1/shopper`, or `{ shopper: null }` when this browser holds no shopper token (no request is made). */
|
|
135
|
+
export type ShopperStateView = ShopperStateDto | {
|
|
136
|
+
shopper: null;
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Server actions for favorites, stock watches, the shopper's own state and consent (shopper-state spec §4.2, §5, §6, §7.4, §9.4; PL8, PL9). Call them
|
|
140
|
+
* from your own `"use server"` actions. Signed in (a session cookie) they use `/v1/me/*`; as a guest the session-less `/v1/shopper/*`
|
|
141
|
+
* relay with the server key and `X-Shopper-Ip`. The guest token lives only in `__Host-sf_shopper` (HttpOnly, 12 months): a minting
|
|
142
|
+
* answer sets it, every other successful guest write renews it, `SHOPPER_TOKEN_UNKNOWN`/`SHOPPER_TOKEN_ADOPTED` clear it, and no
|
|
143
|
+
* result ever carries it. The actions never set a consent cookie: the browser coordinator is its one writer.
|
|
144
|
+
*/
|
|
145
|
+
export declare function shopperActions(config: AccountActionConfig): {
|
|
146
|
+
favorites: {
|
|
147
|
+
/** `GET /v1/me/favorites` signed in; `GET /v1/shopper/favorites` as a guest (no token: an empty list, no request). */
|
|
148
|
+
list(): Promise<ShopperActionResult<FavoritesDto>>;
|
|
149
|
+
/** `POST …/favorites/items`; as a guest without a token this mints one (persisted in the cookie, never returned). */
|
|
150
|
+
add(body: AddFavoriteRequest): Promise<ShopperActionResult<FavoriteItemAnswerDto>>;
|
|
151
|
+
/** `DELETE …/favorites/items/{itemId}`; a guest without a token has nothing to remove (no request). */
|
|
152
|
+
remove(itemId: string): Promise<AccountResult<void>>;
|
|
153
|
+
/** `DELETE …/favorites`; a guest without a token has nothing to clear (no request). */
|
|
154
|
+
clear(): Promise<AccountResult<void>>;
|
|
155
|
+
};
|
|
156
|
+
watches: {
|
|
157
|
+
/**
|
|
158
|
+
* `POST /v1/me/watches` signed in (addressed to the account's own e-mail: `email` is not sent), `POST /v1/shopper/watches` as a
|
|
159
|
+
* guest with `email` (a watch asks for a service, so without a token this mints one: persisted in the cookie, never returned).
|
|
160
|
+
* `201` for a new watch, `200` for the caller's open one; `WATCH_NOT_NEEDED` (`409`) means offer add to cart instead.
|
|
161
|
+
*/
|
|
162
|
+
create(input: CreateWatchInput): Promise<ShopperActionResult<WatchAnswer>>;
|
|
163
|
+
/** `GET /v1/me/watches` signed in (recipient or owner projection per watch); `GET /v1/shopper/watches` as a guest (owner
|
|
164
|
+
* projection; no token: an empty list, no request). */
|
|
165
|
+
list(): Promise<AccountResult<WatchList>>;
|
|
166
|
+
/** `DELETE …/watches/{id}` (`204` whether or not there is such a watch); a guest without a token has nothing to cancel (no request). */
|
|
167
|
+
cancel(id: string): Promise<AccountResult<void>>;
|
|
168
|
+
/**
|
|
169
|
+
* `POST /v1/me/watches/stop-all`: stop every watch addressed to the account's own e-mail and watch mail to it for 12 months.
|
|
170
|
+
* Session only (signed out: `SESSION_REQUIRED`, no request). The mail's cancel link is `cancelWatchByToken` in
|
|
171
|
+
* `@asstio-dev/storefront/shopper`, with the publishable key: these actions hold the server key.
|
|
172
|
+
*/
|
|
173
|
+
stopAll(): Promise<AccountResult<void>>;
|
|
174
|
+
};
|
|
175
|
+
shopperState: {
|
|
176
|
+
/**
|
|
177
|
+
* `GET /v1/shopper` with the token, **always on the guest route and without the session** (the "keep my list" prompt reads it
|
|
178
|
+
* while signed in). No token: `{ shopper: null }` without a request.
|
|
179
|
+
*/
|
|
180
|
+
read(): Promise<AccountResult<ShopperStateView>>;
|
|
181
|
+
/**
|
|
182
|
+
* `DELETE /v1/shopper` with the token, always on the guest route and without the session; then the shopper cookie is cleared.
|
|
183
|
+
* `{ erased: true }` tells the page to call `coordinator.erased()`, which clears the consent cookie.
|
|
184
|
+
*/
|
|
185
|
+
erase(): Promise<AccountResult<{
|
|
186
|
+
erased: true;
|
|
187
|
+
}>>;
|
|
188
|
+
};
|
|
189
|
+
consent: {
|
|
190
|
+
/** `GET /v1/me/consents` signed in (feed `coordinator.setAccount(current, true)`), `GET /v1/shopper/consents` as a guest. */
|
|
191
|
+
read(): Promise<AccountResult<ConsentReadDto>>;
|
|
192
|
+
/** A further history page: `GET /v1/me/consents/history` or `GET /v1/shopper/consents/history`. */
|
|
193
|
+
history(cursor?: string): Promise<AccountResult<ConsentHistoryPageDto>>;
|
|
194
|
+
/**
|
|
195
|
+
* Every consent submission (a decision, a re-send, a replay, a compensation) with the owner the coordinator captured for it; the
|
|
196
|
+
* action writes only for that owner, never for "whoever is signed in now" (PL9):
|
|
197
|
+
* - `a.X`: only under a session whose account (`GET /v1/me`) is X → `PUT /v1/me/consents`, no shopper token;
|
|
198
|
+
* - `t.P`: only when `__Host-sf_shopper` holds the token whose hash prefix is P → `PUT /v1/shopper/consents` with it and no
|
|
199
|
+
* session, also while signed in;
|
|
200
|
+
* - `none`: only with `mayMint: true` (a fresh decision) while there is no session and no shopper cookie → the tokenless guest
|
|
201
|
+
* `PUT`, which mints: the token is persisted and the result's `shopper.owner` is the new `t.` owner that binds this decision.
|
|
202
|
+
* Anything else sends nothing: `{ ok: false, local: "owner_mismatch" }`. The action never sets a consent cookie.
|
|
203
|
+
*/
|
|
204
|
+
put(body: ConsentPutRequest, owner: string, opts?: {
|
|
205
|
+
mayMint?: boolean;
|
|
206
|
+
}): Promise<ConsentPutResult>;
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* The "keep my list" action after a sign-in (spec §4.4; never automatic): `POST /v1/me/adopt-shopper-state` with the cookie's token
|
|
210
|
+
* in the body, under the session. `200` clears the shopper cookie (so do `SHOPPER_TOKEN_UNKNOWN`/`SHOPPER_TOKEN_ADOPTED`); the
|
|
211
|
+
* answer's `accountConsent` lets the page ask on the account. No shopper cookie: `null`, no request. Signed out: `SESSION_REQUIRED`.
|
|
212
|
+
*/
|
|
213
|
+
adopt(): Promise<AccountResult<AdoptionDto | null>>;
|
|
214
|
+
/**
|
|
215
|
+
* The consent owner for the coordinator (PL9): `a.<account>` under a session (read with `GET /v1/me`; a `401` counts as signed
|
|
216
|
+
* out), else `t.<sha256 prefix>` when the shopper cookie exists, else `none`.
|
|
217
|
+
*/
|
|
218
|
+
owner(): Promise<AccountResult<string>>;
|
|
219
|
+
};
|
|
220
|
+
export type ShopperActions = ReturnType<typeof shopperActions>;
|
|
221
|
+
export {};
|