@inglorious/web 6.23.1 → 6.24.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 CHANGED
@@ -1573,6 +1573,35 @@ Set `publicKey` in the plugin's Capacitor config so it refuses unsigned bundles,
1573
1573
 
1574
1574
  ---
1575
1575
 
1576
+ ## Sign-in
1577
+
1578
+ `@inglorious/web/auth` is the type behind a sign-in screen. It walks from the email to a password, a new account or a code sent by email, holds the signed-in `user`, and erases the account on request, as the App Store and Google Play require of apps that create accounts. Codes rather than links work in a native app too, since nobody has to open anything.
1579
+
1580
+ ```javascript
1581
+ import { supabaseAuth } from "@inglorious/supabase"
1582
+ import { createAuth, watchAuth } from "@inglorious/web/auth"
1583
+
1584
+ const adapter = supabaseAuth(supabase)
1585
+
1586
+ const types = {
1587
+ Auth: { ...createAuth({ adapter, methods: ["password", "code"] }), render },
1588
+ }
1589
+
1590
+ watchAuth(adapter, store) // keeps `user` in step with the session
1591
+ ```
1592
+
1593
+ `methods` lists what the screen offers: `"password"` (sign in, create an account confirmed with a code, reset a forgotten password with a code) and `"code"` (sign in with a code alone, creating the account on first use).
1594
+
1595
+ The entity's `step` says what to ask for: `"email"`, `"password"`, `"signUp"`, `"code"` or `"reset"`. Its events take what the person typed: `emailSubmit(email)`, `signInSubmit(password)`, `signUpSubmit({ password, data })`, `codeSubmit(code)`, `resetSubmit({ code, password })`, and move between steps: `signUpShow`, `signInShow`, `codeRequest`, `codeResend`, `resetRequest`, `back`. Signed in, `signOut` and `accountEraseAsk`, then `accountErase` or `accountEraseCancel`. `isReady` turns true once the saved session is read: until then, render nothing rather than the sign-in screen.
1596
+
1597
+ `status` is `"loading"` while waiting, and `error` is a key to put into words: `"invalidEmail"`, `"invalidCode"`, `"weakPassword"`, `"invalidCredentials"`, `"accountExists"`, `"rateLimited"`, `"captcha"`, `"network"` or `"unknown"`. An account not confirmed yet goes straight to the code.
1598
+
1599
+ The adapter talks to the backend. `supabaseAuth` from `@inglorious/supabase` is one; another backend needs `onSessionChange`, `signIn`, `signUp`, `sendCode`, `verifyCode`, `resendCode`, `sendResetCode`, `updatePassword`, `signOut`, `eraseAccount` and `errorCode`, plus `accountExists` to skip straight to the password or the new account.
1600
+
1601
+ `create-app --auth` generates the screen, the account actions in the app bar, the Edge Function that erases accounts and the email templates.
1602
+
1603
+ ---
1604
+
1576
1605
  ## App Links
1577
1606
 
1578
1607
  With Universal Links (iOS) and App Links (Android), a link to the app's domain opens the installed app instead of the browser. `@inglorious/web/app-links` sends the router to that link's path, both for the link that started the app and for links that arrive while it runs. It does nothing outside a native app.
@@ -1992,7 +2021,7 @@ Import everything else from the package that owns it, or from an explicit `@ingl
1992
2021
 
1993
2022
  ```javascript
1994
2023
  import { createStore } from "@inglorious/store"
1995
- import { handleAsync } from "@inglorious/store/async"
2024
+ import { handleAsync, handleRequest } from "@inglorious/store/async"
1996
2025
  import { optimistic } from "@inglorious/store/optimistic"
1997
2026
  import { compute, createSelector } from "@inglorious/store/select"
1998
2027
  import { createDevtools } from "@inglorious/store/client/devtools"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inglorious/web",
3
- "version": "6.23.1",
3
+ "version": "6.24.0",
4
4
  "description": "A new web framework that leverages the power of the Inglorious Store combined with the performance and simplicity of lit-html.",
5
5
  "author": "Matteo Antony Mistretta <antony.mistretta@gmail.com> (https://ingloriouscoderz.it)",
6
6
  "contributors": [
@@ -41,6 +41,10 @@
41
41
  "types": "./types/app-links.d.ts",
42
42
  "import": "./src/app-links/index.js"
43
43
  },
