@vectoriox/iox-ui 5.98.0 → 5.100.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 (43) hide show
  1. package/actions-core/index.d.ts +7 -4
  2. package/composite-core/index.d.ts +222 -2
  3. package/design-core/index.d.ts +334 -1
  4. package/fesm2022/vectoriox-iox-ui-actions-core.mjs +16 -7
  5. package/fesm2022/vectoriox-iox-ui-actions-core.mjs.map +1 -1
  6. package/fesm2022/vectoriox-iox-ui-composite-core.mjs +948 -256
  7. package/fesm2022/vectoriox-iox-ui-composite-core.mjs.map +1 -1
  8. package/fesm2022/vectoriox-iox-ui-design-core.mjs +416 -1
  9. package/fesm2022/vectoriox-iox-ui-design-core.mjs.map +1 -1
  10. package/fesm2022/vectoriox-iox-ui-forms-core.mjs +3 -24
  11. package/fesm2022/vectoriox-iox-ui-forms-core.mjs.map +1 -1
  12. package/fesm2022/vectoriox-iox-ui-generation-core.mjs +23 -13
  13. package/fesm2022/vectoriox-iox-ui-generation-core.mjs.map +1 -1
  14. package/fesm2022/vectoriox-iox-ui-identity-core.mjs +633 -0
  15. package/fesm2022/vectoriox-iox-ui-identity-core.mjs.map +1 -0
  16. package/fesm2022/vectoriox-iox-ui.mjs +2 -59
  17. package/fesm2022/vectoriox-iox-ui.mjs.map +1 -1
  18. package/forms-core/index.d.ts +2 -23
  19. package/generation-core/index.d.ts +3 -1
  20. package/identity-core/index.d.ts +426 -0
  21. package/identity-core/package.json +3 -0
  22. package/index.d.ts +0 -1
  23. package/package.json +5 -1
  24. package/src/actions-core/action.model.ts +1 -1
  25. package/src/actions-core/element-actions.ts +16 -6
  26. package/src/composite-core/account-runtime.ts +428 -0
  27. package/src/composite-core/account.ts +281 -0
  28. package/src/composite-core/public-api.ts +2 -0
  29. package/src/composite-core/recipe-parts.ts +48 -0
  30. package/src/composite-core/shop.ts +6 -26
  31. package/src/design-core/field-classes.ts +65 -0
  32. package/src/design-core/flavor-spec.generated.ts +346 -0
  33. package/src/design-core/public-api.ts +1 -0
  34. package/src/forms-core/field-markup.ts +2 -22
  35. package/src/generation-core/compose-site.ts +19 -9
  36. package/src/generation-core/nav-shape.ts +4 -4
  37. package/src/identity-core/guards.ts +87 -0
  38. package/src/identity-core/public-api.ts +14 -0
  39. package/src/identity-core/sign-in.ts +223 -0
  40. package/src/identity-core/site-auth-transport.ts +134 -0
  41. package/src/identity-core/site-auth.ts +182 -0
  42. package/src/identity-core/words.ts +194 -0
  43. package/styles/iox-design.css +38 -0
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Who signs in, with what, and the broker's two faces (commerce plan §3c "The broker, step by step", C-D6, C-D22).
3
+ * The broker (iox-control-plane, `auth.iox.studio`) and the studios (iox-cms) speak THESE shapes; a provider is one
4
+ * adapter on the broker and one `customerIdentities.provider` value in a studio. Email codes never touch the broker.
5
+ */
6
+
7
+ /** Who the sign-in is for. */
8
+ export enum SignInPurpose {
9
+ /** A buyer on a studio's site. */
10
+ Site = 'site',
11
+ /** A studio's team member — existing users only (wave 2). */
12
+ Admin = 'admin',
13
+ /** portal.iox.studio. */
14
+ Portal = 'portal',
15
+ }
16
+
17
+ /** A provider the broker runs. Google is live; the rest join one adapter at a time (board 18). */
18
+ export enum SignInProvider {
19
+ Google = 'google',
20
+ Meta = 'meta',
21
+ GitHub = 'github',
22
+ LinkedIn = 'linkedin',
23
+ }
24
+
25
+ /** How a provider answers (board 18): OpenID Connect gives a SIGNED ID token; OAuth 2 needs a profile call. */
26
+ export enum SignInProtocol {
27
+ Oidc = 'oidc',
28
+ OAuth2 = 'oauth2',
29
+ }
30
+
31
+ export interface SignInProviderSpec {
32
+ readonly protocol: SignInProtocol;
33
+ /** The answer is signed, so a studio can check it itself — the only kind an admin may sign in with (C-D6). */
34
+ readonly signedAnswer: boolean;
35
+ /** Running on the broker today. */
36
+ readonly live: boolean;
37
+ }
38
+
39
+ export const SIGN_IN_PROVIDER_SPECS: Readonly<Record<SignInProvider, SignInProviderSpec>> = Object.freeze({
40
+ [SignInProvider.Google]: { protocol: SignInProtocol.Oidc, signedAnswer: true, live: true },
41
+ [SignInProvider.LinkedIn]: { protocol: SignInProtocol.Oidc, signedAnswer: true, live: false },
42
+ [SignInProvider.Meta]: { protocol: SignInProtocol.OAuth2, signedAnswer: false, live: false },
43
+ [SignInProvider.GitHub]: { protocol: SignInProtocol.OAuth2, signedAnswer: false, live: false },
44
+ });
45
+
46
+ export function isSignInProvider(value: unknown): value is SignInProvider {
47
+ return typeof value === 'string' && (Object.values(SignInProvider) as string[]).includes(value);
48
+ }
49
+
50
+ export function isSignInPurpose(value: unknown): value is SignInPurpose {
51
+ return typeof value === 'string' && (Object.values(SignInPurpose) as string[]).includes(value);
52
+ }
53
+
54
+ /** May `provider` serve `purpose`? Buyers and the portal take any provider; a team member only a signed answer (C-D6). */
55
+ export function providerServes(provider: SignInProvider, purpose: SignInPurpose): boolean {
56
+ const spec = SIGN_IN_PROVIDER_SPECS[provider];
57
+ if (!spec) return false;
58
+ return purpose === SignInPurpose.Admin ? spec.signedAnswer : true;
59
+ }
60
+
61
+ // ── the broker ──────────────────────────────────────────────────────────────────────────────────
62
+
63
+ /** The broker's public host (its own ingress; ops.iox.studio is unchanged). */
64
+ export const BROKER_HOST = 'auth.iox.studio';
65
+ export const BROKER_ORIGIN = `https://${BROKER_HOST}`;
66
+
67
+ /** A ticket lives 60 s and is used once; so does a hand-off code. */
68
+ export const SIGN_IN_TICKET_TTL_SECONDS = 60;
69
+ export const SIGN_IN_HANDOFF_TTL_SECONDS = 60;
70
+
71
+ /** The server-to-server routes on the control plane's API host (bearer: the studio's INSTANCE_TOKEN). */
72
+ export enum BrokerApiRoute {
73
+ Tickets = 'instances/me/sign-in/tickets',
74
+ Redeem = 'instances/me/sign-in/redeem',
75
+ }
76
+
77
+ /** The browser's routes on `auth.iox.studio`, one pair per provider. */
78
+ export enum BrokerBrowserRoute {
79
+ Start = 'start',
80
+ Callback = 'callback',
81
+ }
82
+
83
+ /** `/<route>` on the control plane's API host, root-relative. */
84
+ export function brokerApiPath(route: BrokerApiRoute): string {
85
+ return `/${route}`;
86
+ }
87
+
88
+ /** `https://auth.iox.studio/<provider>/<route>`. */
89
+ export function brokerBrowserUrl(provider: SignInProvider, route: BrokerBrowserRoute, origin: string = BROKER_ORIGIN): string {
90
+ return `${origin.replace(/\/+$/, '')}/${encodeURIComponent(provider)}/${route}`;
91
+ }
92
+
93
+ /** Where the browser goes to begin: `https://auth.iox.studio/<provider>/start?ticket=<ticket>`. */
94
+ export function brokerStartUrl(provider: SignInProvider, ticket: string, origin: string = BROKER_ORIGIN): string {
95
+ return `${brokerBrowserUrl(provider, BrokerBrowserRoute.Start, origin)}?${BROKER_TICKET_PARAM}=${encodeURIComponent(ticket)}`;
96
+ }
97
+
98
+ /** The ONE address registered with each provider: `https://auth.iox.studio/<provider>/callback`. */
99
+ export function brokerCallbackUrl(provider: SignInProvider, origin: string = BROKER_ORIGIN): string {
100
+ return brokerBrowserUrl(provider, BrokerBrowserRoute.Callback, origin);
101
+ }
102
+
103
+ export const BROKER_TICKET_PARAM = 'ticket';
104
+
105
+ /** `POST instances/me/sign-in/tickets` — body. */
106
+ export interface SignInTicketRequest {
107
+ provider: SignInProvider;
108
+ purpose: SignInPurpose;
109
+ /** Where the broker sends the browser back; its host must be one of the asking tenant's. */
110
+ returnUrl: string;
111
+ }
112
+
113
+ /** 201 — `expiresAt` is an ISO date. */
114
+ export interface SignInTicketAnswer {
115
+ ticket: string;
116
+ startUrl: string;
117
+ expiresAt: string;
118
+ }
119
+
120
+ /** `POST instances/me/sign-in/redeem` — body: the hand-off code the browser brought back. */
121
+ export interface SignInRedeemRequest {
122
+ code: string;
123
+ }
124
+
125
+ /** 200 — the person the provider vouched for. Only the tenant (or the portal) that asked for the ticket gets it. */
126
+ export interface SignInRedeemAnswer {
127
+ provider: SignInProvider;
128
+ purpose: SignInPurpose;
129
+ /** The provider's stable id for the person (`customerIdentities.subject`). */
130
+ subject: string;
131
+ email: string;
132
+ /** Link to an existing customer by email ONLY when true (board 18's one security rule). */
133
+ emailVerified: boolean;
134
+ name?: string;
135
+ picture?: string;
136
+ returnUrl: string;
137
+ }
138
+
139
+ /** What the broker refuses, in its answer body `{ code }`. */
140
+ export enum BrokerRefusalCode {
141
+ /** 403 — the return address is not one of this tenant's hosts. */
142
+ ReturnHostRefused = 'return-host-refused',
143
+ /** 400 */
144
+ UnknownProvider = 'unknown-provider',
145
+ /** 503 — no client id/secret for the provider in the broker's environment. */
146
+ ProviderNotConfigured = 'provider-not-configured',
147
+ /** 404 */
148
+ CodeUnknown = 'code-unknown',
149
+ /** 410 */
150
+ CodeUsedOrExpired = 'code-used-or-expired',
151
+ /** 403 — another tenant's code. */
152
+ NotYours = 'not-yours',
153
+ }
154
+
155
+ export const BROKER_REFUSAL_STATUS: Readonly<Record<BrokerRefusalCode, number>> = Object.freeze({
156
+ [BrokerRefusalCode.ReturnHostRefused]: 403,
157
+ [BrokerRefusalCode.UnknownProvider]: 400,
158
+ [BrokerRefusalCode.ProviderNotConfigured]: 503,
159
+ [BrokerRefusalCode.CodeUnknown]: 404,
160
+ [BrokerRefusalCode.CodeUsedOrExpired]: 410,
161
+ [BrokerRefusalCode.NotYours]: 403,
162
+ });
163
+
164
+ export function isBrokerRefusalCode(value: unknown): value is BrokerRefusalCode {
165
+ return typeof value === 'string' && (Object.values(BrokerRefusalCode) as string[]).includes(value);
166
+ }
167
+
168
+ // ── back from the broker ───────────────────────────────────────────────────────────────────────
169
+
170
+ /** The hand-off code's query parameter on the return address. Never a name or an email in an address. */
171
+ export const SIGN_IN_HANDOFF_PARAM = 'iox_signin';
172
+ /** The failure's query parameter on the return address. */
173
+ export const SIGN_IN_ERROR_PARAM = 'iox_signin_error';
174
+
175
+ /** Why the browser came back without a person. */
176
+ export enum SignInReturnError {
177
+ /** The person pressed Cancel on the provider's screen. */
178
+ Cancelled = 'cancelled',
179
+ /** The provider's answer failed a check (issuer, audience, nonce, an unverified email). */
180
+ Refused = 'refused',
181
+ /** The ticket or the provider's state had expired. */
182
+ Expired = 'expired',
183
+ Failed = 'failed',
184
+ }
185
+
186
+ export function isSignInReturnError(value: unknown): value is SignInReturnError {
187
+ return typeof value === 'string' && (Object.values(SignInReturnError) as string[]).includes(value);
188
+ }
189
+
190
+ /** The return address with `?iox_signin=<code>` added (its own query, `next`, kept). */
191
+ export function withSignInHandoff(returnUrl: string, code: string): string {
192
+ return withParam(returnUrl, SIGN_IN_HANDOFF_PARAM, code);
193
+ }
194
+
195
+ /** The return address with `?iox_signin_error=<error>` added. */
196
+ export function withSignInError(returnUrl: string, error: SignInReturnError): string {
197
+ return withParam(returnUrl, SIGN_IN_ERROR_PARAM, error);
198
+ }
199
+
200
+ function withParam(address: string, name: string, value: string): string {
201
+ const url = new URL(address);
202
+ url.searchParams.delete(SIGN_IN_HANDOFF_PARAM);
203
+ url.searchParams.delete(SIGN_IN_ERROR_PARAM);
204
+ url.searchParams.set(name, value);
205
+ return url.toString();
206
+ }
207
+
208
+ export type SignInReturn =
209
+ | { readonly code: string; readonly error?: undefined }
210
+ | { readonly code?: undefined; readonly error: SignInReturnError };
211
+
212
+ /**
213
+ * What came back on a return address's query (`?iox_signin=` or `?iox_signin_error=`), or null when neither did. An
214
+ * error wins over a code; an unknown error reads `failed`; an empty code is no code.
215
+ */
216
+ export function readSignInReturn(search: string | URLSearchParams | null | undefined): SignInReturn | null {
217
+ const params = typeof search === 'string' ? new URLSearchParams(search.startsWith('?') ? search.slice(1) : search) : search;
218
+ if (!params) return null;
219
+ const error = params.get(SIGN_IN_ERROR_PARAM);
220
+ if (error !== null) return { error: isSignInReturnError(error) ? error : SignInReturnError.Failed };
221
+ const code = params.get(SIGN_IN_HANDOFF_PARAM)?.trim();
222
+ return code ? { code } : null;
223
+ }
@@ -0,0 +1,134 @@
1
+ import { isSameOriginPath } from './guards';
2
+ import { isEmailCodeShape, normalizeEmailCode, normalizeSignInEmail, SiteCustomer } from './site-auth';
3
+ import { brokerStartUrl, SignInProvider } from './sign-in';
4
+ import { SiteSignInRefusalCode, siteSignInCodeOf } from './words';
5
+
6
+ /**
7
+ * THE TRANSPORT a site's sign-in parts speak (commerce E3a, the `CartTransport` rule): the parts own no HTTP. The engine
8
+ * implements it over iox-cms's site routes (`siteAuthPath`, `siteProviderPath`, the cookie carried by the browser); the
9
+ * builder canvas uses `simulatedSiteAuthTransport` — the ADMIN's browser is never a buyer, so nothing is sent and no
10
+ * session exists.
11
+ */
12
+ export interface SiteAuthTransport {
13
+ /** The signed-in buyer, or null. */
14
+ me(): Promise<SiteCustomer | null>;
15
+ /** Ask the studio to start a provider's sign-in; the answer is the address the browser goes to next. */
16
+ startProvider(provider: SignInProvider, returnPath: string): Promise<{ startUrl: string }>;
17
+ /** Send a code to `email` (the studio always accepts — it never says whether the email is known). */
18
+ sendCode(email: string): Promise<void>;
19
+ /** Check the code; the signed-in buyer. */
20
+ verifyCode(email: string, code: string): Promise<SiteCustomer>;
21
+ signOut(): Promise<void>;
22
+ }
23
+
24
+ /** A refused transport call, carrying the code the visitor's words come from (`signInRefusal`). */
25
+ export class SiteAuthError extends Error {
26
+ readonly code: SiteSignInRefusalCode;
27
+
28
+ constructor(code: unknown) {
29
+ const known = siteSignInCodeOf(code);
30
+ super(known);
31
+ this.name = 'SiteAuthError';
32
+ this.code = known;
33
+ }
34
+ }
35
+
36
+ /** The code any thrown value carries: a `SiteAuthError`'s own, else `network` (the call never answered). */
37
+ export function siteAuthErrorCode(error: unknown): SiteSignInRefusalCode {
38
+ return error instanceof SiteAuthError ? error.code : SiteSignInRefusalCode.Network;
39
+ }
40
+
41
+ /** The sample buyer the canvas signs in as. */
42
+ export const SAMPLE_CUSTOMER: Readonly<SiteCustomer> = Object.freeze({ id: 'sample-customer', email: 'noa.levi@example.com', name: 'Noa Levi' });
43
+
44
+ /** The one code the simulated transport accepts (any other six digits are "not right" — so the error can be designed). */
45
+ export const SIMULATED_SIGN_IN_CODE = '123456';
46
+
47
+ export interface SimulatedSiteAuthTransport extends SiteAuthTransport {
48
+ /** Who is signed in on the canvas right now. */
49
+ readonly customer: SiteCustomer | null;
50
+ setCustomer(customer: SiteCustomer | null): void;
51
+ }
52
+
53
+ /**
54
+ * The canvas' transport: in memory, nothing sent. A code is "sent" to any well-formed email; `123456` signs in as the
55
+ * sample buyer under the typed email, any other six digits are `code-wrong`; a provider's start answers the broker's
56
+ * address with a sample ticket (the canvas host never follows it).
57
+ */
58
+ export function simulatedSiteAuthTransport(start: SiteCustomer | null = null): SimulatedSiteAuthTransport {
59
+ let customer: SiteCustomer | null = start;
60
+ const sentTo = new Set<string>();
61
+ return {
62
+ get customer() {
63
+ return customer;
64
+ },
65
+ setCustomer(next) {
66
+ customer = next;
67
+ },
68
+ async me() {
69
+ return customer;
70
+ },
71
+ async startProvider(provider, returnPath) {
72
+ if (!isSameOriginPath(returnPath)) throw new SiteAuthError(SiteSignInRefusalCode.Failed);
73
+ return { startUrl: brokerStartUrl(provider, 'sample-ticket') };
74
+ },
75
+ async sendCode(email) {
76
+ const key = normalizeSignInEmail(email);
77
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(key)) throw new SiteAuthError(SiteSignInRefusalCode.InvalidEmail);
78
+ sentTo.add(key);
79
+ },
80
+ async verifyCode(email, code) {
81
+ const key = normalizeSignInEmail(email);
82
+ const digits = normalizeEmailCode(code);
83
+ if (!sentTo.has(key) || !isEmailCodeShape(digits)) throw new SiteAuthError(SiteSignInRefusalCode.CodeWrong);
84
+ if (digits !== SIMULATED_SIGN_IN_CODE) throw new SiteAuthError(SiteSignInRefusalCode.CodeWrong);
85
+ customer = { ...SAMPLE_CUSTOMER, email: key };
86
+ return customer;
87
+ },
88
+ async signOut() {
89
+ customer = null;
90
+ },
91
+ };
92
+ }
93
+
94
+ /** A transport that has nothing to reach: `me` is null, every change refused as `network`. */
95
+ export const NO_SITE_AUTH_TRANSPORT: SiteAuthTransport = Object.freeze({
96
+ me: async () => null,
97
+ startProvider: async () => { throw new SiteAuthError(SiteSignInRefusalCode.ProviderUnavailable); },
98
+ sendCode: async () => { throw new SiteAuthError(SiteSignInRefusalCode.Network); },
99
+ verifyCode: async () => { throw new SiteAuthError(SiteSignInRefusalCode.Network); },
100
+ signOut: async () => undefined,
101
+ });
102
+
103
+ // ── what a page shows of the buyer ───────────────────────────────────────────────────────────
104
+
105
+ /** The context slot the account parts bind to (`$customer.initial`, `$customer.name`). */
106
+ export const CUSTOMER_SLOT = '$customer';
107
+
108
+ /** `$customer` — what a page may show of the buyer: never the id. */
109
+ export interface CustomerSlot {
110
+ signedIn: boolean;
111
+ name: string;
112
+ /** The first letter of the name, else of the email; '' when signed out. */
113
+ initial: string;
114
+ email: string;
115
+ }
116
+
117
+ /** The first visible letter of a name or an email, upper-cased where the script has case. */
118
+ export function customerInitial(customer: Pick<SiteCustomer, 'name' | 'email'> | null | undefined): string {
119
+ const source = (customer?.name ?? '').trim() || (customer?.email ?? '').trim();
120
+ const first = Array.from(source)[0] ?? '';
121
+ return first.toLocaleUpperCase();
122
+ }
123
+
124
+ /** The name a page greets with: the buyer's own, else the email's local part. */
125
+ export function customerDisplayName(customer: Pick<SiteCustomer, 'name' | 'email'> | null | undefined): string {
126
+ const name = (customer?.name ?? '').trim();
127
+ if (name) return name;
128
+ return (customer?.email ?? '').split('@')[0] ?? '';
129
+ }
130
+
131
+ export function customerSlotOf(customer: SiteCustomer | null | undefined): CustomerSlot {
132
+ if (!customer) return { signedIn: false, name: '', initial: '', email: '' };
133
+ return { signedIn: true, name: customerDisplayName(customer), initial: customerInitial(customer), email: customer.email };
134
+ }
@@ -0,0 +1,182 @@
1
+ import { safeNextPath } from './guards';
2
+ import { SignInProvider } from './sign-in';
3
+
4
+ /**
5
+ * A buyer's sign-in on a studio's site (commerce plan §3c, C-D5): iox-cms's public routes under `api/site/:orgId/`, the
6
+ * session it issues, and the cookies it sets. A customer is not a user — its token has its OWN secret and audience and
7
+ * every admin route refuses it (trap T3).
8
+ */
9
+
10
+ export enum SiteAuthRoute {
11
+ /** `POST { email }` → 202 always (never says whether the email is known). */
12
+ Code = 'auth/code',
13
+ /** `POST { email, code }` → the session. */
14
+ CodeVerify = 'auth/code/verify',
15
+ Refresh = 'auth/refresh',
16
+ SignOut = 'auth/signout',
17
+ /** `GET` → `{ customer }` (null when signed out). */
18
+ Me = 'me',
19
+ MyOrders = 'me/orders',
20
+ }
21
+
22
+ /** Every route a site's sign-in calls, by name (the provider pair is per provider — `siteProviderPath`). */
23
+ export const SITE_AUTH_ROUTES: Readonly<Record<keyof typeof SiteAuthRoute, SiteAuthRoute>> = Object.freeze({ ...SiteAuthRoute });
24
+
25
+ /** A provider's two routes on the studio: start (`POST { returnPath }` → `{ startUrl }`) and return (the broker's GET). */
26
+ export enum SiteProviderRoute {
27
+ Start = 'start',
28
+ Return = 'return',
29
+ }
30
+
31
+ function siteBase(orgId: string): string {
32
+ return `/api/site/${encodeURIComponent(orgId)}`;
33
+ }
34
+
35
+ /** A sign-in route of one org, ROOT-relative: `/api/site/<org>/<route>`. */
36
+ export function siteAuthPath(orgId: string, route: SiteAuthRoute): string {
37
+ return `${siteBase(orgId)}/${route}`;
38
+ }
39
+
40
+ /** `/api/site/<org>/auth/<provider>/<start|return>`. */
41
+ export function siteProviderPath(orgId: string, provider: SignInProvider, route: SiteProviderRoute): string {
42
+ return `${siteBase(orgId)}/auth/${encodeURIComponent(provider)}/${route}`;
43
+ }
44
+
45
+ /** The `next` query parameter of the return route — where the buyer lands after signing in. */
46
+ export const SIGN_IN_NEXT_PARAM = 'next';
47
+
48
+ /**
49
+ * The address the studio asks the broker to send the browser back to:
50
+ * `https://<host>/api/site/<org>/auth/<provider>/return?next=<path>`. `origin` is the studio's own (`https://<host>`);
51
+ * a `next` that is not a same-origin path becomes `/`.
52
+ */
53
+ export function siteProviderReturnUrl(origin: string, orgId: string, provider: SignInProvider, next: string | null | undefined): string {
54
+ const path = siteProviderPath(orgId, provider, SiteProviderRoute.Return);
55
+ return `${origin.replace(/\/+$/, '')}${path}?${SIGN_IN_NEXT_PARAM}=${encodeURIComponent(safeNextPath(next))}`;
56
+ }
57
+
58
+ // ── the requests and answers ───────────────────────────────────────────────────────────────────
59
+
60
+ export interface SiteProviderStartRequest {
61
+ /** The page to come back to (a same-origin path). */
62
+ returnPath: string;
63
+ }
64
+
65
+ export interface SiteProviderStartAnswer {
66
+ startUrl: string;
67
+ }
68
+
69
+ export interface SiteCodeRequest {
70
+ email: string;
71
+ }
72
+
73
+ export interface SiteCodeVerifyRequest {
74
+ email: string;
75
+ code: string;
76
+ }
77
+
78
+ /** What a site may know about the signed-in buyer — nothing else (pages stay cacheable; personal parts fill in later). */
79
+ export interface SiteCustomer {
80
+ id: string;
81
+ email: string;
82
+ name: string | null;
83
+ }
84
+
85
+ /** `GET me`, `POST auth/code/verify`, `POST auth/refresh`. */
86
+ export interface SiteMeAnswer {
87
+ customer: SiteCustomer | null;
88
+ }
89
+
90
+ // ── the session ────────────────────────────────────────────────────────────────────────────────
91
+
92
+ /** The buyer token's audience — never an admin token's. */
93
+ export const SITE_AUDIENCE = 'site';
94
+
95
+ /** The buyer session's JWT claims. */
96
+ export interface SiteSessionClaims {
97
+ /** The customer id. */
98
+ sub: string;
99
+ aud: typeof SITE_AUDIENCE;
100
+ /** The org the customer belongs to — a session is good on ONE org's routes. */
101
+ org: string;
102
+ iat?: number;
103
+ exp?: number;
104
+ }
105
+
106
+ /** True when `claims` carry the site audience and both ids — the shape `CustomerGuard` accepts (it checks the signature). */
107
+ export function isSiteSessionClaims(claims: unknown): claims is SiteSessionClaims {
108
+ if (!claims || typeof claims !== 'object') return false;
109
+ const c = claims as Record<string, unknown>;
110
+ const aud = Array.isArray(c['aud']) ? c['aud'] : [c['aud']];
111
+ return aud.includes(SITE_AUDIENCE) && typeof c['sub'] === 'string' && !!c['sub'] && typeof c['org'] === 'string' && !!c['org'];
112
+ }
113
+
114
+ /** True when a token's claims carry the site audience at all — what the admin guard refuses (T3). */
115
+ export function hasSiteAudience(claims: unknown): boolean {
116
+ if (!claims || typeof claims !== 'object') return false;
117
+ const aud = (claims as Record<string, unknown>)['aud'];
118
+ return Array.isArray(aud) ? aud.includes(SITE_AUDIENCE) : aud === SITE_AUDIENCE;
119
+ }
120
+
121
+ // ── the cookies (per org: many orgs share one host — trap T10) ────────────────────────────────
122
+
123
+ /** The buyer session: httpOnly, `Path=/` (the site's SSR reads it — the cart cookie's reason), SameSite=Lax. */
124
+ export const CUSTOMER_COOKIE_PREFIX = 'iox_c_';
125
+ /** A Google sign-in in flight: httpOnly, short, holds a hash binding the ticket — a forged return fails without it. */
126
+ export const SIGN_IN_STATE_COOKIE_PREFIX = 'iox_si_';
127
+ export const SITE_COOKIE_PATH = '/';
128
+ /** Long enough for a person on the provider's screen; the ticket inside expires long before. */
129
+ export const SIGN_IN_STATE_MAX_AGE_SECONDS = 600;
130
+
131
+ export function customerCookieName(orgId: string): string {
132
+ return `${CUSTOMER_COOKIE_PREFIX}${orgId}`;
133
+ }
134
+
135
+ export function signInStateCookieName(orgId: string): string {
136
+ return `${SIGN_IN_STATE_COOKIE_PREFIX}${orgId}`;
137
+ }
138
+
139
+ // ── the email code ─────────────────────────────────────────────────────────────────────────────
140
+
141
+ export const EMAIL_CODE_LENGTH = 6;
142
+ export const EMAIL_CODE_TTL_MINUTES = 10;
143
+ export const EMAIL_CODE_TTL_MS = EMAIL_CODE_TTL_MINUTES * 60_000;
144
+ /** Wrong codes before the code is spent and a new one must be sent. */
145
+ export const EMAIL_CODE_MAX_TRIES = 5;
146
+
147
+ const EMAIL_CODE = new RegExp(`^\\d{${EMAIL_CODE_LENGTH}}$`);
148
+
149
+ /** A typed or pasted code as digits only ("481 203", "481-203" → "481203"); anything else is kept, to be refused. */
150
+ export function normalizeEmailCode(input: unknown): string {
151
+ return String(input ?? '').replace(/[\s-]/g, '');
152
+ }
153
+
154
+ /** Exactly six ASCII digits. */
155
+ export function isEmailCodeShape(code: unknown): boolean {
156
+ return typeof code === 'string' && EMAIL_CODE.test(code);
157
+ }
158
+
159
+ /** An email as a studio keys its customers by (unique per org): trimmed, lower case. */
160
+ export function normalizeSignInEmail(email: unknown): string {
161
+ return String(email ?? '').trim().toLowerCase();
162
+ }
163
+
164
+ /** Has the code outlived its ten minutes? `now` is the caller's — the core reads no clock. */
165
+ export function emailCodeExpired(sentAt: number | Date, now: number | Date): boolean {
166
+ return +now - +sentAt >= EMAIL_CODE_TTL_MS;
167
+ }
168
+
169
+ /** How many more codes may be tried after `wrongTries` wrong ones (0 = the code is spent). */
170
+ export function emailCodeTriesLeft(wrongTries: number): number {
171
+ return Math.max(0, EMAIL_CODE_MAX_TRIES - Math.max(0, Math.floor(wrongTries || 0)));
172
+ }
173
+
174
+ // ── the fixed account page (C-D3: fixed like checkout, the look's dress) ────────────────────────
175
+
176
+ export const ACCOUNT_PATH = 'account';
177
+
178
+ /** The buyer's account page — their orders: `/<orgLabel>/account` (the engine answers it on every studio). */
179
+ export function accountHref(orgLabel?: string | null): string {
180
+ const label = String(orgLabel ?? '').replace(/^\/+|\/+$/g, '');
181
+ return label ? `/${encodeURIComponent(label)}/${ACCOUNT_PATH}` : `/${ACCOUNT_PATH}`;
182
+ }