@authyon/auth 0.1.3

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/dist/index.js ADDED
@@ -0,0 +1,468 @@
1
+ // src/errors.ts
2
+ var AuthyonError = class extends Error {
3
+ constructor(status, body) {
4
+ super(body.detail ?? body.title ?? `Authyon request failed with status ${status}`);
5
+ this.name = "AuthyonError";
6
+ this.status = status;
7
+ this.code = body.code ?? "unknown";
8
+ this.title = body.title ?? "Error";
9
+ this.detail = body.detail;
10
+ }
11
+ is(code) {
12
+ return this.code === code;
13
+ }
14
+ };
15
+ var ErrorCodes = {
16
+ EmailTaken: "user.email_taken",
17
+ PasswordWeak: "user.password_weak",
18
+ PasswordPwned: "user.password_pwned"
19
+ };
20
+
21
+ // src/storage.ts
22
+ var STORAGE_KEY = "authyon.session";
23
+ function memoryStorage() {
24
+ let session = null;
25
+ return {
26
+ get: () => session,
27
+ set: (s) => {
28
+ session = s;
29
+ },
30
+ clear: () => {
31
+ session = null;
32
+ }
33
+ };
34
+ }
35
+ function localStorageAdapter(key = STORAGE_KEY) {
36
+ return {
37
+ get() {
38
+ try {
39
+ const raw = window.localStorage.getItem(key);
40
+ return raw ? JSON.parse(raw) : null;
41
+ } catch {
42
+ return null;
43
+ }
44
+ },
45
+ set(session) {
46
+ try {
47
+ window.localStorage.setItem(key, JSON.stringify(session));
48
+ } catch {
49
+ }
50
+ },
51
+ clear() {
52
+ try {
53
+ window.localStorage.removeItem(key);
54
+ } catch {
55
+ }
56
+ }
57
+ };
58
+ }
59
+ function defaultStorage() {
60
+ if (typeof window !== "undefined" && typeof window.localStorage !== "undefined") {
61
+ return localStorageAdapter();
62
+ }
63
+ return memoryStorage();
64
+ }
65
+
66
+ // src/client.ts
67
+ var DEFAULT_BASE_URL = "https://api.authyon.com";
68
+ var EXPIRY_SKEW_MS = 3e4;
69
+ var AuthyonClient = class {
70
+ constructor(options) {
71
+ this.listeners = /* @__PURE__ */ new Set();
72
+ this.refreshInFlight = null;
73
+ // ── Passwordless (passkey) login ─────────────────────────────────────────
74
+ this.webauthn = {
75
+ /** POST /auth/webauthn/login/start — begins a passkey sign-in. */
76
+ loginStart: (email) => this.request("/auth/webauthn/login/start", { method: "POST", body: { email } }),
77
+ /**
78
+ * POST /auth/webauthn/login/finish — completes the passkey ceremony and
79
+ * stores the session.
80
+ */
81
+ loginFinish: (assertion) => this.request("/auth/webauthn/login/finish", {
82
+ method: "POST",
83
+ body: assertion
84
+ }).then((data) => this.setSession(data, "signed_in"))
85
+ };
86
+ // ── Social sign-in (SSO) ─────────────────────────────────────────────────
87
+ this.sso = {
88
+ /** GET /auth/sso/providers — providers enabled for this environment. */
89
+ providers: () => this.request("/auth/sso/providers"),
90
+ /**
91
+ * Builds the URL to redirect the browser to in order to start a
92
+ * provider's sign-in flow (`GET /auth/sso/{provider}/start`). Navigate
93
+ * to it directly — e.g. `window.location.href = client.sso.startUrl(...)`.
94
+ */
95
+ startUrl: (provider, params) => {
96
+ const query = new URLSearchParams({ redirect_uri: params.redirectUri });
97
+ if (params.state) query.set("state", params.state);
98
+ if (params.mode) query.set("mode", params.mode);
99
+ return `${this.baseUrl}/auth/sso/${encodeURIComponent(provider)}/start?${query}`;
100
+ },
101
+ /**
102
+ * POST /auth/sso/exchange — swaps the one-time code from the provider
103
+ * callback for tokens and stores the session.
104
+ */
105
+ exchange: (code) => this.request("/auth/sso/exchange", { method: "POST", body: { code } }).then(
106
+ (data) => this.setSession(data, "signed_in")
107
+ )
108
+ };
109
+ // ── User ─────────────────────────────────────────────────────────────────
110
+ this.user = {
111
+ /** GET /auth/me — fresh profile of the current user. */
112
+ me: () => this.request("/auth/me", { bearer: true }).then(normalizeUser),
113
+ /** GET /auth/sessions — active refresh-token sessions with device/IP data. */
114
+ sessions: () => this.request("/auth/sessions", { bearer: true }),
115
+ /** GET /auth/me/activities — recent account activity for the current user. */
116
+ activities: (params = {}) => this.request(`/auth/me/activities?${toQuery(params)}`, { bearer: true }),
117
+ /**
118
+ * Revokes a single session by id (e.g. one entry from `sessions()`),
119
+ * signing that device out without affecting the current one.
120
+ *
121
+ * ⚠️ Not directly confirmed against the published API reference at the
122
+ * time this SDK was written — `DELETE /auth/sessions/{id}` follows the
123
+ * REST convention the rest of the documented API uses, but verify it
124
+ * against the Authyon dashboard/API reference before relying on it. If
125
+ * the endpoint differs, override via a raw call to your own backend.
126
+ */
127
+ revokeSession: (sessionId) => this.request(`/auth/sessions/${encodeURIComponent(sessionId)}`, {
128
+ method: "DELETE",
129
+ bearer: true
130
+ }),
131
+ /** POST /auth/password-reset/request — always resolves (no account enumeration). */
132
+ requestPasswordReset: (email) => this.request("/auth/password-reset/request", { method: "POST", body: { email } }),
133
+ /** POST /auth/password-reset/confirm — sets a new password and revokes all refresh tokens. */
134
+ confirmPasswordReset: (token, newPassword) => this.request("/auth/password-reset/confirm", {
135
+ method: "POST",
136
+ body: { token, newPassword }
137
+ })
138
+ };
139
+ // ── Organization ─────────────────────────────────────────────────────────
140
+ this.organization = {
141
+ /** GET /auth/tenants — all organization memberships. */
142
+ list: () => this.request("/auth/tenants", { bearer: true }),
143
+ /**
144
+ * POST /auth/tenants — creates an organization owned by the signed-in
145
+ * user (only available when self-service organization creation is
146
+ * enabled for the environment).
147
+ */
148
+ create: (params = {}) => this.request("/auth/tenants", { method: "POST", bearer: true, body: params }),
149
+ /** GET /auth/tenants/{organizationId} — fetch one of the user's organizations by id. */
150
+ get: (organizationId) => this.request(`/auth/tenants/${encodeURIComponent(organizationId)}`, { bearer: true }),
151
+ /**
152
+ * PATCH /auth/tenants/{organizationId} — renames the organization.
153
+ * Requires the `tenants:manage` custom permission on it.
154
+ */
155
+ rename: (organizationId, name) => this.request(`/auth/tenants/${encodeURIComponent(organizationId)}`, {
156
+ method: "PATCH",
157
+ bearer: true,
158
+ body: { name }
159
+ }),
160
+ /** POST /auth/switch-tenant — issues a fresh token scoped to the new organization. */
161
+ switch: (organizationSlug) => this.request("/auth/switch-tenant", {
162
+ method: "POST",
163
+ bearer: true,
164
+ body: { tenantSlug: organizationSlug }
165
+ }).then((data) => this.setSession(data, "refreshed")),
166
+ /** The organization the current session is scoped to, from the cached session — no network call. */
167
+ current: () => this.getSession()?.user?.activeOrganization ?? null,
168
+ members: {
169
+ /** GET /auth/tenants/{organizationId}/members — list an organization's members. */
170
+ list: (organizationId, params = {}) => this.request(
171
+ `/auth/tenants/${encodeURIComponent(organizationId)}/members?${toQuery(params)}`,
172
+ { bearer: true }
173
+ ),
174
+ /** POST /auth/tenants/{organizationId}/members — invite a member by e-mail. */
175
+ invite: (organizationId, params) => this.request(`/auth/tenants/${encodeURIComponent(organizationId)}/members`, {
176
+ method: "POST",
177
+ bearer: true,
178
+ body: params
179
+ }),
180
+ /** DELETE /auth/tenants/{organizationId}/members/{userId} — remove a member. */
181
+ remove: (organizationId, userId) => this.request(
182
+ `/auth/tenants/${encodeURIComponent(organizationId)}/members/${encodeURIComponent(userId)}`,
183
+ { method: "DELETE", bearer: true }
184
+ )
185
+ },
186
+ roles: {
187
+ /** GET /auth/tenants/{organizationId}/roles — roles available in the organization. */
188
+ list: (organizationId) => this.request(`/auth/tenants/${encodeURIComponent(organizationId)}/roles`, {
189
+ bearer: true
190
+ })
191
+ }
192
+ };
193
+ // ── Two-factor management (authenticated) ────────────────────────────────
194
+ this.twoFactor = {
195
+ /** GET /auth/2fa/status — enrolled methods and recovery code count. */
196
+ status: () => this.request("/auth/2fa/status", { bearer: true }),
197
+ /** POST /auth/2fa/resend-email — resends the code for an in-flight login challenge. */
198
+ resendEmail: (challengeToken) => this.request("/auth/2fa/resend-email", { method: "POST", body: { challengeToken } }),
199
+ /** POST /auth/2fa/authenticator/setup — returns secret, QR SVG and otpauth URI. */
200
+ setupAuthenticator: () => this.request("/auth/2fa/authenticator/setup", { method: "POST", bearer: true }),
201
+ /** POST /auth/2fa/authenticator/confirm — returns 10 single-use recovery codes. */
202
+ confirmAuthenticator: (code) => this.request("/auth/2fa/authenticator/confirm", {
203
+ method: "POST",
204
+ bearer: true,
205
+ body: { code }
206
+ }),
207
+ /**
208
+ * POST /auth/2fa/email/enable — two-step opt-in for email-based OTP.
209
+ * Call without `code` to receive one by e-mail, then call again with
210
+ * that code to confirm enrolment.
211
+ */
212
+ enableEmail: (code) => this.request("/auth/2fa/email/enable", { method: "POST", bearer: true, body: { code } }),
213
+ /** POST /auth/2fa/disable — turns off a specific 2FA method (requires current password). */
214
+ disable: (method, currentPassword) => this.request("/auth/2fa/disable", {
215
+ method: "POST",
216
+ bearer: true,
217
+ body: { method, currentPassword }
218
+ }),
219
+ /**
220
+ * POST /auth/2fa/recovery-codes/regenerate — rotates the 10 single-use
221
+ * recovery codes (requires current password).
222
+ */
223
+ regenerateRecoveryCodes: (currentPassword) => this.request("/auth/2fa/recovery-codes/regenerate", {
224
+ method: "POST",
225
+ bearer: true,
226
+ body: { currentPassword }
227
+ }),
228
+ webauthn: {
229
+ /** POST /auth/2fa/webauthn/register/start — begins passkey enrolment for 2FA. */
230
+ registerStart: () => this.request("/auth/2fa/webauthn/register/start", { method: "POST", bearer: true }),
231
+ /** POST /auth/2fa/webauthn/register/finish — finishes passkey enrolment. */
232
+ registerFinish: (ceremonyToken, attestationJson, nickname) => this.request("/auth/2fa/webauthn/register/finish", {
233
+ method: "POST",
234
+ bearer: true,
235
+ body: { ceremonyToken, attestationJson, nickname }
236
+ }),
237
+ /** GET /auth/2fa/webauthn/credentials — the caller's registered passkeys. */
238
+ credentials: () => this.request("/auth/2fa/webauthn/credentials", { bearer: true }),
239
+ /** PATCH /auth/2fa/webauthn/credentials/{id} — renames a passkey. */
240
+ renameCredential: (id, nickname) => this.request(`/auth/2fa/webauthn/credentials/${encodeURIComponent(id)}`, {
241
+ method: "PATCH",
242
+ bearer: true,
243
+ body: { nickname }
244
+ }),
245
+ /** DELETE /auth/2fa/webauthn/credentials/{id} — removes a passkey (requires current password). */
246
+ removeCredential: (id, currentPassword) => this.request(`/auth/2fa/webauthn/credentials/${encodeURIComponent(id)}`, {
247
+ method: "DELETE",
248
+ bearer: true,
249
+ body: { currentPassword }
250
+ }),
251
+ /**
252
+ * POST /auth/2fa/webauthn/assertion/start — fetches WebAuthn assertion
253
+ * options for an in-flight login challenge (2FA method `"webauthn"`).
254
+ */
255
+ assertionStart: (challengeToken) => this.request("/auth/2fa/webauthn/assertion/start", {
256
+ method: "POST",
257
+ body: { challengeToken }
258
+ })
259
+ }
260
+ };
261
+ if (!options.envKey)
262
+ throw new Error("Authyon: `envKey` is required (pk_live_... / pk_test_...)");
263
+ this.envKey = options.envKey;
264
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
265
+ this.storage = options.storage ?? defaultStorage();
266
+ this.autoRefresh = options.autoRefresh ?? true;
267
+ this.fetchImpl = options.fetch ?? fetch.bind(globalThis);
268
+ }
269
+ // ── Session state ────────────────────────────────────────────────────────
270
+ /** Current persisted session, or null when signed out. */
271
+ getSession() {
272
+ return this.storage.get();
273
+ }
274
+ isAuthenticated() {
275
+ return this.getSession() !== null;
276
+ }
277
+ /**
278
+ * Returns a valid access token, refreshing it transparently when it is
279
+ * expired or about to expire. Returns null when signed out.
280
+ */
281
+ async getAccessToken() {
282
+ const session = this.getSession();
283
+ if (!session) return null;
284
+ if (this.autoRefresh && Date.now() >= session.expiresAt - EXPIRY_SKEW_MS) {
285
+ try {
286
+ return (await this.refresh()).accessToken;
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+ return session.accessToken;
292
+ }
293
+ /** Subscribe to sign-in / refresh / sign-out events. Returns an unsubscribe fn. */
294
+ onAuthStateChange(listener) {
295
+ this.listeners.add(listener);
296
+ return () => this.listeners.delete(listener);
297
+ }
298
+ emit(event) {
299
+ for (const listener of this.listeners) listener(event);
300
+ }
301
+ setSession(raw, event) {
302
+ const session = {
303
+ ...raw,
304
+ user: raw.user ? normalizeUser(raw.user) : void 0,
305
+ expiresAt: Date.now() + raw.expiresIn * 1e3
306
+ };
307
+ this.storage.set(session);
308
+ this.emit(event === "signed_out" ? { type: "signed_out" } : { type: event, session });
309
+ return session;
310
+ }
311
+ clearSession() {
312
+ this.storage.clear();
313
+ this.emit({ type: "signed_out" });
314
+ }
315
+ // ── HTTP core ────────────────────────────────────────────────────────────
316
+ async request(path, options = {}, isRetry = false) {
317
+ const headers = {
318
+ "X-Authyon-Environment": this.envKey,
319
+ ...options.headers
320
+ };
321
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
322
+ if (options.bearer) {
323
+ const token = await this.getAccessToken();
324
+ if (!token)
325
+ throw new AuthyonError(401, { code: "auth.not_authenticated", title: "Not authenticated" });
326
+ headers.Authorization = `Bearer ${token}`;
327
+ }
328
+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {
329
+ method: options.method ?? "GET",
330
+ headers,
331
+ body: options.body !== void 0 ? JSON.stringify(options.body) : void 0
332
+ });
333
+ if (response.status === 401 && options.bearer && this.autoRefresh && !isRetry && this.getSession()) {
334
+ try {
335
+ await this.refresh();
336
+ } catch {
337
+ this.clearSession();
338
+ throw await this.toError(response);
339
+ }
340
+ return this.request(path, options, true);
341
+ }
342
+ if (!response.ok) throw await this.toError(response);
343
+ if (response.status === 204) return void 0;
344
+ return await response.json();
345
+ }
346
+ async toError(response) {
347
+ let body = {};
348
+ try {
349
+ body = await response.json();
350
+ } catch {
351
+ }
352
+ return new AuthyonError(response.status, body);
353
+ }
354
+ // ── Auth flows ───────────────────────────────────────────────────────────
355
+ /** POST /auth/register — creates a new user (rate-limited to 20/hour per IP). */
356
+ async register(params) {
357
+ return this.request("/auth/register", { method: "POST", body: params });
358
+ }
359
+ /**
360
+ * POST /auth/login — authenticates and stores the session, or returns a
361
+ * 2FA challenge to complete via `verifyTwoFactor()`.
362
+ */
363
+ async login(params) {
364
+ const { organizationSlug, ...rest } = params;
365
+ const body = organizationSlug ? { ...rest, tenantSlug: organizationSlug } : rest;
366
+ const data = await this.request("/auth/login", {
367
+ method: "POST",
368
+ body
369
+ });
370
+ if (data.twoFactorRequired) {
371
+ return data;
372
+ }
373
+ const session = this.setSession(data, "signed_in");
374
+ return { twoFactorRequired: false, session };
375
+ }
376
+ /** POST /auth/2fa/verify — redeems a 2FA challenge from `login()` and stores the session. */
377
+ async verifyTwoFactor(params) {
378
+ const data = await this.request("/auth/2fa/verify", { method: "POST", body: params });
379
+ return this.setSession(data, "signed_in");
380
+ }
381
+ /** POST /auth/refresh — rotates the single-use refresh token (single-flight). */
382
+ async refresh() {
383
+ if (this.refreshInFlight) return this.refreshInFlight;
384
+ const current = this.getSession();
385
+ if (!current)
386
+ throw new AuthyonError(401, { code: "auth.not_authenticated", title: "Not authenticated" });
387
+ this.refreshInFlight = this.request("/auth/refresh", {
388
+ method: "POST",
389
+ body: { refreshToken: current.refreshToken }
390
+ }).then(
391
+ (data) => this.setSession({ user: current.user, ...data }, "refreshed")
392
+ ).catch((error) => {
393
+ if (error instanceof AuthyonError && (error.status === 401 || error.status === 403)) {
394
+ this.clearSession();
395
+ }
396
+ throw error;
397
+ }).finally(() => {
398
+ this.refreshInFlight = null;
399
+ });
400
+ return this.refreshInFlight;
401
+ }
402
+ /**
403
+ * POST /auth/logout — revokes the current refresh token and clears local
404
+ * state. Pass `{ everywhere: true }` to revoke every session for the user.
405
+ */
406
+ async logout(options = {}) {
407
+ const session = this.getSession();
408
+ if (session) {
409
+ try {
410
+ if (options.everywhere) {
411
+ await this.request("/auth/logout", { method: "POST", bearer: true });
412
+ } else {
413
+ await this.request("/auth/logout", {
414
+ method: "POST",
415
+ body: { refreshToken: session.refreshToken }
416
+ });
417
+ }
418
+ } catch {
419
+ }
420
+ }
421
+ this.clearSession();
422
+ }
423
+ // ── Token verification ───────────────────────────────────────────────────
424
+ /** POST /auth/introspect — lightweight token introspection. */
425
+ async introspect(token) {
426
+ const accessToken = token ?? await this.getAccessToken();
427
+ return this.request("/auth/introspect", { method: "POST", body: { token: accessToken } });
428
+ }
429
+ /** POST /auth/validate — recommended: cross-checks DB state, returns user + organization. */
430
+ async validate(token) {
431
+ const accessToken = token ?? await this.getAccessToken();
432
+ const raw = await this.request("/auth/validate", {
433
+ method: "POST",
434
+ headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : void 0
435
+ });
436
+ return {
437
+ user: normalizeUser(raw.user),
438
+ organization: raw.organization ?? raw.tenant ?? null
439
+ };
440
+ }
441
+ };
442
+ function normalizeUser(raw) {
443
+ const { tenants, activeTenant, ...rest } = raw;
444
+ return {
445
+ ...rest,
446
+ organizations: raw.organizations ?? tenants,
447
+ activeOrganization: raw.activeOrganization ?? activeTenant ?? null
448
+ };
449
+ }
450
+ function createClient(options) {
451
+ return new AuthyonClient(options);
452
+ }
453
+ function toQuery(params) {
454
+ const query = new URLSearchParams();
455
+ for (const [key, value] of Object.entries(params)) {
456
+ if (value !== void 0) query.set(key, String(value));
457
+ }
458
+ return query.toString();
459
+ }
460
+ export {
461
+ AuthyonClient,
462
+ AuthyonError,
463
+ ErrorCodes,
464
+ createClient,
465
+ defaultStorage,
466
+ localStorageAdapter,
467
+ memoryStorage
468
+ };
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@authyon/auth",
3
+ "version": "0.1.3",
4
+ "description": "Authyon SDK for browsers — auth, sessions, multi-tenant and 2FA for vanilla JS/TS.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "sideEffects": false,
21
+ "scripts": {
22
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
23
+ "typecheck": "tsc --noEmit"
24
+ },
25
+ "keywords": [
26
+ "authyon",
27
+ "auth",
28
+ "authentication",
29
+ "jwt",
30
+ "2fa",
31
+ "multi-tenant"
32
+ ],
33
+ "devDependencies": {
34
+ "tsup": "^8.0.0",
35
+ "typescript": "^5.5.0"
36
+ }
37
+ }