44
+ "./auth": {
45
+ "types": "./types/auth.d.ts",
46
+ "import": "./src/auth/index.js"
47
+ },
44
48
  "./back-button": {
45
49
  "types": "./types/back-button.d.ts",
46
50
  "import": "./src/back-button/index.js"
@@ -154,7 +158,7 @@
154
158
  "lit-html": "^3.3.3"
155
159
  },
156
160
  "peerDependencies": {
157
- "@inglorious/store": "^12.3.0"
161
+ "@inglorious/store": "^12.4.0"
158
162
  },
159
163
  "devDependencies": {
160
164
  "@inglorious/eslint-config": "1.2.0",
@@ -0,0 +1,294 @@
1
+ import { handleRequest } from "@inglorious/store/async"
2
+
3
+ const DEFAULT_ID = "auth"
4
+ const DEFAULT_METHODS = ["password"]
5
+ const DEFAULT_MIN_PASSWORD_LENGTH = 8
6
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
7
+ const CODE = /^\d{6,10}$/
8
+
9
+ /**
10
+ * The type behind a sign-in screen: it walks from the email to a password, a
11
+ * new account or a code sent by email, and holds the signed-in `user`. Codes
12
+ * work everywhere, a native app included, since nobody has to open a link.
13
+ *
14
+ * `methods` lists what the screen offers: `"password"` (sign in, create an
15
+ * account, confirm it with a code, reset a forgotten password) and `"code"`
16
+ * (sign in with a code sent by email, creating the account on first use).
17
+ *
18
+ * The entity's `step` says what to ask for: `"email"`, `"password"`,
19
+ * `"signUp"`, `"code"` or `"reset"`. `status` is `"loading"` while waiting,
20
+ * then `"success"` or `"error"`, and `error` is a key: `"invalidEmail"`, `"invalidCode"`, `"weakPassword"`,
21
+ * `"invalidCredentials"`, `"accountExists"`, `"rateLimited"`, `"captcha"`,
22
+ * `"network"` or `"unknown"`.
23
+ *
24
+ * The `adapter` talks to the backend: `signIn`, `signUp`, `sendCode`,
25
+ * `verifyCode`, `resendCode`, `sendResetCode`, `updatePassword`, `signOut`,
26
+ * `eraseAccount`, `errorCode`, and optionally `accountExists`, which skips
27
+ * straight to the password or the new account. `supabaseAuth` from
28
+ * `@inglorious/supabase` is one.
29
+ *
30
+ * @param {Object} config
31
+ * @param {Object} config.adapter
32
+ * @param {("password" | "code")[]} [config.methods]
33
+ * @param {number} [config.minPasswordLength] Defaults to 8.
34
+ *
35
+ * @example
36
+ * const types = { Auth: [createAuth({ adapter: supabaseAuth(supabase) }), screen] }
37
+ * watchAuth(supabaseAuth(supabase), store)
38
+ */
39
+ export function createAuth({
40
+ adapter,
41
+ methods = DEFAULT_METHODS,
42
+ minPasswordLength = DEFAULT_MIN_PASSWORD_LENGTH,
43
+ }) {
44
+ const hasPassword = methods.includes("password")
45
+ const hasCode = methods.includes("code")
46
+
47
+ return {
48
+ create(entity) {
49
+ entity.user ??= null
50
+ entity.isReady ??= false
51
+ entity.methods = methods
52
+ reset(entity)
53
+ },
54
+
55
+ sessionChange(entity, user) {
56
+ entity.user = user ?? null
57
+ entity.isReady = true
58
+ if (user) reset(entity)
59
+ },
60
+
61
+ emailSubmit(entity, email, api) {
62
+ const clean = String(email ?? "")
63
+ .trim()
64
+ .toLowerCase()
65
+ entity.email = clean
66
+ if (!EMAIL.test(clean)) {
67
+ entity.error = "invalidEmail"
68
+ return
69
+ }
70
+ entity.error = null
71
+ if (hasPassword) {
72
+ api.notify(`#${entity.id}:emailCheck`, clean)
73
+ return
74
+ }
75
+ api.notify(`#${entity.id}:codeSend`, clean)
76
+ },
77
+
78
+ ...request("emailCheck", {
79
+ async run(email) {
80
+ return adapter.accountExists ? await adapter.accountExists(email) : true
81
+ },
82
+ success(entity, exists) {
83
+ entity.step = exists ? "password" : "signUp"
84
+ },
85
+ }),
86
+
87
+ signUpShow(entity) {
88
+ entity.step = "signUp"
89
+ entity.error = null
90
+ },
91
+
92
+ signInShow(entity) {
93
+ entity.step = "password"
94
+ entity.error = null
95
+ },
96
+
97
+ back(entity) {
98
+ reset(entity, entity.email)
99
+ },
100
+
101
+ signInSubmit(entity, password, api) {
102
+ api.notify(`#${entity.id}:signIn`, { email: entity.email, password })
103
+ },
104
+
105
+ ...request("signIn", {
106
+ run: ({ email, password }) => adapter.signIn(email, password),
107
+ success(entity, user) {
108
+ entity.user = user
109
+ reset(entity)
110
+ },
111
+ error(entity, code) {
112
+ if (code !== "emailNotConfirmed") return
113
+ entity.error = null
114
+ showCode(entity, "signUp")
115
+ },
116
+ }),
117
+
118
+ signUpSubmit(entity, { password, data } = {}, api) {
119
+ if (String(password ?? "").length < minPasswordLength) {
120
+ entity.error = "weakPassword"
121
+ return
122
+ }
123
+ api.notify(`#${entity.id}:signUp`, {
124
+ email: entity.email,
125
+ password,
126
+ data,
127
+ })
128
+ },
129
+
130
+ ...request("signUp", {
131
+ run: ({ email, password, data }) => adapter.signUp(email, password, data),
132
+ success(entity, user) {
133
+ if (user) {
134
+ entity.user = user
135
+ reset(entity)
136
+ return
137
+ }
138
+ showCode(entity, "signUp")
139
+ },
140
+ }),
141
+
142
+ codeRequest(entity, _, api) {
143
+ if (!hasCode) return
144
+ api.notify(`#${entity.id}:codeSend`, entity.email)
145
+ },
146
+
147
+ ...request("codeSend", {
148
+ run: (email) => adapter.sendCode(email),
149
+ success(entity) {
150
+ showCode(entity, "signIn")
151
+ },
152
+ }),
153
+
154
+ codeSubmit(entity, code, api) {
155
+ const clean = String(code ?? "").trim()
156
+ if (!CODE.test(clean)) {
157
+ entity.error = "invalidCode"
158
+ return
159
+ }
160
+ api.notify(`#${entity.id}:codeVerify`, {
161
+ email: entity.email,
162
+ code: clean,
163
+ purpose: entity.codeFor,
164
+ })
165
+ },
166
+
167
+ ...request("codeVerify", {
168
+ run: ({ email, code, purpose }) =>
169
+ adapter.verifyCode(email, code, purpose),
170
+ success(entity, user) {
171
+ entity.user = user
172
+ reset(entity)
173
+ },
174
+ }),
175
+
176
+ codeResend(entity, _, api) {
177
+ api.notify(`#${entity.id}:resend`, {
178
+ email: entity.email,
179
+ purpose: entity.codeFor,
180
+ })
181
+ },
182
+
183
+ ...request("resend", {
184
+ run: ({ email, purpose }) => adapter.resendCode(email, purpose),
185
+ success(entity) {
186
+ entity.isCodeResent = true
187
+ },
188
+ }),
189
+
190
+ resetRequest(entity, _, api) {
191
+ if (!hasPassword) return
192
+ api.notify(`#${entity.id}:resetSend`, entity.email)
193
+ },
194
+
195
+ ...request("resetSend", {
196
+ run: (email) => adapter.sendResetCode(email),
197
+ success(entity) {
198
+ entity.step = "reset"
199
+ entity.codeFor = "reset"
200
+ entity.isCodeResent = false
201
+ },
202
+ }),
203
+
204
+ resetSubmit(entity, { code, password } = {}, api) {
205
+ const clean = String(code ?? "").trim()
206
+ if (!CODE.test(clean)) {
207
+ entity.error = "invalidCode"
208
+ return
209
+ }
210
+ if (String(password ?? "").length < minPasswordLength) {
211
+ entity.error = "weakPassword"
212
+ return
213
+ }
214
+ api.notify(`#${entity.id}:passwordReset`, {
215
+ email: entity.email,
216
+ code: clean,
217
+ password,
218
+ })
219
+ },
220
+
221
+ ...request("passwordReset", {
222
+ async run({ email, code, password }) {
223
+ await adapter.verifyCode(email, code, "reset")
224
+ return adapter.updatePassword(password)
225
+ },
226
+ success(entity, user) {
227
+ entity.user = user
228
+ reset(entity)
229
+ },
230
+ }),
231
+
232
+ ...request("signOut", {
233
+ run: () => adapter.signOut(),
234
+ success(entity) {
235
+ entity.user = null
236
+ reset(entity)
237
+ },
238
+ }),
239
+
240
+ accountEraseAsk(entity) {
241
+ entity.isEraseAsked = true
242
+ },
243
+
244
+ accountEraseCancel(entity) {
245
+ entity.isEraseAsked = false
246
+ },
247
+
248
+ ...request("accountErase", {
249
+ run: () => adapter.eraseAccount(),
250
+ success(entity) {
251
+ entity.user = null
252
+ reset(entity)
253
+ },
254
+ }),
255
+ }
256
+
257
+ function request(name, handlers) {
258
+ return handleRequest(name, handlers, {
259
+ toError: (error) => adapter.errorCode?.(error) ?? "unknown",
260
+ })
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Keeps the entity's `user` in step with the backend's session: signed in or
266
+ * out, from this tab or another, and when a saved session is restored at
267
+ * launch, which sets `isReady`.
268
+ *
269
+ * @param {{ onSessionChange: (listener: (user: object | null) => void) => () => void }} adapter
270
+ * @param {{ notify: (type: string, payload?: unknown) => void }} store
271
+ * @param {{ id?: string }} [options]
272
+ * @returns {() => void} Stops watching.
273
+ */
274
+ export function watchAuth(adapter, store, { id = DEFAULT_ID } = {}) {
275
+ return adapter.onSessionChange((user) =>
276
+ store.notify(`#${id}:sessionChange`, user),
277
+ )
278
+ }
279
+
280
+ function reset(entity, email = "") {
281
+ entity.step = "email"
282
+ entity.email = email
283
+ entity.codeFor = null
284
+ entity.status = "idle"
285
+ entity.error = null
286
+ entity.isCodeResent = false
287
+ entity.isEraseAsked = false
288
+ }
289
+
290
+ function showCode(entity, purpose) {
291
+ entity.step = "code"
292
+ entity.codeFor = purpose
293
+ entity.isCodeResent = false
294
+ }
@@ -0,0 +1,127 @@
1
+ import { Api } from "./mount"
2
+
3
+ /** The signed-in user, as the backend describes them. */
4
+ export interface AuthUser {
5
+ id: string
6
+ email?: string
7
+ [key: string]: unknown
8
+ }
9
+
10
+ /** What a code sent by email is for. */
11
+ export type AuthCodePurpose = "signIn" | "signUp" | "reset"
12
+
13
+ /** How people sign in: a password, a code sent by email, or both. */
14
+ export type AuthMethod = "password" | "code"
15
+
16
+ /** What went wrong, as a key the screen turns into words. */
17
+ export type AuthError =
18
+ | "invalidEmail"
19
+ | "invalidCode"
20
+ | "weakPassword"
21
+ | "invalidCredentials"
22
+ | "emailNotConfirmed"
23
+ | "accountExists"
24
+ | "rateLimited"
25
+ | "captcha"
26
+ | "network"
27
+ | "unknown"
28
+
29
+ /** Where accounts live. Each call rejects on failure. */
30
+ export interface AuthAdapter {
31
+ /** Calls `listener` with the user on every sign-in and sign-out, and once the saved session is known. */
32
+ onSessionChange(listener: (user: AuthUser | null) => void): () => void
33
+ /** Whether the email has an account: skips straight to the password or the new account. */
34
+ accountExists?(email: string): Promise<boolean>
35
+ signIn(email: string, password: string): Promise<AuthUser>
36
+ /** The user when signed in at once, `null` when the email needs confirming with a code. */
37
+ signUp(
38
+ email: string,
39
+ password: string,
40
+ data?: Record<string, unknown>,
41
+ ): Promise<AuthUser | null>
42
+ /** Sends a sign-in code, creating the account on first use. */
43
+ sendCode(email: string): Promise<void>
44
+ verifyCode(
45
+ email: string,
46
+ code: string,
47
+ purpose: AuthCodePurpose,
48
+ ): Promise<AuthUser>
49
+ resendCode(email: string, purpose: AuthCodePurpose): Promise<void>
50
+ sendResetCode(email: string): Promise<void>
51
+ /** Sets the signed-in user's new password. */
52
+ updatePassword(password: string): Promise<AuthUser>
53
+ signOut(): Promise<void>
54
+ /** Deletes the signed-in user's account and everything that is theirs, then signs out. */
55
+ eraseAccount(): Promise<void>
56
+ /** The key for a failure. */
57
+ errorCode?(error: unknown): AuthError
58
+ }
59
+
60
+ export interface AuthConfig {
61
+ adapter: AuthAdapter
62
+ /** Defaults to `["password"]`. */
63
+ methods?: AuthMethod[]
64
+ /** Defaults to 8. */
65
+ minPasswordLength?: number
66
+ }
67
+
68
+ export interface AuthEntity {
69
+ id?: string
70
+ type: string
71
+ user: AuthUser | null
72
+ /** The saved session has been read: until then, the user is unknown. */
73
+ isReady: boolean
74
+ methods: AuthMethod[]
75
+ step: "email" | "password" | "signUp" | "code" | "reset"
76
+ email: string
77
+ codeFor: AuthCodePurpose | null
78
+ /** `"idle"` until the first request. */
79
+ status: "idle" | "loading" | "success" | "error"
80
+ error: AuthError | null
81
+ isCodeResent: boolean
82
+ /** The user asked to erase their account and hasn't confirmed yet. */
83
+ isEraseAsked: boolean
84
+ }
85
+
86
+ type Handler<TPayload = void> = (
87
+ entity: AuthEntity,
88
+ payload: TPayload,
89
+ api?: Api,
90
+ ) => void
91
+
92
+ export type AuthType = {
93
+ create(entity: AuthEntity): void
94
+ sessionChange: Handler<AuthUser | null>
95
+ emailSubmit: Handler<string>
96
+ signInSubmit: Handler<string>
97
+ signUpShow: Handler
98
+ signInShow: Handler
99
+ signUpSubmit: Handler<{
100
+ password: string
101
+ data?: Record<string, unknown>
102
+ }>
103
+ codeRequest: Handler
104
+ codeSubmit: Handler<string>
105
+ codeResend: Handler
106
+ resetRequest: Handler
107
+ resetSubmit: Handler<{ code: string; password: string }>
108
+ back: Handler
109
+ signOut: Handler
110
+ accountEraseAsk: Handler
111
+ accountEraseCancel: Handler
112
+ accountErase: Handler
113
+ [handler: string]: unknown
114
+ }
115
+
116
+ /** The type behind a sign-in screen, holding the signed-in `user`. */
117
+ export declare function createAuth(config: AuthConfig): AuthType
118
+
119
+ /**
120
+ * Keeps the entity's `user` in step with the backend's session.
121
+ * @returns A function that stops watching.
122
+ */
123
+ export declare function watchAuth(
124
+ adapter: Pick<AuthAdapter, "onSessionChange">,
125
+ store: { notify(type: string, payload?: unknown): void },
126
+ options?: { id?: string },
127
+ ): () => void
@@ -1,9 +1,11 @@
1
- /** What `haptics` needs of `Haptics` from `@capacitor/haptics`. */
1
+ /**
2
+ * What `haptics` needs of `Haptics` from `@capacitor/haptics`, whose options
3
+ * take its `ImpactStyle` and `NotificationType` enums: `"LIGHT"`, `"MEDIUM"`,
4
+ * `"HEAVY"` and `"SUCCESS"`, `"WARNING"`, `"ERROR"`.
5
+ */
2
6
  export interface HapticsPlugin {
3
- impact(options: { style: "LIGHT" | "MEDIUM" | "HEAVY" }): Promise<void>
4
- notification(options: {
5
- type: "SUCCESS" | "WARNING" | "ERROR"
6
- }): Promise<void>
7
+ impact(options?: { style?: string }): Promise<void>
8
+ notification(options?: { type?: string }): Promise<void>
7
9
  }
8
10
 
9
11
  /**