@authlor/browser 0.0.0-stage → 0.3.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 +29 -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-DM1YaOig.css +1 -0
- package/account-ui/assets/index-DdKBGKhQ.js +17 -0
- package/account-ui/index.js +5 -0
- package/index.d.ts +43 -0
- package/index.js +179 -0
- package/native-client.js +246 -0
- package/navigation.js +45 -0
- package/package.json +10 -4
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Generated at SDK build time. Executable code and assets are pinned by the npm artifact.
|
|
2
|
+
export { mountUserProfile } from "./assets/index-DdKBGKhQ.js";
|
|
3
|
+
export const manifest = { styles: [new URL("./assets/index-DM1YaOig.css", import.meta.url).href], fonts: {
|
|
4
|
+
inter: new URL("./assets/Inter-VariableFont_opsz_wght-c8O0ljhh.ttf", import.meta.url).href,
|
|
5
|
+
code: new URL("./assets/GoogleSansCode-VariableFont_MONO_wght-CUQnOM0p.ttf", import.meta.url).href } };
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
type Authorization = { nativeTicket: string } | { redirectUri: string; state: string; nonce: string; codeChallenge: string } | { oauthQuery: string } | { accountAction: 'open' | 'security' | 'add' | 'reverify' };
|
|
2
|
+
type Complete = { status: 'complete'; ticket: string };
|
|
3
|
+
type NeedsSms = { status: 'needs_sms_code'; attemptId: string };
|
|
4
|
+
type AuthResult = Complete | NeedsSms | { status: 'needs_email_code' | 'needs_email_link'; attemptId: string };
|
|
5
|
+
type SignIn = ({ email: string } | { username: string } | { phone: string }) & { password?: string; authorization?: Authorization };
|
|
6
|
+
type SignUp = { email?: string; phone?: string; username?: string; password?: string; confirmation?: string; firstName?: string; lastName?: string; legalAccepted?: boolean; authorization?: Authorization; invitation?: string };
|
|
7
|
+
export type HostedAuthClient = {
|
|
8
|
+
signIn(body: SignIn): Promise<AuthResult>;
|
|
9
|
+
signUp(body: SignUp): Promise<AuthResult>;
|
|
10
|
+
continueSession(authorization: Authorization): Promise<{ redirect: string }>;
|
|
11
|
+
getMfaChallenge(challenge: string): Promise<{ authenticator: boolean; backup: boolean; sms?: string; setup?: { key: string; uri: string } }>;
|
|
12
|
+
sendMfaSms(challenge: string): Promise<{ sent: true }>;
|
|
13
|
+
verifyMfa(challenge: string, code: string, method?: 'sms'): Promise<{ redirect: string; backupCodes?: string[] }>;
|
|
14
|
+
signInWithSocial(provider: string, authorization?: Authorization, options?: { returnTo?: 'account'; legalAccepted?: boolean }): Promise<void>;
|
|
15
|
+
linkSocialAccount(provider: string): Promise<void>;
|
|
16
|
+
verifyEmailCode(attemptId: string, code: string): Promise<Complete | NeedsSms>;
|
|
17
|
+
sendSmsCode(attemptId: string): Promise<{ status: 'sms_sent' }>;
|
|
18
|
+
verifySmsCode(attemptId: string, code: string): Promise<Complete>;
|
|
19
|
+
checkEmailLink(attemptId: string): Promise<Complete | NeedsSms | { status: 'needs_email_link' }>;
|
|
20
|
+
confirmEmailLink(token: string): Promise<{ status: 'email_confirmed' }>;
|
|
21
|
+
requestPasswordReset(email: string): Promise<{ status: 'accepted' }>;
|
|
22
|
+
resetPassword(token: string, password: string): Promise<{ status: 'password_reset' }>;
|
|
23
|
+
signInWithPasskey(options?: { authorization?: Authorization; conditional?: boolean; signal?: AbortSignal }): Promise<Complete>;
|
|
24
|
+
registerPasskey(options?: { ticket?: string; signal?: AbortSignal }): Promise<{ status: 'passkey_registered' }>;
|
|
25
|
+
continuePasskeySetup(promptId: string, dismiss: boolean): Promise<{ redirect: string }>;
|
|
26
|
+
finish(result: Complete): Promise<void>;
|
|
27
|
+
};
|
|
28
|
+
export type AuthlorBrowserClient = Omit<HostedAuthClient, 'signInWithPasskey'> & {
|
|
29
|
+
signInWithPasskey(): Promise<void>;
|
|
30
|
+
readonly user: { id: string; name: string; email: string | null } | null;
|
|
31
|
+
load(): Promise<AuthlorBrowserClient>;
|
|
32
|
+
getToken(): Promise<string | null>;
|
|
33
|
+
subscribe(listener: (state: { signedIn: boolean; user: AuthlorBrowserClient['user'] }) => void): () => void;
|
|
34
|
+
redirectToSignIn(options?: { returnTo?: string; addAccount?: boolean }): Promise<void>;
|
|
35
|
+
signOut(): Promise<void>;
|
|
36
|
+
openUserProfile(): Promise<void>;
|
|
37
|
+
closeUserProfile(): void;
|
|
38
|
+
mountUserProfile(element: HTMLElement): Promise<void>;
|
|
39
|
+
unmountUserProfile(): void;
|
|
40
|
+
destroy(): void;
|
|
41
|
+
};
|
|
42
|
+
export function createAuthlorClient(config: { baseUrl?: string; publishableKey: string; hosted: true }): HostedAuthClient;
|
|
43
|
+
export function createAuthlorClient(config: { baseUrl?: string; publishableKey: string; hosted?: false }): AuthlorBrowserClient;
|
package/index.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { createNativeClient } from './native-client.js';
|
|
2
|
+
import { completionDestination, socialDestination } from './navigation.js';
|
|
3
|
+
/** Create a client for browser-to-Authlor authentication. Pass public configuration only. */
|
|
4
|
+
export function createAuthlorClient({ baseUrl, publishableKey, hosted = false, ...unknown }, compatibility = {}) {
|
|
5
|
+
if (!/^pk_(?:test|live)_[A-Za-z0-9_-]{32}$/.test(publishableKey)) throw new Error('Provide an Authlor publishable key.');
|
|
6
|
+
if (Object.keys(unknown).some((name) => /secret|password|private/i.test(name))) throw new Error('Pass public configuration only to the browser SDK.');
|
|
7
|
+
if (baseUrl) {
|
|
8
|
+
const base = new URL(baseUrl);
|
|
9
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname);
|
|
10
|
+
if (base.username || base.password || base.pathname !== '/' || base.search || base.hash ||
|
|
11
|
+
base.protocol !== 'https:' && !(base.protocol === 'http:' && loopback)) throw new Error('Use an HTTPS Authlor origin, or HTTP loopback for Development.');
|
|
12
|
+
}
|
|
13
|
+
const path = `/api/hosted-auth/${encodeURIComponent(publishableKey)}`;
|
|
14
|
+
const explicitEndpoint = baseUrl && new URL(`${path}/`, baseUrl);
|
|
15
|
+
let discovered, navigationPolicy;
|
|
16
|
+
async function completion(value) {
|
|
17
|
+
const endpoint = await resolveEndpoint();
|
|
18
|
+
navigationPolicy ??= fetch(new URL(path, endpoint), { credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(10000) })
|
|
19
|
+
.then(async (response) => {
|
|
20
|
+
if (!response.ok) throw new Error('Could not load registered authentication destinations.');
|
|
21
|
+
const metadata = await response.json();
|
|
22
|
+
if (metadata.frontendApiUrl !== new URL(path, endpoint).href || metadata.publishableKey !== publishableKey) throw new Error('Invalid authentication destination policy.');
|
|
23
|
+
return metadata;
|
|
24
|
+
}).catch((error) => { navigationPolicy = undefined; throw error; });
|
|
25
|
+
return completionDestination(value, endpoint, await navigationPolicy);
|
|
26
|
+
}
|
|
27
|
+
function resolveEndpoint() {
|
|
28
|
+
if (explicitEndpoint) return explicitEndpoint;
|
|
29
|
+
discovered ??= fetch(`https://api.authlor.com${path}`, { credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(5_000) })
|
|
30
|
+
.then(async (response) => {
|
|
31
|
+
if (!response.ok) throw new Error('Could not discover the Authlor instance.');
|
|
32
|
+
const { frontendApiUrl } = await response.json();
|
|
33
|
+
const endpoint = new URL(frontendApiUrl);
|
|
34
|
+
if (endpoint.protocol !== 'https:' || endpoint.pathname !== path || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) {
|
|
35
|
+
throw new Error('Authlor returned an invalid frontend API URL.');
|
|
36
|
+
}
|
|
37
|
+
return new URL(`${path}/`, endpoint);
|
|
38
|
+
}).catch((error) => { discovered = undefined; throw error; });
|
|
39
|
+
return discovered;
|
|
40
|
+
}
|
|
41
|
+
async function request(operation, body, { signal, credentials = 'omit' } = {}) {
|
|
42
|
+
const endpoint = await resolveEndpoint();
|
|
43
|
+
const response = await fetch(new URL(operation, endpoint), {
|
|
44
|
+
method: 'POST',
|
|
45
|
+
credentials,
|
|
46
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(12000)]) : AbortSignal.timeout(12000),
|
|
47
|
+
redirect: 'error',
|
|
48
|
+
headers: { 'Content-Type': 'application/json' },
|
|
49
|
+
body: JSON.stringify(body),
|
|
50
|
+
});
|
|
51
|
+
const result = await response.json().catch(() => null);
|
|
52
|
+
if (!response.ok || !result) {
|
|
53
|
+
throw Object.assign(new Error(result?.message ?? 'Could not complete authentication.'), { code: result?.code, status: response.status });
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
function navigate(endpoint, operation, fields) {
|
|
58
|
+
const form = document.createElement('form');
|
|
59
|
+
form.method = 'POST';
|
|
60
|
+
form.action = new URL(operation, endpoint).href;
|
|
61
|
+
form.hidden = true;
|
|
62
|
+
for (const [name, value] of Object.entries(fields)) {
|
|
63
|
+
const field = document.createElement('input');
|
|
64
|
+
field.type = 'hidden';
|
|
65
|
+
field.name = name;
|
|
66
|
+
field.value = value;
|
|
67
|
+
form.append(field);
|
|
68
|
+
}
|
|
69
|
+
document.body.append(form);
|
|
70
|
+
form.submit();
|
|
71
|
+
}
|
|
72
|
+
const legacy = {
|
|
73
|
+
signIn: (body) => request('sign-in', body, { credentials: 'same-origin' }),
|
|
74
|
+
signUp: (body) => request('sign-up', body, { credentials: 'same-origin' }),
|
|
75
|
+
continueSession: (authorization) => request('continue-session', { authorization }, { credentials: 'same-origin' }),
|
|
76
|
+
getMfaChallenge: (challenge) => request('mfa-status', { challenge }, { credentials: 'same-origin' }),
|
|
77
|
+
sendMfaSms: (challenge) => request('mfa-send-sms', { challenge }, { credentials: 'same-origin' }),
|
|
78
|
+
verifyMfa: (challenge, code, method) => request('mfa-verify', { challenge, code, method }, { credentials: 'same-origin' }),
|
|
79
|
+
async signInWithSocial(provider, authorization, options) {
|
|
80
|
+
const endpoint = await resolveEndpoint();
|
|
81
|
+
if (location.origin === endpoint.origin) {
|
|
82
|
+
const { url } = await request('social-start', {
|
|
83
|
+
provider, authorization, returnTo: options?.returnTo, legalAccepted: options?.legalAccepted,
|
|
84
|
+
}, { credentials: 'same-origin' });
|
|
85
|
+
location.assign(socialDestination(url, provider));
|
|
86
|
+
} else {
|
|
87
|
+
navigate(endpoint, 'social-start', { provider, ...(authorization && { authorization: JSON.stringify(authorization) }),
|
|
88
|
+
...(options?.legalAccepted === true && { legalAccepted: 'true' }) });
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
async linkSocialAccount(provider) {
|
|
92
|
+
const { url } = await request('social-link', { provider }, { credentials: 'same-origin' });
|
|
93
|
+
location.assign(socialDestination(url, provider));
|
|
94
|
+
},
|
|
95
|
+
verifyEmailCode: (attemptId, code) => request('verify', { attemptId, code }),
|
|
96
|
+
sendSmsCode: (attemptId) => request('send-sms-code', { attemptId }),
|
|
97
|
+
verifySmsCode: (attemptId, code) => request('verify-sms-code', { attemptId, code }),
|
|
98
|
+
checkEmailLink: (attemptId) => request('email-link-status', { attemptId }),
|
|
99
|
+
confirmEmailLink: (token) => request('confirm-email-link', { token }),
|
|
100
|
+
requestPasswordReset: (email) => request('request-password-reset', { email }),
|
|
101
|
+
resetPassword: (token, password) => request('reset-password', { token, password }),
|
|
102
|
+
async signInWithPasskey({ authorization, conditional = false, signal } = {}) {
|
|
103
|
+
if (!globalThis.PublicKeyCredential) throw new Error('Passkeys are unavailable in this browser.');
|
|
104
|
+
const { attemptId, options } = await request('passkey-sign-in-options', { authorization, conditional }, { signal, credentials: 'same-origin' });
|
|
105
|
+
const credential = await navigator.credentials.get({
|
|
106
|
+
publicKey: { ...options, challenge: fromBase64Url(options.challenge), allowCredentials: decodeDescriptors(options.allowCredentials) },
|
|
107
|
+
mediation: conditional ? 'conditional' : 'required',
|
|
108
|
+
signal,
|
|
109
|
+
});
|
|
110
|
+
if (!credential) throw new Error('No passkey was selected.');
|
|
111
|
+
return request('passkey-sign-in-verify', { attemptId, response: serializeCredential(credential) }, { signal });
|
|
112
|
+
},
|
|
113
|
+
async registerPasskey({ ticket, signal } = {}) {
|
|
114
|
+
if (!globalThis.PublicKeyCredential) throw new Error('Passkeys are unavailable in this browser.');
|
|
115
|
+
const { attemptId, options } = await request('passkey-registration-options', { ticket }, { signal, credentials: 'same-origin' });
|
|
116
|
+
const publicKey = { ...options, challenge: fromBase64Url(options.challenge),
|
|
117
|
+
user: { ...options.user, id: fromBase64Url(options.user.id) },
|
|
118
|
+
excludeCredentials: decodeDescriptors(options.excludeCredentials) };
|
|
119
|
+
let credential;
|
|
120
|
+
try {
|
|
121
|
+
credential = await navigator.credentials.create({ publicKey, signal });
|
|
122
|
+
} catch (error) {
|
|
123
|
+
const name = error?.name ?? 'Error';
|
|
124
|
+
let message;
|
|
125
|
+
switch (name) {
|
|
126
|
+
case 'AbortError': message = 'Passkey setup was canceled.'; break;
|
|
127
|
+
case 'TimeoutError': message = 'Passkey setup timed out. Try again.'; break;
|
|
128
|
+
case 'NotAllowedError': message = 'Passkey setup was canceled or timed out.'; break;
|
|
129
|
+
case 'InvalidStateError': message = 'This authenticator already has a passkey for this account.'; break;
|
|
130
|
+
case 'ConstraintError':
|
|
131
|
+
case 'NotSupportedError': message = 'This authenticator can’t create a passkey for this account.'; break;
|
|
132
|
+
case 'SecurityError': message = 'Passkey setup isn’t available at this web address.'; break;
|
|
133
|
+
default: message = 'Could not create a passkey. Try again.';
|
|
134
|
+
}
|
|
135
|
+
throw Object.assign(new Error(message, { cause: error }), { name });
|
|
136
|
+
}
|
|
137
|
+
if (!credential) throw new Error('No passkey was created.');
|
|
138
|
+
return request('passkey-registration-verify', { attemptId, response: serializeCredential(credential) }, { signal, credentials: 'same-origin' });
|
|
139
|
+
},
|
|
140
|
+
continuePasskeySetup: (promptId, dismiss) => request('passkey-prompt-continue', { promptId, dismiss }, { credentials: 'same-origin' }),
|
|
141
|
+
async finish({ ticket }) {
|
|
142
|
+
const endpoint = await resolveEndpoint();
|
|
143
|
+
if (location.origin === endpoint.origin) {
|
|
144
|
+
const { redirect } = await request('finish', { ticket }, { credentials: 'same-origin' });
|
|
145
|
+
location.assign(await completion(redirect));
|
|
146
|
+
} else {
|
|
147
|
+
// A top-level form lets Authlor set its cookie without third-party cookies.
|
|
148
|
+
navigate(endpoint, 'finish', { ticket });
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
return hosted ? legacy : createNativeClient({ publishableKey, resolveEndpoint, legacy, legacyCookie: compatibility.legacyCookie === true });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function fromBase64Url(value) {
|
|
156
|
+
return Uint8Array.from(atob(value.replaceAll('-', '+').replaceAll('_', '/')), (byte) => byte.charCodeAt(0));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function toBase64Url(value) {
|
|
160
|
+
return btoa(String.fromCharCode(...new Uint8Array(value))).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function decodeDescriptors(descriptors) {
|
|
164
|
+
return descriptors?.map((descriptor) => ({ ...descriptor, id: fromBase64Url(descriptor.id) }));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function serializeCredential(credential) {
|
|
168
|
+
if (typeof credential.toJSON === 'function') return credential.toJSON();
|
|
169
|
+
const response = credential.response;
|
|
170
|
+
const data = { clientDataJSON: toBase64Url(response.clientDataJSON) };
|
|
171
|
+
if ('attestationObject' in response) data.attestationObject = toBase64Url(response.attestationObject);
|
|
172
|
+
else {
|
|
173
|
+
data.authenticatorData = toBase64Url(response.authenticatorData);
|
|
174
|
+
data.signature = toBase64Url(response.signature);
|
|
175
|
+
data.userHandle = response.userHandle ? toBase64Url(response.userHandle) : null;
|
|
176
|
+
}
|
|
177
|
+
return { id: credential.id, rawId: toBase64Url(credential.rawId), type: credential.type, response: data,
|
|
178
|
+
clientExtensionResults: credential.getClientExtensionResults() };
|
|
179
|
+
}
|
package/native-client.js
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
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
|
+
await load();
|
|
225
|
+
if (!session) { sessionStorage.setItem(`${flowKey}:account`, '1'); await client.redirectToSignIn(); return; }
|
|
226
|
+
ui ??= await uiModule();
|
|
227
|
+
if (destroyed || !session || signingOut) return;
|
|
228
|
+
if (mounting) { await mounting; if (mountedElement === element && userMount) return; }
|
|
229
|
+
client.closeUserProfile();
|
|
230
|
+
const generation = mountGeneration; mountedElement = element;
|
|
231
|
+
mounting = ui.module.mountUserProfile(element, { metadata, manifest: ui.manifest, accountRequest,
|
|
232
|
+
registerPasskey: () => popup('passkey'), linkSocialAccount: (provider) => popup('social', provider),
|
|
233
|
+
reverify: () => popup('reverify'), signOut: client.signOut, close: client.closeUserProfile,
|
|
234
|
+
addAccount: async () => { sessionStorage.setItem(`${flowKey}:account`, '1'); await client.redirectToSignIn({ addAccount: true }); }, changed: async () => { await refresh(); channel?.postMessage({ type: 'changed' }); },
|
|
235
|
+
ended: () => { sessionGeneration++; update(null); client.closeUserProfile(); } })
|
|
236
|
+
.then((unmount) => { if (generation !== mountGeneration) unmount(); else userMount = unmount; })
|
|
237
|
+
.finally(() => { mounting = undefined; });
|
|
238
|
+
await mounting;
|
|
239
|
+
},
|
|
240
|
+
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); },
|
|
241
|
+
closeUserProfile() { mountGeneration++; userMount?.(); userMount = undefined; mountedElement = undefined; for (const url of imageUrls) URL.revokeObjectURL(url); imageUrls.clear(); },
|
|
242
|
+
unmountUserProfile() { client.closeUserProfile(); },
|
|
243
|
+
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(); },
|
|
244
|
+
};
|
|
245
|
+
return client;
|
|
246
|
+
}
|
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.3.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
|
+
}
|