@vectoriox/iox-ui 5.98.0 → 5.99.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/fesm2022/vectoriox-iox-ui-identity-core.mjs +535 -0
- package/fesm2022/vectoriox-iox-ui-identity-core.mjs.map +1 -0
- package/identity-core/index.d.ts +364 -0
- package/identity-core/package.json +3 -0
- package/package.json +5 -1
- package/src/identity-core/guards.ts +87 -0
- package/src/identity-core/public-api.ts +13 -0
- package/src/identity-core/sign-in.ts +223 -0
- package/src/identity-core/site-auth.ts +172 -0
- package/src/identity-core/words.ts +194 -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,172 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { BrokerRefusalCode, SignInReturnError } from './sign-in';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The sign-in dialog's words and its refusals, in English and Hebrew. A string-rendered site has no translation
|
|
5
|
+
* service, so the core carries both itself (commerce-core `CHECKOUT_WORDS` precedent); a host with its own translations
|
|
6
|
+
* may key them by the stable codes instead.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface SignInLabel {
|
|
10
|
+
readonly en: string;
|
|
11
|
+
readonly he: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export enum SignInLanguage {
|
|
15
|
+
En = 'en',
|
|
16
|
+
He = 'he',
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function signInLanguage(lang: string | null | undefined): SignInLanguage {
|
|
20
|
+
const primary = String(lang ?? '').trim().toLowerCase().split(/[-_]/)[0];
|
|
21
|
+
return primary === 'he' || primary === 'iw' ? SignInLanguage.He : SignInLanguage.En;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function fillIn(words: string, fill: Readonly<Record<string, string | number>>): string {
|
|
25
|
+
return words.replace(/\{(\w+)\}/g, (all, key) => (key in fill ? String(fill[key]) : all));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export enum SignInWord {
|
|
29
|
+
SignIn = 'signIn',
|
|
30
|
+
SignInTo = 'signInTo',
|
|
31
|
+
Why = 'why',
|
|
32
|
+
ContinueWithGoogle = 'continueWithGoogle',
|
|
33
|
+
Or = 'or',
|
|
34
|
+
Email = 'email',
|
|
35
|
+
EmailPlaceholder = 'emailPlaceholder',
|
|
36
|
+
SendCode = 'sendCode',
|
|
37
|
+
CodeSent = 'codeSent',
|
|
38
|
+
Code = 'code',
|
|
39
|
+
CodeValid = 'codeValid',
|
|
40
|
+
SendAgain = 'sendAgain',
|
|
41
|
+
Verify = 'verify',
|
|
42
|
+
OtherEmail = 'otherEmail',
|
|
43
|
+
Working = 'working',
|
|
44
|
+
Close = 'close',
|
|
45
|
+
SignOut = 'signOut',
|
|
46
|
+
Account = 'account',
|
|
47
|
+
YourOrders = 'yourOrders',
|
|
48
|
+
Hello = 'hello',
|
|
49
|
+
SignedIn = 'signedIn',
|
|
50
|
+
SignedOut = 'signedOut',
|
|
51
|
+
NoPassword = 'noPassword',
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** `{site}`, `{email}`, `{name}`, `{minutes}` are filled by `signInWord`. */
|
|
55
|
+
export const SIGN_IN_WORDS: Readonly<Record<SignInWord, SignInLabel>> = Object.freeze({
|
|
56
|
+
[SignInWord.SignIn]: { en: 'Sign in', he: 'התחברות' },
|
|
57
|
+
[SignInWord.SignInTo]: { en: 'Sign in to {site}', he: 'התחברות ל־{site}' },
|
|
58
|
+
[SignInWord.Why]: { en: 'See your orders and check out faster.', he: 'לראות את ההזמנות שלך ולשלם מהר יותר.' },
|
|
59
|
+
[SignInWord.ContinueWithGoogle]: { en: 'Continue with Google', he: 'המשך עם Google' },
|
|
60
|
+
[SignInWord.Or]: { en: 'or', he: 'או' },
|
|
61
|
+
[SignInWord.Email]: { en: 'Email', he: 'אימייל' },
|
|
62
|
+
[SignInWord.EmailPlaceholder]: { en: 'name@example.com', he: 'name@example.com' },
|
|
63
|
+
[SignInWord.SendCode]: { en: 'Send me a code', he: 'שלחו לי קוד' },
|
|
64
|
+
[SignInWord.CodeSent]: { en: 'We sent a 6-digit code to {email}', he: 'שלחנו קוד בן 6 ספרות אל {email}' },
|
|
65
|
+
[SignInWord.Code]: { en: 'Code', he: 'קוד' },
|
|
66
|
+
[SignInWord.CodeValid]: { en: 'Valid for {minutes} minutes', he: 'בתוקף ל־{minutes} דקות' },
|
|
67
|
+
[SignInWord.SendAgain]: { en: 'Send again', he: 'שליחה חוזרת' },
|
|
68
|
+
[SignInWord.Verify]: { en: 'Sign in', he: 'התחברות' },
|
|
69
|
+
[SignInWord.OtherEmail]: { en: 'Use another email', he: 'אימייל אחר' },
|
|
70
|
+
[SignInWord.Working]: { en: 'One moment…', he: 'רגע…' },
|
|
71
|
+
[SignInWord.Close]: { en: 'Close', he: 'סגירה' },
|
|
72
|
+
[SignInWord.SignOut]: { en: 'Sign out', he: 'התנתקות' },
|
|
73
|
+
[SignInWord.Account]: { en: 'Account', he: 'החשבון שלי' },
|
|
74
|
+
[SignInWord.YourOrders]: { en: 'Your orders', he: 'ההזמנות שלך' },
|
|
75
|
+
[SignInWord.Hello]: { en: 'Hello, {name}', he: 'שלום, {name}' },
|
|
76
|
+
[SignInWord.SignedIn]: { en: 'You are signed in.', he: 'התחברת.' },
|
|
77
|
+
[SignInWord.SignedOut]: { en: 'You are signed out.', he: 'התנתקת.' },
|
|
78
|
+
[SignInWord.NoPassword]: { en: 'No password — we email you a code.', he: 'בלי סיסמה — נשלח לך קוד במייל.' },
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
export function signInWord(word: SignInWord, lang: string | null | undefined, fill: Readonly<Record<string, string | number>> = {}): string {
|
|
82
|
+
return fillIn(SIGN_IN_WORDS[word][signInLanguage(lang)], fill);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ── a refusal, said on its field ─────────────────────────────────────────────────────────────
|
|
86
|
+
|
|
87
|
+
/** Where in the sign-in dialog a refusal is said. */
|
|
88
|
+
export enum SignInSlot {
|
|
89
|
+
Email = 'email',
|
|
90
|
+
Code = 'code',
|
|
91
|
+
/** Under "Continue with Google". */
|
|
92
|
+
Provider = 'provider',
|
|
93
|
+
/** The dialog as a whole. */
|
|
94
|
+
Dialog = 'dialog',
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Every code a site's sign-in can hear: iox-cms's answers, the broker's return errors (`?iox_signin_error=`), and
|
|
99
|
+
* `network` for no answer at all.
|
|
100
|
+
*/
|
|
101
|
+
export enum SiteSignInRefusalCode {
|
|
102
|
+
InvalidEmail = 'invalid-email',
|
|
103
|
+
CodeWrong = 'code-wrong',
|
|
104
|
+
CodeExpired = 'code-expired',
|
|
105
|
+
TooManyTries = 'too-many-tries',
|
|
106
|
+
RateLimited = 'rate-limited',
|
|
107
|
+
/** The broker cannot run the provider (down, not configured, the host refused). */
|
|
108
|
+
ProviderUnavailable = 'provider-unavailable',
|
|
109
|
+
Cancelled = 'cancelled',
|
|
110
|
+
Refused = 'refused',
|
|
111
|
+
Expired = 'expired',
|
|
112
|
+
Failed = 'failed',
|
|
113
|
+
/** The return came back without this browser's sign-in cookie — a forged or stale return. */
|
|
114
|
+
StateMismatch = 'state-mismatch',
|
|
115
|
+
Blocked = 'blocked',
|
|
116
|
+
NotSignedIn = 'not-signed-in',
|
|
117
|
+
Network = 'network',
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface SignInRefusalRule {
|
|
121
|
+
readonly slot: SignInSlot;
|
|
122
|
+
readonly label: SignInLabel;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const TRY_GOOGLE_AGAIN: SignInLabel = { en: 'Google sign-in did not work. Try again, or use an email code.', he: 'ההתחברות עם Google לא הצליחה. נסו שוב, או התחברו עם קוד במייל.' };
|
|
126
|
+
const SEND_NEW_CODE: SignInLabel = { en: 'This code has expired. Send a new one.', he: 'תוקף הקוד פג. שלחו קוד חדש.' };
|
|
127
|
+
|
|
128
|
+
export const SIGN_IN_REFUSALS: Readonly<Record<SiteSignInRefusalCode, SignInRefusalRule>> = Object.freeze({
|
|
129
|
+
[SiteSignInRefusalCode.InvalidEmail]: { slot: SignInSlot.Email, label: { en: 'Enter an email address, like name@example.com.', he: 'הקלידו כתובת אימייל, למשל name@example.com.' } },
|
|
130
|
+
[SiteSignInRefusalCode.CodeWrong]: { slot: SignInSlot.Code, label: { en: 'That code is not right. Check it and try again.', he: 'הקוד לא נכון. בדקו ונסו שוב.' } },
|
|
131
|
+
[SiteSignInRefusalCode.CodeExpired]: { slot: SignInSlot.Code, label: SEND_NEW_CODE },
|
|
132
|
+
[SiteSignInRefusalCode.TooManyTries]: { slot: SignInSlot.Code, label: { en: 'Too many wrong codes. Send a new one.', he: 'יותר מדי קודים שגויים. שלחו קוד חדש.' } },
|
|
133
|
+
[SiteSignInRefusalCode.RateLimited]: { slot: SignInSlot.Dialog, label: { en: 'Too many tries. Wait a minute and try again.', he: 'יותר מדי ניסיונות. המתינו דקה ונסו שוב.' } },
|
|
134
|
+
[SiteSignInRefusalCode.ProviderUnavailable]: { slot: SignInSlot.Provider, label: { en: 'Google sign-in is not available right now. Use an email code.', he: 'ההתחברות עם Google לא זמינה כרגע. התחברו עם קוד במייל.' } },
|
|
135
|
+
[SiteSignInRefusalCode.Cancelled]: { slot: SignInSlot.Provider, label: { en: 'Google sign-in was cancelled.', he: 'ההתחברות עם Google בוטלה.' } },
|
|
136
|
+
[SiteSignInRefusalCode.Refused]: { slot: SignInSlot.Provider, label: { en: 'Google could not confirm this account. Use an email code.', he: 'Google לא אישר את החשבון הזה. התחברו עם קוד במייל.' } },
|
|
137
|
+
[SiteSignInRefusalCode.Expired]: { slot: SignInSlot.Provider, label: { en: 'The sign-in took too long. Try again.', he: 'ההתחברות ארכה יותר מדי. נסו שוב.' } },
|
|
138
|
+
[SiteSignInRefusalCode.Failed]: { slot: SignInSlot.Provider, label: TRY_GOOGLE_AGAIN },
|
|
139
|
+
[SiteSignInRefusalCode.StateMismatch]: { slot: SignInSlot.Provider, label: TRY_GOOGLE_AGAIN },
|
|
140
|
+
[SiteSignInRefusalCode.Blocked]: { slot: SignInSlot.Dialog, label: { en: 'This account cannot sign in here. Contact the business.', he: 'החשבון הזה לא יכול להתחבר כאן. פנו לעסק.' } },
|
|
141
|
+
[SiteSignInRefusalCode.NotSignedIn]: { slot: SignInSlot.Dialog, label: { en: 'You are signed out. Sign in again.', he: 'התנתקת. התחברו שוב.' } },
|
|
142
|
+
[SiteSignInRefusalCode.Network]: { slot: SignInSlot.Dialog, label: { en: 'We could not reach the site. Try again.', he: 'לא הצלחנו להגיע לאתר. נסו שוב.' } },
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
export function isSiteSignInRefusalCode(code: unknown): code is SiteSignInRefusalCode {
|
|
146
|
+
return typeof code === 'string' && (Object.values(SiteSignInRefusalCode) as string[]).includes(code);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** A broker refusal as the site says it: a person never hears "return-host-refused". */
|
|
150
|
+
const FROM_BROKER: Readonly<Record<BrokerRefusalCode, SiteSignInRefusalCode>> = Object.freeze({
|
|
151
|
+
[BrokerRefusalCode.ReturnHostRefused]: SiteSignInRefusalCode.ProviderUnavailable,
|
|
152
|
+
[BrokerRefusalCode.UnknownProvider]: SiteSignInRefusalCode.ProviderUnavailable,
|
|
153
|
+
[BrokerRefusalCode.ProviderNotConfigured]: SiteSignInRefusalCode.ProviderUnavailable,
|
|
154
|
+
[BrokerRefusalCode.CodeUnknown]: SiteSignInRefusalCode.Expired,
|
|
155
|
+
[BrokerRefusalCode.CodeUsedOrExpired]: SiteSignInRefusalCode.Expired,
|
|
156
|
+
[BrokerRefusalCode.NotYours]: SiteSignInRefusalCode.Failed,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
const FROM_RETURN: Readonly<Record<SignInReturnError, SiteSignInRefusalCode>> = Object.freeze({
|
|
160
|
+
[SignInReturnError.Cancelled]: SiteSignInRefusalCode.Cancelled,
|
|
161
|
+
[SignInReturnError.Refused]: SiteSignInRefusalCode.Refused,
|
|
162
|
+
[SignInReturnError.Expired]: SiteSignInRefusalCode.Expired,
|
|
163
|
+
[SignInReturnError.Failed]: SiteSignInRefusalCode.Failed,
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
/** Any code a sign-in heard, as the site's own: a site code as is, a broker code or a return error mapped, else `failed`. */
|
|
167
|
+
export function siteSignInCodeOf(code: unknown): SiteSignInRefusalCode {
|
|
168
|
+
if (isSiteSignInRefusalCode(code)) return code;
|
|
169
|
+
if (typeof code === 'string' && code in FROM_BROKER) return FROM_BROKER[code as BrokerRefusalCode];
|
|
170
|
+
if (typeof code === 'string' && code in FROM_RETURN) return FROM_RETURN[code as SignInReturnError];
|
|
171
|
+
return SiteSignInRefusalCode.Failed;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export interface SignInRefusal {
|
|
175
|
+
code: SiteSignInRefusalCode;
|
|
176
|
+
slot: SignInSlot;
|
|
177
|
+
words: string;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** One refusal, on its slot, in the visitor's words. */
|
|
181
|
+
export function signInRefusal(code: unknown, lang: string | null | undefined): SignInRefusal {
|
|
182
|
+
const known = siteSignInCodeOf(code);
|
|
183
|
+
const rule = SIGN_IN_REFUSALS[known];
|
|
184
|
+
return { code: known, slot: rule.slot, words: rule.label[signInLanguage(lang)] };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** A refused call's body (`{ code }`) — or nothing at all (`network`) — as one refusal. The body's `message` is a log
|
|
188
|
+
* line and is never shown. A 429 with no code is `rate-limited`. */
|
|
189
|
+
export function signInRefusalOf(body: unknown, lang: string | null | undefined, status?: number | null): SignInRefusal {
|
|
190
|
+
const code = body && typeof body === 'object' ? (body as { code?: unknown }).code : undefined;
|
|
191
|
+
if (code !== undefined) return signInRefusal(code, lang);
|
|
192
|
+
if (status === 429) return signInRefusal(SiteSignInRefusalCode.RateLimited, lang);
|
|
193
|
+
return signInRefusal(body === undefined || body === null ? SiteSignInRefusalCode.Network : SiteSignInRefusalCode.Failed, lang);
|
|
194
|
+
}
|