@owlmeans/client-auth 0.1.18-rc.4 → 0.1.18-rc.41

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 (180) hide show
  1. package/README.md +280 -37
  2. package/agent-meta/manifest.json +2 -2
  3. package/agent-meta/skills/client-auth/SKILL.md +139 -21
  4. package/build/components/dispatcher/component.d.ts.map +1 -1
  5. package/build/components/dispatcher/component.js +14 -3
  6. package/build/components/dispatcher/component.js.map +1 -1
  7. package/build/entrypoints.d.ts +7 -0
  8. package/build/entrypoints.d.ts.map +1 -0
  9. package/build/entrypoints.js +7 -0
  10. package/build/entrypoints.js.map +1 -0
  11. package/build/helper.d.ts +2 -1
  12. package/build/helper.d.ts.map +1 -1
  13. package/build/helper.js +24 -3
  14. package/build/helper.js.map +1 -1
  15. package/build/index.d.ts +1 -1
  16. package/build/index.d.ts.map +1 -1
  17. package/build/index.js +1 -1
  18. package/build/index.js.map +1 -1
  19. package/build/login/adopt.d.ts +24 -0
  20. package/build/login/adopt.d.ts.map +1 -0
  21. package/build/login/adopt.js +28 -0
  22. package/build/login/adopt.js.map +1 -0
  23. package/build/login/consts.d.ts +49 -0
  24. package/build/login/consts.d.ts.map +1 -0
  25. package/build/login/consts.js +49 -0
  26. package/build/login/consts.js.map +1 -0
  27. package/build/login/credit.d.ts +24 -0
  28. package/build/login/credit.d.ts.map +1 -0
  29. package/build/login/credit.js +58 -0
  30. package/build/login/credit.js.map +1 -0
  31. package/build/login/env.d.ts +32 -0
  32. package/build/login/env.d.ts.map +1 -0
  33. package/build/login/env.js +84 -0
  34. package/build/login/env.js.map +1 -0
  35. package/build/login/flow.d.ts +20 -0
  36. package/build/login/flow.d.ts.map +1 -0
  37. package/build/login/flow.js +39 -0
  38. package/build/login/flow.js.map +1 -0
  39. package/build/login/hook.d.ts +37 -0
  40. package/build/login/hook.d.ts.map +1 -0
  41. package/build/login/hook.js +72 -0
  42. package/build/login/hook.js.map +1 -0
  43. package/build/login/i18n/be.json +37 -0
  44. package/build/login/i18n/de.json +37 -0
  45. package/build/login/i18n/en.json +37 -0
  46. package/build/login/i18n/es.json +37 -0
  47. package/build/login/i18n/fr.json +37 -0
  48. package/build/login/i18n/pl.json +37 -0
  49. package/build/login/i18n/ru.json +37 -0
  50. package/build/login/i18n/uk.json +37 -0
  51. package/build/login/i18n.d.ts +2 -0
  52. package/build/login/i18n.d.ts.map +1 -0
  53. package/build/login/i18n.js +27 -0
  54. package/build/login/i18n.js.map +1 -0
  55. package/build/login/index.d.ts +15 -0
  56. package/build/login/index.d.ts.map +1 -0
  57. package/build/login/index.js +15 -0
  58. package/build/login/index.js.map +1 -0
  59. package/build/login/methods.d.ts +25 -0
  60. package/build/login/methods.d.ts.map +1 -0
  61. package/build/login/methods.js +97 -0
  62. package/build/login/methods.js.map +1 -0
  63. package/build/login/resume.d.ts +30 -0
  64. package/build/login/resume.d.ts.map +1 -0
  65. package/build/login/resume.js +57 -0
  66. package/build/login/resume.js.map +1 -0
  67. package/build/login/screen.d.ts +17 -0
  68. package/build/login/screen.d.ts.map +1 -0
  69. package/build/login/screen.js +76 -0
  70. package/build/login/screen.js.map +1 -0
  71. package/build/login/service.d.ts +31 -0
  72. package/build/login/service.d.ts.map +1 -0
  73. package/build/login/service.js +148 -0
  74. package/build/login/service.js.map +1 -0
  75. package/build/login/surrogate.d.ts +20 -0
  76. package/build/login/surrogate.d.ts.map +1 -0
  77. package/build/login/surrogate.js +33 -0
  78. package/build/login/surrogate.js.map +1 -0
  79. package/build/login/terms.d.ts +20 -0
  80. package/build/login/terms.d.ts.map +1 -0
  81. package/build/login/terms.js +0 -0
  82. package/build/login/terms.js.map +1 -0
  83. package/build/login/types.d.ts +256 -0
  84. package/build/login/types.d.ts.map +1 -0
  85. package/build/login/types.js +31 -0
  86. package/build/login/types.js.map +1 -0
  87. package/build/manager/components/authentication/control.js +3 -3
  88. package/build/manager/components/authentication/control.js.map +1 -1
  89. package/build/manager/components/authentication/types.d.ts +2 -2
  90. package/build/manager/components/authentication/types.d.ts.map +1 -1
  91. package/build/manager/components/tunnel-consumer.js +2 -2
  92. package/build/manager/components/tunnel-consumer.js.map +1 -1
  93. package/build/manager/entrypoints.d.ts +11 -0
  94. package/build/manager/entrypoints.d.ts.map +1 -0
  95. package/build/manager/entrypoints.js +17 -0
  96. package/build/manager/entrypoints.js.map +1 -0
  97. package/build/manager/plugins/basic-ed25519.d.ts.map +1 -1
  98. package/build/manager/plugins/basic-ed25519.js +5 -0
  99. package/build/manager/plugins/basic-ed25519.js.map +1 -1
  100. package/build/manager/plugins/exports.d.ts +2 -0
  101. package/build/manager/plugins/exports.d.ts.map +1 -1
  102. package/build/manager/plugins/exports.js +2 -0
  103. package/build/manager/plugins/exports.js.map +1 -1
  104. package/build/manager/plugins/index.d.ts +1 -5
  105. package/build/manager/plugins/index.d.ts.map +1 -1
  106. package/build/manager/plugins/index.js +9 -1
  107. package/build/manager/plugins/index.js.map +1 -1
  108. package/build/manager/plugins/methods.d.ts +6 -0
  109. package/build/manager/plugins/methods.d.ts.map +1 -0
  110. package/build/manager/plugins/methods.js +65 -0
  111. package/build/manager/plugins/methods.js.map +1 -0
  112. package/build/manager/plugins/re-captcha.d.ts.map +1 -1
  113. package/build/manager/plugins/re-captcha.js +5 -0
  114. package/build/manager/plugins/re-captcha.js.map +1 -1
  115. package/build/manager/plugins/registry.d.ts +20 -0
  116. package/build/manager/plugins/registry.d.ts.map +1 -0
  117. package/build/manager/plugins/registry.js +19 -0
  118. package/build/manager/plugins/registry.js.map +1 -0
  119. package/build/manager/plugins/tunnel-consumer.d.ts.map +1 -1
  120. package/build/manager/plugins/tunnel-consumer.js +8 -1
  121. package/build/manager/plugins/tunnel-consumer.js.map +1 -1
  122. package/build/manager/plugins/types.d.ts +53 -0
  123. package/build/manager/plugins/types.d.ts.map +1 -1
  124. package/build/service.js +1 -1
  125. package/build/service.js.map +1 -1
  126. package/package.json +36 -27
  127. package/src/components/dispatcher/component.tsx +16 -3
  128. package/src/entrypoints.ts +10 -0
  129. package/src/helper.ts +26 -3
  130. package/src/index.ts +1 -1
  131. package/src/login/adopt.ts +31 -0
  132. package/src/login/consts.ts +64 -0
  133. package/src/login/credit.ts +75 -0
  134. package/src/login/env.ts +86 -0
  135. package/src/login/flow.ts +44 -0
  136. package/src/login/hook.ts +80 -0
  137. package/src/login/i18n/be.json +37 -0
  138. package/src/login/i18n/de.json +37 -0
  139. package/src/login/i18n/en.json +37 -0
  140. package/src/login/i18n/es.json +37 -0
  141. package/src/login/i18n/fr.json +37 -0
  142. package/src/login/i18n/pl.json +37 -0
  143. package/src/login/i18n/ru.json +37 -0
  144. package/src/login/i18n/uk.json +37 -0
  145. package/src/login/i18n.ts +28 -0
  146. package/src/login/index.ts +15 -0
  147. package/src/login/methods.ts +113 -0
  148. package/src/login/resume.ts +58 -0
  149. package/src/login/screen.tsx +136 -0
  150. package/src/login/service.ts +195 -0
  151. package/src/login/surrogate.ts +45 -0
  152. package/src/login/terms.ts +0 -0
  153. package/src/login/types.ts +279 -0
  154. package/src/manager/README.md +37 -80
  155. package/src/manager/components/authentication/control.ts +3 -3
  156. package/src/manager/components/authentication/types.ts +2 -2
  157. package/src/manager/components/tunnel-consumer.tsx +2 -2
  158. package/src/manager/entrypoints.ts +18 -0
  159. package/src/manager/plugins/basic-ed25519.tsx +7 -0
  160. package/src/manager/plugins/exports.ts +2 -0
  161. package/src/manager/plugins/index.ts +10 -4
  162. package/src/manager/plugins/methods.ts +74 -0
  163. package/src/manager/plugins/re-captcha.tsx +7 -0
  164. package/src/manager/plugins/registry.ts +26 -0
  165. package/src/manager/plugins/tunnel-consumer.tsx +10 -1
  166. package/src/manager/plugins/types.ts +54 -0
  167. package/src/service.ts +1 -1
  168. package/tests/context.ts +1 -2
  169. package/tests/login.spec.ts +332 -0
  170. package/build/.gitkeep +0 -0
  171. package/build/manager/modules.d.ts +0 -2
  172. package/build/manager/modules.d.ts.map +0 -1
  173. package/build/manager/modules.js +0 -16
  174. package/build/manager/modules.js.map +0 -1
  175. package/build/modules.d.ts +0 -4
  176. package/build/modules.d.ts.map +0 -1
  177. package/build/modules.js +0 -9
  178. package/build/modules.js.map +0 -1
  179. package/src/manager/modules.ts +0 -18
  180. package/src/modules.ts +0 -13
