@authlor/browser 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +134 -2
- package/account-ui/THIRD_PARTY_NOTICES.txt +518 -0
- package/account-ui/assets/GoogleSansCode-VariableFont_MONO_wght-CUQnOM0p.ttf +0 -0
- package/account-ui/assets/Inter-VariableFont_opsz_wght-c8O0ljhh.ttf +0 -0
- package/account-ui/assets/index-2UhP_hst.js +17 -0
- package/account-ui/assets/index-BKdNzoP5.css +1 -0
- package/account-ui/index.js +5 -0
- package/index.d.ts +43 -0
- package/index.js +179 -0
- package/native-client.js +249 -0
- package/navigation.js +45 -0
- package/package.json +10 -4
package/native-client.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
const opaque = () => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replaceAll('+','-').replaceAll('/','_').replaceAll('=','');
|
|
2
|
+
const base64 = (buffer) => btoa(String.fromCharCode(...new Uint8Array(buffer))).replaceAll('+','-').replaceAll('/','_').replaceAll('=','');
|
|
3
|
+
const uiLoads = new Map();
|
|
4
|
+
|
|
5
|
+
export function createNativeClient({ publishableKey, resolveEndpoint, legacy, legacyCookie = false }) {
|
|
6
|
+
let metadata, discovery, refreshing, loading, loaded = false, session = null, timer, ui, userMount, mounting, mountedElement, mountGeneration = 0;
|
|
7
|
+
let lastActivity = 0, lastActivitySent = 0, failures = 0, sessionGeneration = 0, destroyed = false, signingOut = false;
|
|
8
|
+
const imageUrls = new Set();
|
|
9
|
+
const listeners = new Set();
|
|
10
|
+
const storageKey = `authlor:${publishableKey}:client`;
|
|
11
|
+
const flowKey = `authlor:${publishableKey}:handshake`;
|
|
12
|
+
const cookieName = () => `${location.protocol === 'https:' && !legacyCookie ? '__Host-' : ''}authlor_session_${metadata.instanceId.slice(4)}`;
|
|
13
|
+
const channel = typeof BroadcastChannel === 'function' ? new BroadcastChannel(`authlor:${publishableKey}`) : null;
|
|
14
|
+
let flowAuthorization;
|
|
15
|
+
const readCredential = () => { try { return sessionStorage.getItem(storageKey); } catch { return null; } };
|
|
16
|
+
const clearCredential = () => { try { sessionStorage.removeItem(storageKey); } catch {} };
|
|
17
|
+
function saveCredential(value) {
|
|
18
|
+
if (metadata.environment === 'production') { clearCredential(); return; }
|
|
19
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(value)) throw new Error('Invalid browser renewal credential.');
|
|
20
|
+
sessionStorage.setItem(storageKey, value);
|
|
21
|
+
}
|
|
22
|
+
async function discover() {
|
|
23
|
+
discovery ??= Promise.resolve(resolveEndpoint()).then(async (endpoint) => {
|
|
24
|
+
const url = new URL(`/api/native/${encodeURIComponent(publishableKey)}/`, endpoint);
|
|
25
|
+
const response = await fetch(url, { credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(10000) });
|
|
26
|
+
if (!response.ok) throw new Error('Could not discover the native Authlor instance.');
|
|
27
|
+
const value = await response.json();
|
|
28
|
+
if (value.version !== 2 || value.origin !== url.origin || !/^ins_[A-Za-z0-9]{28}$/.test(value.instanceId) ||
|
|
29
|
+
!/^app_[A-Za-z0-9]{28}$/.test(value.appId) || !['development','staging','production'].includes(value.environment) ||
|
|
30
|
+
value.environment !== 'development' && (url.protocol !== 'https:' || location.protocol !== 'https:') ||
|
|
31
|
+
value.endpoints !== url.pathname.slice(0, -1)) throw new Error('Invalid Authlor discovery.');
|
|
32
|
+
metadata = { ...value, endpoint: url };
|
|
33
|
+
if (metadata.environment === 'production') clearCredential();
|
|
34
|
+
return metadata;
|
|
35
|
+
}).catch((error) => { discovery = undefined; throw error; });
|
|
36
|
+
return discovery;
|
|
37
|
+
}
|
|
38
|
+
async function request(operation, body = {}, account = false) {
|
|
39
|
+
await discover();
|
|
40
|
+
const credential = metadata.environment === 'production' ? null : readCredential();
|
|
41
|
+
const response = await fetch(new URL(operation, metadata.endpoint), { method: 'POST', redirect: 'error',
|
|
42
|
+
credentials: metadata.environment === 'production' ? 'include' : 'omit', signal: AbortSignal.timeout(12000),
|
|
43
|
+
headers: { 'Content-Type': 'application/json', ...(credential && { 'X-Authlor-Client': credential }),
|
|
44
|
+
...(account && session?.accountToken && { Authorization: `Bearer ${session.accountToken}` }) }, body: JSON.stringify(body) });
|
|
45
|
+
const result = response.status === 204 ? null : await response.json().catch(() => null);
|
|
46
|
+
if (!response.ok) throw Object.assign(new Error(result?.message ?? 'Could not complete the Authlor request.'), { status: response.status, code: result?.code });
|
|
47
|
+
return result;
|
|
48
|
+
}
|
|
49
|
+
function update(result) {
|
|
50
|
+
if (result && (typeof result.token !== 'string' || typeof result.accountToken !== 'string' || !Number.isFinite(result.expiresAt) || result.expiresAt <= Date.now())) throw new Error('Authlor returned an invalid session.');
|
|
51
|
+
const previousSubject = session?.user?.id;
|
|
52
|
+
session = result;
|
|
53
|
+
if (!result) clearCredential();
|
|
54
|
+
if (!result && previousSubject) channel?.postMessage({ type: 'signed-out', subject: previousSubject });
|
|
55
|
+
if (metadata) document.cookie = `${cookieName()}=${result?.token ?? ''}; Path=/; SameSite=Lax; Max-Age=${result ? Math.max(0, Math.floor((result.expiresAt - Date.now()) / 1000)) : 0}${location.protocol === 'https:' ? '; Secure' : ''}`;
|
|
56
|
+
for (const listener of listeners) listener({ user: result?.user ?? null, signedIn: !!result });
|
|
57
|
+
}
|
|
58
|
+
async function refresh(activity = false) {
|
|
59
|
+
if (destroyed || signingOut) return session;
|
|
60
|
+
const generation = sessionGeneration;
|
|
61
|
+
refreshing ??= (async () => {
|
|
62
|
+
try {
|
|
63
|
+
const active = activity || lastActivity > lastActivitySent;
|
|
64
|
+
const result = await request('session', { activity: active });
|
|
65
|
+
if (generation !== sessionGeneration || destroyed || signingOut) return session;
|
|
66
|
+
update(result);
|
|
67
|
+
failures = 0;
|
|
68
|
+
if (active) lastActivitySent = Date.now();
|
|
69
|
+
return session;
|
|
70
|
+
} catch (error) { if (generation === sessionGeneration && !destroyed && !signingOut) { failures++; if (error.status === 401 || error.status === 403 || error.status === 404) update(null); } throw error; }
|
|
71
|
+
finally { refreshing = undefined; }
|
|
72
|
+
})();
|
|
73
|
+
return refreshing;
|
|
74
|
+
}
|
|
75
|
+
function schedule() {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
if (!loaded) return;
|
|
78
|
+
const delay = failures ? Math.min(50000, 2000 * 2 ** Math.min(failures, 5)) : session ? Math.max(1000, session.expiresAt - Date.now() - 10000) : 50000;
|
|
79
|
+
timer = setTimeout(async () => { try { await refresh(); } catch {} finally { schedule(); } }, Math.min(50000, delay));
|
|
80
|
+
}
|
|
81
|
+
async function prepare({ returnTo = location.pathname + location.search, addAccount = false } = {}) {
|
|
82
|
+
const destination = new URL(returnTo, location.origin);
|
|
83
|
+
if (destination.origin !== location.origin || destination.username || destination.password || destination.hash) throw new Error('Return to a route on this application.');
|
|
84
|
+
const verifier = opaque(), state = opaque();
|
|
85
|
+
const challenge = base64(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)));
|
|
86
|
+
sessionStorage.setItem(flowKey, JSON.stringify({ verifier, state, expires: Date.now() + 300000 }));
|
|
87
|
+
const result = await request('authorize', { state, challenge, returnTo: destination.href, addAccount });
|
|
88
|
+
flowAuthorization = result.authorization;
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
async function load() {
|
|
92
|
+
if (destroyed) throw new Error('This Authlor client has been destroyed.');
|
|
93
|
+
if (loaded) return client;
|
|
94
|
+
const generation = sessionGeneration;
|
|
95
|
+
loading ??= (async () => {
|
|
96
|
+
await discover();
|
|
97
|
+
const fragment = new URLSearchParams(location.hash.slice(1));
|
|
98
|
+
if (fragment.has('authlor_code')) {
|
|
99
|
+
history.replaceState(history.state, '', location.pathname + location.search);
|
|
100
|
+
let flow;
|
|
101
|
+
try { flow = JSON.parse(sessionStorage.getItem(flowKey)); } catch {}
|
|
102
|
+
sessionStorage.removeItem(flowKey);
|
|
103
|
+
if (!flow || flow.expires <= Date.now() || flow.state !== fragment.get('authlor_state')) throw new Error('Authentication expired. Start sign-in again.');
|
|
104
|
+
const result = await request('redeem', { code: fragment.get('authlor_code'), state: flow.state, verifier: flow.verifier });
|
|
105
|
+
if (destroyed || generation !== sessionGeneration) return client;
|
|
106
|
+
if (result.credential) saveCredential(result.credential);
|
|
107
|
+
update(result); channel?.postMessage({ type: 'changed' });
|
|
108
|
+
} else if (fragment.get('authlor_signin') === '1') {
|
|
109
|
+
history.replaceState(history.state, '', location.pathname + location.search);
|
|
110
|
+
return client.redirectToSignIn();
|
|
111
|
+
} else {
|
|
112
|
+
try { await refresh(); } catch (error) { if (error.status !== 401) throw error; }
|
|
113
|
+
}
|
|
114
|
+
if (destroyed || generation !== sessionGeneration) return client;
|
|
115
|
+
loaded = true;
|
|
116
|
+
addEventListener('online', resume);
|
|
117
|
+
document.addEventListener('visibilitychange', resume);
|
|
118
|
+
document.addEventListener('pointerdown', interacted, { passive: true });
|
|
119
|
+
document.addEventListener('keydown', interacted, { passive: true });
|
|
120
|
+
schedule();
|
|
121
|
+
if (session && sessionStorage.getItem(`${flowKey}:account`) === '1') {
|
|
122
|
+
sessionStorage.removeItem(`${flowKey}:account`);
|
|
123
|
+
queueMicrotask(() => void client.openUserProfile().catch(() => {}));
|
|
124
|
+
}
|
|
125
|
+
return client;
|
|
126
|
+
})().catch((error) => { loading = undefined; throw error; });
|
|
127
|
+
return loading;
|
|
128
|
+
}
|
|
129
|
+
function interacted() { lastActivity = Date.now(); }
|
|
130
|
+
function resume() { if (loaded && document.visibilityState !== 'hidden') void refresh().catch(() => {}).finally(schedule); }
|
|
131
|
+
if (channel) channel.onmessage = (event) => {
|
|
132
|
+
if (event.data?.type === 'signed-out' && event.data.subject === session?.user?.id) { sessionGeneration++; update(null); client.closeUserProfile(); }
|
|
133
|
+
else if (event.data?.type === 'credential-rotated' && event.data.clientId && event.data.clientId === session?.clientId) { sessionGeneration++; update(null); client.closeUserProfile(); }
|
|
134
|
+
else if (event.data?.type === 'changed') { sessionGeneration++; void Promise.resolve(refreshing).catch(() => {}).then(resume); }
|
|
135
|
+
};
|
|
136
|
+
async function popup(kind, provider) {
|
|
137
|
+
const child = window.open('about:blank', 'authlor-account-action', 'popup,width=620,height=760');
|
|
138
|
+
if (!child) throw new Error('Allow popups to continue.');
|
|
139
|
+
const nonce = opaque();
|
|
140
|
+
try {
|
|
141
|
+
await client.getToken();
|
|
142
|
+
if (!session) { child.close(); return client.redirectToSignIn(); }
|
|
143
|
+
const result = await request('popup', { kind, provider, nonce }, true);
|
|
144
|
+
const target = new URL(result.url);
|
|
145
|
+
if (target.origin !== metadata.origin || target.username || target.password) throw new Error('Invalid account popup destination.');
|
|
146
|
+
child.location.replace(target.href);
|
|
147
|
+
await new Promise((resolve, reject) => {
|
|
148
|
+
const timeout = setTimeout(() => finish(new Error('Account verification timed out.')), 300000);
|
|
149
|
+
const poll = setInterval(() => { if (child.closed) finish(new Error('Canceled.')); }, 500);
|
|
150
|
+
const receive = (event) => { if (event.origin === metadata.origin && event.source === child && event.data?.nonce === nonce && event.data?.type === 'authlor:account-action') finish(event.data.error ? new Error(event.data.error) : null); };
|
|
151
|
+
function finish(error) { clearTimeout(timeout); clearInterval(poll); removeEventListener('message', receive); child.close(); error ? reject(error) : resolve(); }
|
|
152
|
+
addEventListener('message', receive);
|
|
153
|
+
});
|
|
154
|
+
await refresh();
|
|
155
|
+
} catch (error) { child.close(); throw error; }
|
|
156
|
+
}
|
|
157
|
+
async function uiModule() {
|
|
158
|
+
const key = 'packaged-0.3.0';
|
|
159
|
+
if (!uiLoads.has(key)) uiLoads.set(key, import('./account-ui/index.js').then((module) => ({ module, manifest: module.manifest }))
|
|
160
|
+
.catch((error) => { uiLoads.delete(key); throw error; }));
|
|
161
|
+
return uiLoads.get(key);
|
|
162
|
+
}
|
|
163
|
+
async function accountRequest(url, init = {}) {
|
|
164
|
+
await client.getToken();
|
|
165
|
+
if (!session) throw Object.assign(new Error('Sign in to continue.'), { sessionExpired: true, status: 401 });
|
|
166
|
+
const target = new URL(url, metadata.origin);
|
|
167
|
+
const accountPath = `/api/hosted-apps/${metadata.appId}/account`;
|
|
168
|
+
if (target.origin !== metadata.origin || target.username || target.password || target.hash || !(target.pathname === accountPath || target.pathname.startsWith(accountPath + '/'))) throw new Error('Account requests must use the Authlor account API.');
|
|
169
|
+
const switching = target.pathname === accountPath + '/accounts/switch' && (init.method ?? 'GET').toUpperCase() === 'POST';
|
|
170
|
+
const renewal = switching && metadata.environment !== 'production' ? readCredential() : null;
|
|
171
|
+
const headers = new Headers(init.headers);
|
|
172
|
+
headers.delete('X-Authlor-Client');
|
|
173
|
+
if (renewal) headers.set('X-Authlor-Client', renewal);
|
|
174
|
+
headers.set('Authorization', `Bearer ${session.accountToken}`);
|
|
175
|
+
const response = await fetch(target, { ...init, credentials: metadata.environment === 'production' ? 'include' : 'omit', redirect: 'error',
|
|
176
|
+
signal: init.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(12000)]) : AbortSignal.timeout(12000),
|
|
177
|
+
headers });
|
|
178
|
+
if (!response.ok) {
|
|
179
|
+
const data = await response.json().catch(() => null);
|
|
180
|
+
throw Object.assign(new Error(data?.message ?? 'Could not update the account.'), { sessionExpired: response.status === 401, status: response.status, signIn: data?.code === 'reauth_required' });
|
|
181
|
+
}
|
|
182
|
+
const result = response.status === 204 ? undefined : response.headers.get('content-type')?.includes('json') ? await response.json() : await response.blob();
|
|
183
|
+
if (result?.switched === true) {
|
|
184
|
+
sessionGeneration++;
|
|
185
|
+
if (result.credential) saveCredential(result.credential);
|
|
186
|
+
if (metadata.environment === 'production') channel?.postMessage({ type: 'changed' });
|
|
187
|
+
else channel?.postMessage({ type: 'credential-rotated', clientId: session?.clientId });
|
|
188
|
+
if (refreshing) await refreshing.catch(() => {});
|
|
189
|
+
}
|
|
190
|
+
if (!['GET','HEAD'].includes((init.method ?? 'GET').toUpperCase())) {
|
|
191
|
+
try { await refresh(true); } catch (error) { if (error.status !== 401) throw error; }
|
|
192
|
+
}
|
|
193
|
+
if (!result || result instanceof Blob) return result;
|
|
194
|
+
if (result?.imageUrl) {
|
|
195
|
+
const imageUrl = new URL(result.imageUrl, metadata.origin);
|
|
196
|
+
if (imageUrl.origin !== metadata.origin || imageUrl.username || imageUrl.password || !imageUrl.pathname.startsWith(accountPath + '/')) throw new Error('Invalid account image URL.');
|
|
197
|
+
const image = await fetch(imageUrl, { headers: { Authorization: `Bearer ${session.accountToken}` }, credentials: 'omit', redirect: 'error', signal: init.signal ?? AbortSignal.timeout(12000) });
|
|
198
|
+
result.imageUrl = image.ok ? URL.createObjectURL(await image.blob()) : null;
|
|
199
|
+
if (result.imageUrl) imageUrls.add(result.imageUrl);
|
|
200
|
+
}
|
|
201
|
+
if (result?.defaultAvatarUrl) {
|
|
202
|
+
const avatar = new URL(result.defaultAvatarUrl, metadata.origin);
|
|
203
|
+
if (avatar.origin !== metadata.origin || avatar.username || avatar.password || !avatar.pathname.startsWith(`/api/hosted-apps/${metadata.appId}/default-avatar/`)) throw new Error('Invalid default avatar URL.');
|
|
204
|
+
result.defaultAvatarUrl = avatar.href;
|
|
205
|
+
}
|
|
206
|
+
return result;
|
|
207
|
+
}
|
|
208
|
+
const client = {
|
|
209
|
+
...legacy,
|
|
210
|
+
load, get user() { return session?.user ?? null; },
|
|
211
|
+
subscribe(listener) { listeners.add(listener); listener({ user: session?.user ?? null, signedIn: !!session }); return () => listeners.delete(listener); },
|
|
212
|
+
async getToken() { await load(); if (!session || session.expiresAt - Date.now() < 10000) { try { await refresh(); } catch (error) { if (error.status !== 401) throw error; } } return session?.token ?? null; },
|
|
213
|
+
async redirectToSignIn(options) { const result = await prepare(options); const url = new URL(result.url); if (url.origin !== metadata.origin || url.username || url.password) throw new Error('Invalid sign-in destination.'); location.assign(url.href); },
|
|
214
|
+
async signIn(body) { const flow = body.authorization ?? flowAuthorization ?? (await prepare()).authorization; return legacy.signIn({ ...body, authorization: flow }); },
|
|
215
|
+
async signUp(body) { const flow = body.authorization ?? flowAuthorization ?? (await prepare()).authorization; return legacy.signUp({ ...body, authorization: flow }); },
|
|
216
|
+
async signInWithSocial(provider, authorization, options) { return legacy.signInWithSocial(provider, authorization ?? (await prepare()).authorization, options); },
|
|
217
|
+
// WebAuthn must execute on the existing accounts-domain RP, never the embedding application origin.
|
|
218
|
+
async signInWithPasskey() { await client.redirectToSignIn(); },
|
|
219
|
+
async registerPasskey() { await popup('passkey'); return { status: 'passkey_registered' }; },
|
|
220
|
+
async linkSocialAccount(provider) { await popup('social', provider); },
|
|
221
|
+
async signOut() { sessionGeneration++; signingOut = true; try { await request('sign-out'); sessionGeneration++; update(null); client.closeUserProfile(); } finally { signingOut = false; schedule(); } },
|
|
222
|
+
async mountUserProfile(element) {
|
|
223
|
+
if (!(element instanceof HTMLElement)) throw new Error('Provide an account container element.');
|
|
224
|
+
const requestedGeneration = mountGeneration;
|
|
225
|
+
await load();
|
|
226
|
+
if (destroyed || requestedGeneration !== mountGeneration) return;
|
|
227
|
+
if (!session) { sessionStorage.setItem(`${flowKey}:account`, '1'); await client.redirectToSignIn(); return; }
|
|
228
|
+
ui ??= await uiModule();
|
|
229
|
+
if (destroyed || !session || signingOut || requestedGeneration !== mountGeneration) return;
|
|
230
|
+
if (mounting) { await mounting; if (mountedElement === element && userMount) return; }
|
|
231
|
+
if (destroyed || requestedGeneration !== mountGeneration) return;
|
|
232
|
+
client.closeUserProfile();
|
|
233
|
+
const generation = mountGeneration; mountedElement = element;
|
|
234
|
+
mounting = ui.module.mountUserProfile(element, { metadata, manifest: ui.manifest, accountRequest,
|
|
235
|
+
registerPasskey: () => popup('passkey'), linkSocialAccount: (provider) => popup('social', provider),
|
|
236
|
+
reverify: () => popup('reverify'), signOut: client.signOut, close: client.closeUserProfile,
|
|
237
|
+
addAccount: async () => { sessionStorage.setItem(`${flowKey}:account`, '1'); await client.redirectToSignIn({ addAccount: true }); }, changed: async () => { await refresh(); channel?.postMessage({ type: 'changed' }); },
|
|
238
|
+
ended: () => { sessionGeneration++; update(null); client.closeUserProfile(); } })
|
|
239
|
+
.then((unmount) => { if (generation !== mountGeneration) unmount(); else userMount = unmount; })
|
|
240
|
+
.finally(() => { mounting = undefined; });
|
|
241
|
+
await mounting;
|
|
242
|
+
},
|
|
243
|
+
async openUserProfile() { let element = document.getElementById(`authlor-account-${publishableKey}`); if (!element) { element = document.createElement('div'); element.id = `authlor-account-${publishableKey}`; document.body.append(element); } await client.mountUserProfile(element); },
|
|
244
|
+
closeUserProfile() { mountGeneration++; userMount?.(); userMount = undefined; mountedElement = undefined; for (const url of imageUrls) URL.revokeObjectURL(url); imageUrls.clear(); },
|
|
245
|
+
unmountUserProfile() { client.closeUserProfile(); },
|
|
246
|
+
destroy() { destroyed = true; sessionGeneration++; loaded = false; clearTimeout(timer); removeEventListener('online', resume); document.removeEventListener('visibilitychange', resume); document.removeEventListener('pointerdown', interacted); document.removeEventListener('keydown', interacted); channel?.close(); client.closeUserProfile(); listeners.clear(); },
|
|
247
|
+
};
|
|
248
|
+
return client;
|
|
249
|
+
}
|
package/navigation.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
const providers = {
|
|
2
|
+
google: ['https://accounts.google.com/o/oauth2/v2/auth'],
|
|
3
|
+
github: ['https://github.com/login/oauth/authorize'],
|
|
4
|
+
microsoft: ['https://login.microsoftonline.com/common/oauth2/v2.0/authorize'],
|
|
5
|
+
apple: ['https://appleid.apple.com/auth/authorize'],
|
|
6
|
+
discord: ['https://discord.com/api/oauth2/authorize'],
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
function destination(value, base) {
|
|
10
|
+
if (typeof value !== 'string' || !value || /[\u0000-\u0020\u007f\\]/.test(value)) throw new Error('Invalid authentication destination.');
|
|
11
|
+
const url = new URL(value, base);
|
|
12
|
+
const loopback = ['localhost','127.0.0.1','[::1]'].includes(url.hostname);
|
|
13
|
+
if (url.username || url.password || url.protocol !== 'https:' && !(loopback && url.protocol === 'http:')) throw new Error('Invalid authentication destination.');
|
|
14
|
+
return url;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function socialDestination(value, provider) {
|
|
18
|
+
const url = destination(value);
|
|
19
|
+
if (url.hash || !(providers[provider] ?? []).includes(url.origin + url.pathname)) throw new Error('Unregistered social authorization destination.');
|
|
20
|
+
return url.href;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function matchesRegistered(url, registered) {
|
|
24
|
+
const target = destination(registered);
|
|
25
|
+
return !url.hash && url.origin === target.origin && url.pathname === target.pathname &&
|
|
26
|
+
[...target.searchParams].every(([key, value]) => url.searchParams.getAll(key).length === 1 && url.searchParams.get(key) === value);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function completionDestination(value, endpoint, metadata) {
|
|
30
|
+
const url = destination(value, endpoint);
|
|
31
|
+
const callbacks = Array.isArray(metadata.callbacks) ? metadata.callbacks : [];
|
|
32
|
+
if (callbacks.some((callback) => matchesRegistered(url, callback))) return url.href;
|
|
33
|
+
const destinations = Object.values(metadata.destinations ?? {}).filter((item) => typeof item === 'string');
|
|
34
|
+
if (destinations.some((target) => destination(target).href === url.href)) return url.href;
|
|
35
|
+
const origin = new URL(endpoint).origin;
|
|
36
|
+
const issuer = destination(metadata.issuer);
|
|
37
|
+
if (url.origin !== origin || issuer.origin !== origin) throw new Error('Unregistered completion destination.');
|
|
38
|
+
if (url.pathname === issuer.pathname + '/oauth2/authorize' && !url.hash && callbacks.includes(url.searchParams.get('redirect_uri'))) return url.href;
|
|
39
|
+
const login = destination(metadata.hostedUrls?.signIn);
|
|
40
|
+
const pageRoot = login.pathname.replace(/\/login$/, '/');
|
|
41
|
+
const pages = ['login','account','mfa','passkey-setup'].map((page) => pageRoot + page);
|
|
42
|
+
const nativeComplete = `/api/native/${encodeURIComponent(metadata.publishableKey)}/complete`;
|
|
43
|
+
if (login.origin === origin && pages.includes(url.pathname) || url.pathname === nativeComplete && !url.hash) return url.href;
|
|
44
|
+
throw new Error('Unregistered completion destination.');
|
|
45
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@authlor/browser",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Authlor browser SDK by Vyslor: authentication and on-demand account management.",
|
|
5
|
+
"author": "Vyslor",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://authlor.com",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"exports": { ".": { "types": "./index.d.ts", "default": "./index.js" } },
|
|
10
|
+
"files": ["index.js", "index.d.ts", "native-client.js", "navigation.js", "account-ui/index.js", "account-ui/assets", "account-ui/THIRD_PARTY_NOTICES.txt", "README.md", "LICENSE"],
|
|
11
|
+
"publishConfig": { "registry": "https://registry.npmjs.org", "access": "public", "provenance": false }
|
|
12
|
+
}
|