@@ -0,0 +1,113 @@
1
+ import type { LoginMethodConfig, LoginScreenConfig } from '@owlmeans/config'
2
+ import { DEFAULT_METHOD_ORDER } from './consts.js'
3
+ import type { LoginMethod, LoginMethodContext, LoginMethodSource } from './types.js'
4
+
5
+ /**
6
+ * The module-global registry of method SOURCES.
7
+ *
8
+ * A source, rather than a method, because the two things that offer sign-in methods answer
9
+ * different questions at different times: the plugin registry knows what code is loaded, and the
10
+ * OIDC configuration knows what an entity is federated with. Both are answered per render — a
11
+ * provider list can arrive from the api-config middleware after the first paint.
12
+ *
13
+ * Global, like the `AuthenticationPlugin` map it mirrors, because a package registers its source
14
+ * from a side-effect import that has no context to hang it on. A context-scoped registry exists
15
+ * alongside it on the login service, and both are merged by {@link resolveLoginMethods}.
16
+ */
17
+ const sources: LoginMethodSource[] = []
18
+
19
+ export const registerMethodSource = (source: LoginMethodSource): void => {
20
+ const existing = sources.findIndex(candidate => candidate.alias === source.alias)
21
+ if (existing >= 0) {
22
+ sources.splice(existing, 1)
23
+ }
24
+ sources.push(source)
25
+ }
26
+
27
+ export const listMethodSources = (): LoginMethodSource[] => [...sources]
28
+
29
+ /** Normalize a config entry, which may be a bare id or a full override object. */
30
+ const asConfig = (entry: string | LoginMethodConfig): LoginMethodConfig =>
31
+ typeof entry === 'string' ? { id: entry } : entry
32
+
33
+ const merge = (method: LoginMethod, override: LoginMethodConfig | undefined): LoginMethod =>
34
+ override == null ? method : {
35
+ ...method,
36
+ ...(override.label != null ? { label: override.label } : {}),
37
+ ...(override.i18nKey != null ? { i18nKey: override.i18nKey } : {}),
38
+ ...(override.icon != null ? { icon: override.icon } : {}),
39
+ ...(override.order != null ? { order: override.order } : {}),
40
+ ...(override.emphasis != null ? { emphasis: override.emphasis } : {}),
41
+ ...(override.params != null ? { params: { ...method.params, ...override.params } } : {}),
42
+ }
43
+
44
+ /**
45
+ * Everything the current environment may be offered, in the order it should be offered in.
46
+ *
47
+ * Resolution order matters and is not arbitrary:
48
+ *
49
+ * 1. Sources produce candidates. A source that throws is skipped rather than taking the screen
50
+ * down — a misconfigured provider list must not remove the sign-in method that does work.
51
+ * 2. `restricted` candidates are dropped unless the configuration named them, which is what makes
52
+ * an operator login opt-in rather than merely unadvertised.
53
+ * 3. An explicit `methods` list is both a filter AND the order, because an app that bothered to
54
+ * list them means that list.
55
+ */
56
+ export const resolveLoginMethods = (
57
+ ctx: LoginMethodContext, cfg?: LoginScreenConfig, extra: LoginMethodSource[] = []
58
+ ): LoginMethod[] => {
59
+ const candidates: LoginMethod[] = []
60
+ for (const source of [...sources, ...extra]) {
61
+ try {
62
+ candidates.push(...source.list(ctx))
63
+ } catch (e) {
64
+ console.error(`login: method source "${source.alias}" failed`, e)
65
+ }
66
+ }
67
+
68
+ const overrides = cfg?.overrides ?? {}
69
+ const listed = cfg?.methods?.map(asConfig)
70
+ const listedIds = listed?.map(entry => entry.id).filter((id): id is string => id != null)
71
+
72
+ const offered = candidates
73
+ .filter(method => {
74
+ const override = overrides[method.id] ?? listed?.find(entry => entry.id === method.id)
75
+ if (override?.enabled === false || override?.hidden === true) {
76
+ return false
77
+ }
78
+ // A restricted method is offered only where the configuration asked for it — by naming it in
79
+ // `methods`, or by enabling it in `overrides`. Registering the plugin is deliberately not
80
+ // enough: an operator login that appears wherever its code happens to be bundled is an
81
+ // operator login in production.
82
+ if (method.restricted === true
83
+ && listedIds?.includes(method.id) !== true
84
+ && override?.enabled !== true) {
85
+ return false
86
+ }
87
+ return true
88
+ })
89
+ .map(method => merge(method, overrides[method.id]))
90
+
91
+ if (listedIds != null) {
92
+ return listedIds
93
+ .map(id => {
94
+ const method = offered.find(candidate => candidate.id === id)
95
+ return method != null ? merge(method, listed?.find(entry => entry.id === id)) : null
96
+ })
97
+ .filter((method): method is LoginMethod => method != null)
98
+ }
99
+
100
+ return offered.sort((a, b) => {
101
+ const order = (a.order ?? DEFAULT_METHOD_ORDER) - (b.order ?? DEFAULT_METHOD_ORDER)
102
+ return order !== 0 ? order : a.id.localeCompare(b.id)
103
+ })
104
+ }
105
+
106
+ /**
107
+ * The method a screen highlights and focuses.
108
+ *
109
+ * The first `primary` one, else the first offered. It is highlighted, never started: requirement
110
+ * one of this whole feature is that nothing leaves the document without a click.
111
+ */
112
+ export const primaryLoginMethod = (methods: LoginMethod[]): LoginMethod | null =>
113
+ methods.find(method => method.emphasis === 'primary') ?? methods[0] ?? null
@@ -0,0 +1,58 @@
1
+ import { LoginOutcome } from './types.js'
2
+
3
+ /**
4
+ * The message key a FINISHED sign-in attempt should show, or null when it actually went somewhere.
5
+ *
6
+ * A dispatcher may treat `Passed` as "carry on with the ordinary continuation", because it has one.
7
+ * A screen does not: the user clicked, the document did not move, and nothing rendered — which is
8
+ * indistinguishable from a broken button, and is exactly how a null authorization URL used to
9
+ * present itself. Every outcome that leaves the user looking at the same screen therefore has to
10
+ * say something.
11
+ */
12
+ export const loginAttemptError = (outcome: LoginOutcome | null): string | null => {
13
+ switch (outcome) {
14
+ case LoginOutcome.Gesture:
15
+ case LoginOutcome.Blocked:
16
+ // The window never opened. That is the popup blocker, and it has its own copy.
17
+ return 'login.error.blocked'
18
+ case LoginOutcome.Failed:
19
+ case LoginOutcome.Passed:
20
+ return 'login.error.failed'
21
+ default:
22
+ // Handled, Redirected and Orphaned all did something; Orphaned reports itself elsewhere.
23
+ return null
24
+ }
25
+ }
26
+
27
+ /** What a dispatcher does once `login().resume(...)` has answered. */
28
+ export enum ResumeAction {
29
+ /** The plugin took it over — the browser is leaving, or the window is closing. */
30
+ Stop = 'stop',
31
+ /** Render the outcome to the user; there is nothing further to do automatically. */
32
+ Render = 'render',
33
+ /** Ordinary tab: keep the session and carry on to the application. */
34
+ Navigate = 'navigate',
35
+ }
36
+
37
+ /**
38
+ * The one reading of a `resume` outcome, shared by every dispatcher.
39
+ *
40
+ * Exported as a pure function because three dispatchers — `web-client`, `web-oidc-rp` and
41
+ * `mui-oidc-rp` — have to agree on it, and the last time they each held their own copy of a
42
+ * decision they drifted, which is how a popup came to render the application inside itself in two
43
+ * packages at once. It is also the whole rule, so it is testable without a DOM.
44
+ */
45
+ export const resumeAction = (outcome: LoginOutcome): ResumeAction => {
46
+ switch (outcome) {
47
+ case LoginOutcome.Handled:
48
+ case LoginOutcome.Redirected:
49
+ return ResumeAction.Stop
50
+ case LoginOutcome.Orphaned:
51
+ case LoginOutcome.Failed:
52
+ case LoginOutcome.Gesture:
53
+ case LoginOutcome.Blocked:
54
+ return ResumeAction.Render
55
+ default:
56
+ return ResumeAction.Navigate
57
+ }
58
+ }
@@ -0,0 +1,136 @@
1
+ import { useCallback, useState } from 'react'
2
+ import type { CSSProperties, FC } from 'react'
3
+ import { useContext } from '@owlmeans/client'
4
+ import type { CommonConfig } from '@owlmeans/config'
5
+ import type { LoginContext, LoginMethod, LoginScreenProps, LoginService } from './types.js'
6
+ import { LOGIN_SERVICE } from './consts.js'
7
+ import { primaryLoginMethod } from './methods.js'
8
+ import { acceptTerms, resolveTerms, termsAccepted } from './terms.js'
9
+ import { resolveCredit } from './credit.js'
10
+
11
+ /**
12
+ * The page the card sits in.
13
+ *
14
+ * It carries its own viewport height because this screen is rendered straight out of the
15
+ * dispatcher, into whatever the application happens to have around it — which is usually nothing
16
+ * with a height, so a percentage minimum would resolve to zero and leave the card at the top.
17
+ */
18
+ const page: CSSProperties = {
19
+ display: 'flex', alignItems: 'center', justifyContent: 'center',
20
+ minHeight: '100dvh', padding: '1rem',
21
+ fontFamily: 'system-ui, sans-serif', lineHeight: 1.5,
22
+ }
23
+
24
+ // Centred throughout, so the plain screen and the styled one read the same way.
25
+ const box: CSSProperties = {
26
+ width: '100%', maxWidth: '24rem', padding: '1.5rem', textAlign: 'center',
27
+ }
28
+
29
+ const button = (emphasis?: string): CSSProperties => ({
30
+ display: 'block', width: '100%', marginTop: '.5rem', padding: '.625rem 1rem',
31
+ fontSize: '1rem', cursor: 'pointer', borderRadius: '.375rem',
32
+ border: '1px solid currentColor',
33
+ ...(emphasis === 'primary' ? { fontWeight: 600 } : {}),
34
+ })
35
+
36
+ /**
37
+ * The sign-in screen every application gets, whether or not it registered a styled one.
38
+ *
39
+ * It exists because a relying party must render SOMETHING rather than start a flow on its own, and
40
+ * a relying party may not depend on a UI family. So this is deliberately plain: raw elements and
41
+ * inline styles, no Tailwind class that a consumer's stylesheet would have to scan for, no shadcn
42
+ * primitive a consumer would have to vendor. An application that registers a real screen through
43
+ * `login().registerScreen(...)` never sees it.
44
+ *
45
+ * Because it is the floor rather than the design, it still has to be correct: it offers the same
46
+ * methods, enforces the same terms confirmation, centres the same way, and renders the same
47
+ * credit line.
48
+ */
49
+ export const FallbackLoginScreen: FC<LoginScreenProps> = props => {
50
+ const context = useContext() as unknown as LoginContext
51
+ const t = props.translate ?? ((_key: string, defaultValue: string) => defaultValue)
52
+ const cfg = props.config ?? (context.cfg as CommonConfig).security?.auth?.login
53
+ const brand = (context.cfg as CommonConfig).brand
54
+
55
+ const login = context.service<LoginService>(LOGIN_SERVICE)
56
+ const env = login.env()
57
+ const resolved = resolveTerms(props.terms ?? cfg?.terms)
58
+ const credit = resolveCredit(cfg?.credit, brand, context.cfg.service)
59
+
60
+ const [accepted, setAccepted] = useState(() => termsAccepted(resolved))
61
+ const [attempted, setAttempted] = useState(false)
62
+
63
+ const all = login.methods({ context, env })
64
+ const methods = typeof props.methods === 'function'
65
+ ? props.methods(all)
66
+ : props.methods ?? all
67
+ const primary = primaryLoginMethod(methods)
68
+
69
+ const blocked = resolved != null && resolved.required && !accepted
70
+
71
+ const select = useCallback((method: LoginMethod) => {
72
+ if (blocked) {
73
+ setAttempted(true)
74
+ return
75
+ }
76
+ void method.start({ context, env })
77
+ }, [blocked, context, env])
78
+
79
+ const onAccept = useCallback((value: boolean) => {
80
+ setAccepted(value)
81
+ setAttempted(false)
82
+ acceptTerms(resolved, value)
83
+ }, [resolved])
84
+
85
+ return <div data-login-screen style={page}><div style={box}>
86
+ <h1 style={{ fontSize: '1.25rem', marginBottom: '.25rem' }}>
87
+ {props.title ?? t('login.title', 'Sign in')}
88
+ </h1>
89
+ <p style={{ opacity: .75, marginTop: 0 }}>
90
+ {props.subtitle ?? t('login.subtitle', 'Choose how you would like to continue.')}
91
+ </p>
92
+
93
+ {methods.length < 1
94
+ ? <p role="status">{t('login.empty', 'No sign-in method is configured for this application.')}</p>
95
+ : methods.map(method => <button
96
+ key={method.id} type="button" data-login-method={method.id}
97
+ // `aria-disabled`, never `disabled`: a disabled button swallows the click, so a user who
98
+ // has not confirmed the terms would press it and be told nothing at all.
99
+ aria-disabled={blocked} data-blocked={blocked ? 'true' : undefined}
100
+ style={{ ...button(method.emphasis), opacity: blocked ? .6 : 1 }}
101
+ autoFocus={method.id === primary?.id}
102
+ onClick={() => select(method)}
103
+ >
104
+ {method.label ?? t(`login.method.${method.i18nKey ?? method.id}`, method.id)}
105
+ </button>)}
106
+
107
+ {resolved != null && <p style={{ marginTop: '1rem', fontSize: '.875rem' }}>
108
+ <label>
109
+ <input
110
+ type="checkbox" checked={accepted} data-login-terms
111
+ onChange={event => onAccept(event.target.checked)}
112
+ />{' '}
113
+ {t('login.terms.agreement', 'I have read and agree to the Terms & Conditions and the Privacy Policy.')}
114
+ </label>
115
+ {' '}
116
+ <a href={resolved.terms} target="_blank" rel="noreferrer noopener">
117
+ {t('login.terms.terms', 'Terms & Conditions')}
118
+ </a>
119
+ {' · '}
120
+ <a href={resolved.privacy} target="_blank" rel="noreferrer noopener">
121
+ {t('login.terms.privacy', 'Privacy Policy')}
122
+ </a>
123
+ </p>}
124
+
125
+ {attempted && blocked && <p role="alert" style={{ color: '#b00', fontSize: '.875rem' }}>
126
+ {t('login.terms.required',
127
+ 'Please confirm the Terms & Conditions and the Privacy Policy to continue.')}
128
+ </p>}
129
+
130
+ {props.footer ?? <p style={{ marginTop: '2rem', fontSize: '.75rem', opacity: .7 }}>
131
+ {credit.poweredBy && <span>{t('login.credit.powered', 'Powered by OwlMeans')}</span>}
132
+ {credit.poweredBy && credit.line != null && ' · '}
133
+ {credit.line}
134
+ </p>}
135
+ </div></div>
136
+ }
@@ -0,0 +1,195 @@
1
+ import { createLazyService } from '@owlmeans/context'
2
+ import type { BasicConfig, BasicContext } from '@owlmeans/context'
3
+ import type { CommonConfig } from '@owlmeans/config'
4
+ import { DEFAULT_ALIAS } from './consts.js'
5
+ import { defaultLoginEnv } from './env.js'
6
+ import { adoptToken, revokeToken } from './adopt.js'
7
+ import { resolveLoginMethods } from './methods.js'
8
+ import { LoginOutcome } from './types.js'
9
+ import type {
10
+ LoginContext, LoginMethodSource, LoginNotifier, LoginPlugin, LoginPrecondition,
11
+ LoginScreenComponent, LoginService, LoginServiceAppend
12
+ } from './types.js'
13
+
14
+ /**
15
+ * Login service = plugin host. It holds a registry of login plugins and, on every facade call,
16
+ * resolves the active plugin by cascade (priority desc, first whose `match(env)` is truthy) and
17
+ * delegates to it.
18
+ *
19
+ * The facade methods stay ordinary writable properties (never getters) so that non-plugin
20
+ * implementations — e.g. a native login service — can keep overriding them directly.
21
+ *
22
+ * It is a LAZY service on purpose. The host carries no async setup, and plugin packages must be
23
+ * able to reach it from an app's `makeContext` — i.e. while the context is still in the Loading
24
+ * stage. `context.service()` throws for an uninitialized non-lazy service, which would make
25
+ * `ensureLoginService` fail exactly where apps are told to call it.
26
+ *
27
+ * `begin` and `logout` are deliberately NOT `async`. An async facade method defers the plugin's
28
+ * body past a microtask boundary, and a `window.open` that lands after the user gesture has
29
+ * finished being handled is eaten by the popup blocker. The same rule binds every plugin's own
30
+ * `begin` and `logout`, and it is why a precondition must be synchronous too.
31
+ */
32
+ export const makeLoginService = (alias: string = DEFAULT_ALIAS): LoginService => {
33
+ const plugins: LoginPlugin[] = []
34
+ const preconditions: LoginPrecondition[] = []
35
+ const methodSources: LoginMethodSource[] = []
36
+ let screen: LoginScreenComponent | null = null
37
+ let notifier: LoginNotifier | null = null
38
+
39
+ const ctx = (): LoginContext => service.ctx as LoginContext
40
+
41
+ const service: LoginService = createLazyService<LoginService>(alias, {
42
+ registerPlugin: (plugin: LoginPlugin) => {
43
+ const existing = plugins.findIndex(candidate => candidate.alias === plugin.alias)
44
+ if (existing >= 0) {
45
+ plugins.splice(existing, 1)
46
+ }
47
+ plugins.push(plugin)
48
+ plugins.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
49
+ },
50
+
51
+ registerPrecondition: (precondition: LoginPrecondition) => {
52
+ const existing = preconditions.findIndex(candidate => candidate.alias === precondition.alias)
53
+ if (existing >= 0) {
54
+ preconditions.splice(existing, 1)
55
+ }
56
+ preconditions.push(precondition)
57
+ preconditions.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
58
+ },
59
+
60
+ registerMethodSource: (source: LoginMethodSource) => {
61
+ const existing = methodSources.findIndex(candidate => candidate.alias === source.alias)
62
+ if (existing >= 0) {
63
+ methodSources.splice(existing, 1)
64
+ }
65
+ methodSources.push(source)
66
+ },
67
+
68
+ methods: methodCtx => resolveLoginMethods(
69
+ methodCtx,
70
+ (methodCtx.context.cfg as CommonConfig).security?.auth?.login,
71
+ methodSources
72
+ ),
73
+
74
+ registerScreen: value => { screen = value },
75
+
76
+ screen: () => screen,
77
+
78
+ registerNotifier: value => { notifier = value },
79
+
80
+ plugin: env => {
81
+ const environment = env ?? defaultLoginEnv()
82
+ const plugin = plugins.find(
83
+ candidate => candidate.match?.(environment, service.ctx as LoginContext | undefined) ?? true
84
+ )
85
+ if (plugin == null) {
86
+ throw new Error('login: no plugin matches the current environment')
87
+ }
88
+ return plugin
89
+ },
90
+
91
+ env: () => defaultLoginEnv(),
92
+
93
+ enter: () => {
94
+ const env = defaultLoginEnv()
95
+ service.plugin(env).enter?.(ctx(), env)
96
+ },
97
+
98
+ begin: request => {
99
+ const env = defaultLoginEnv()
100
+ // Synchronously, before anything can open a window: a precondition that refuses leaves the
101
+ // user exactly where `Gesture` describes — unable to proceed until they act again.
102
+ for (const precondition of preconditions) {
103
+ if (!precondition.check(ctx(), request, env)) {
104
+ return Promise.resolve(LoginOutcome.Gesture)
105
+ }
106
+ }
107
+
108
+ // Notified here, in the facade, rather than by each caller: `useLogin` fires the flow and
109
+ // forgets the result, and this is the one place every caller — the header hook and the
110
+ // sign-in screen's method buttons alike — passes through on the way to a settled outcome.
111
+ return service.plugin(env).begin(ctx(), request, env).then(outcome => {
112
+ notifier?.(outcome, env)
113
+
114
+ return outcome
115
+ })
116
+ },
117
+
118
+ authorize: async url => {
119
+ const env = defaultLoginEnv()
120
+
121
+ return await service.plugin(env).authorize(ctx(), url, env)
122
+ },
123
+
124
+ complete: async token => {
125
+ const env = defaultLoginEnv()
126
+
127
+ return await service.plugin(env).complete(ctx(), token, env)
128
+ },
129
+
130
+ resume: async token => {
131
+ const env = defaultLoginEnv()
132
+ // Absent means "keep it and carry on" — which is what an ordinary tab has always done, and
133
+ // is why the redirect plugin implements nothing here.
134
+ return await service.plugin(env).resume?.(ctx(), token, env) ?? LoginOutcome.Passed
135
+ },
136
+
137
+ logout: request => {
138
+ const env = defaultLoginEnv()
139
+ const plugin = service.plugin(env)
140
+ if (plugin.logout == null) {
141
+ // A plugin with no logout mechanic still has to end the session it started.
142
+ return revokeToken(ctx()).then(async () => {
143
+ await request.navigate?.()
144
+
145
+ return LoginOutcome.Passed
146
+ })
147
+ }
148
+
149
+ return plugin.logout(ctx(), request, env).then(outcome => {
150
+ notifier?.(outcome, env)
151
+
152
+ return outcome
153
+ })
154
+ },
155
+
156
+ logoutComplete: async () => {
157
+ const env = defaultLoginEnv()
158
+
159
+ return await service.plugin(env).logoutComplete?.(ctx(), env) ?? LoginOutcome.Passed
160
+ },
161
+
162
+ adopt: async token => { await adoptToken(ctx(), token) },
163
+
164
+ revoke: async () => { await revokeToken(ctx()) },
165
+ })
166
+
167
+ return service
168
+ }
169
+
170
+ /**
171
+ * Idempotently obtain the login service on a context, registering an empty host if none exists
172
+ * yet. Plugin packages call this before `registerPlugin`.
173
+ */
174
+ export const ensureLoginService = (ctx: BasicContext<any>): LoginService => {
175
+ if (ctx.hasService(DEFAULT_ALIAS)) {
176
+ return ctx.service<LoginService>(DEFAULT_ALIAS)
177
+ }
178
+ const service = makeLoginService()
179
+ ctx.registerService(service)
180
+
181
+ return service
182
+ }
183
+
184
+ /** Register the host and expose it as `context.login()`. */
185
+ export const appendLogin = <C extends BasicConfig, T extends BasicContext<C>>(
186
+ ctx: T
187
+ ): T & LoginServiceAppend => {
188
+ ensureLoginService(ctx)
189
+ const contextual = ctx as T & LoginServiceAppend
190
+ contextual.login = () => ctx.service<LoginService>(DEFAULT_ALIAS)
191
+
192
+ return contextual
193
+ }
194
+
195
+ export { LoginOutcome }
@@ -0,0 +1,45 @@
1
+ import { DISPATCHER_SURROGATE } from '@owlmeans/auth'
2
+ import type { ClientEntrypoint } from '@owlmeans/client-entrypoint'
3
+ import { LOGIN_INTENT_QUERY, LOGIN_METHOD_QUERY, LOGIN_NEXT_QUERY } from './consts.js'
4
+ import { LoginIntent } from './types.js'
5
+ import type { LoginContext } from './types.js'
6
+
7
+ export interface SurrogateTarget {
8
+ intent: LoginIntent
9
+ /** The address the surrogate should actually run, once it is one window up. */
10
+ next?: string
11
+ /** The method the user already chose in the opener. */
12
+ method?: string
13
+ }
14
+
15
+ /**
16
+ * Where a surrogate window opens.
17
+ *
18
+ * Returns `null` when the application's entrypoint list predates the surrogate route — an app
19
+ * built against an older `@owlmeans/auth-common` has no such entrypoint, and the caller then falls
20
+ * back to opening the dispatcher directly, which is exactly what it used to do. That fallback is
21
+ * the whole compatibility story for already-deployed applications, so it must never be removed in
22
+ * favour of throwing.
23
+ */
24
+ export const surrogatePath = (ctx: LoginContext, target: SurrogateTarget): string | null => {
25
+ if (!ctx.hasEntrypoint(DISPATCHER_SURROGATE)) {
26
+ return null
27
+ }
28
+ let path: string
29
+ try {
30
+ path = ctx.entrypoint<ClientEntrypoint>(DISPATCHER_SURROGATE).path()
31
+ } catch {
32
+ return null
33
+ }
34
+
35
+ const query = new URLSearchParams()
36
+ query.set(LOGIN_INTENT_QUERY, target.intent)
37
+ if (target.next != null && target.next !== '') {
38
+ query.set(LOGIN_NEXT_QUERY, target.next)
39
+ }
40
+ if (target.method != null && target.method !== '') {
41
+ query.set(LOGIN_METHOD_QUERY, target.method)
42
+ }
43
+
44
+ return `${path}?${query.toString()}`
45
+ }
Binary file