foxlogin 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/CHANGELOG.md +33 -0
- package/LICENSE +21 -0
- package/README.md +104 -2
- package/dist/client.d.ts +184 -0
- package/dist/client.js +273 -0
- package/dist/errors.d.ts +26 -0
- package/dist/errors.js +57 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/server.d.ts +82 -0
- package/dist/server.js +78 -0
- package/dist/types.d.ts +48 -0
- package/dist/types.js +1 -0
- package/package.json +26 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.4.0 — 2026-12-03
|
|
4
|
+
|
|
5
|
+
- Google sign-in: `googleSignInUrl`, `signInWithGoogle` (keeps a random state),
|
|
6
|
+
`handleRedirect` (checks the state, exchanges `fox_code`, reports `country_required` or
|
|
7
|
+
`fox_error`) and `completeGoogleSignUp`. Works the same with Fox Login's Google app and with
|
|
8
|
+
an application's own Google app.
|
|
9
|
+
- `getAppConfig()` returns the application's sign-in methods and user fields;
|
|
10
|
+
`signUp` takes `profile` with the values of those fields. `User.profile` holds them.
|
|
11
|
+
|
|
12
|
+
## 0.3.1 — 2026-12-02
|
|
13
|
+
|
|
14
|
+
- `FoxLoginAdmin` accepts per-application secret keys (`sk_live_…`) as well as organization API
|
|
15
|
+
keys (`fk_live_…`). Other keys fail with `invalid_api_key`. New `secretKey` option, same as
|
|
16
|
+
`apiKey`.
|
|
17
|
+
|
|
18
|
+
## 0.3.0 — 2026-12-02
|
|
19
|
+
|
|
20
|
+
- **Breaking:** `signIn`, `verifySignUp`, `signInWithCode` and `confirmPasswordReset` now resolve to
|
|
21
|
+
`{ status: "signed_in", user }` or `{ status: "mfa_required", mfaToken }`.
|
|
22
|
+
- `verifyMfa({ mfaToken, code })` completes a sign-in for users with two-factor authentication.
|
|
23
|
+
|
|
24
|
+
## 0.2.0 — 2026-12-02
|
|
25
|
+
|
|
26
|
+
- `sendSignInCode` / `signInWithCode` (passwordless email code) and `startPasswordReset` /
|
|
27
|
+
`confirmPasswordReset`.
|
|
28
|
+
|
|
29
|
+
## 0.1.0 — 2026-12-02
|
|
30
|
+
|
|
31
|
+
- First release: `FoxLogin` client (sign-up with email code, sign-in, rotating sessions,
|
|
32
|
+
`getToken()` with shared refresh, `onChange`), `verifyToken()` (EdDSA only, JWKS cache) and
|
|
33
|
+
`FoxLoginAdmin` (applications, users) in `foxlogin/server`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 METANETSOFT
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,105 @@
|
|
|
1
|
-
#
|
|
1
|
+
# foxlogin
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official JavaScript / TypeScript SDK for [Fox Login](https://foxlogin.app): hosted login where
|
|
4
|
+
each user's data is stored in their own region (EU or Türkiye).
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npm install foxlogin
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Works in browsers and Node.js 20+. ESM, typed.
|
|
11
|
+
|
|
12
|
+
## In the browser or app: sign users in
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { FoxLogin } from "foxlogin";
|
|
16
|
+
|
|
17
|
+
// The region comes from the key: pk_live_tr_… talks to tr.auth.foxlogin.app.
|
|
18
|
+
const fox = new FoxLogin({ publishableKey: "pk_live_tr_…" });
|
|
19
|
+
|
|
20
|
+
await fox.signUp({ email, password, country: "TR", name }); // always { status: "verification_sent" }
|
|
21
|
+
await fox.verifySignUp({ email, code }); // 6-digit code from the email
|
|
22
|
+
|
|
23
|
+
const r = await fox.signIn({ email, password });
|
|
24
|
+
if (r.status === "mfa_required") {
|
|
25
|
+
await fox.verifyMfa({ mfaToken: r.mfaToken, code: totpCodeFromUser });
|
|
26
|
+
}
|
|
27
|
+
fox.onChange((s) => console.log(s.status));
|
|
28
|
+
|
|
29
|
+
// Send this to your backend; it refreshes itself before it expires.
|
|
30
|
+
const token = await fox.getToken();
|
|
31
|
+
await fetch("/api/orders", { headers: { authorization: `Bearer ${token}` } });
|
|
32
|
+
|
|
33
|
+
await fox.signOut();
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Sessions live in memory by default. To keep users signed in across reloads, pass
|
|
37
|
+
`storage: localStorageStorage()` (or your own `SessionStorage`).
|
|
38
|
+
|
|
39
|
+
### Sign in with Google
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
// On your sign-in page (the redirect URI must be listed under Redirect URLs in the dashboard):
|
|
43
|
+
fox.signInWithGoogle({ redirectUri: "https://your.app/auth/callback" });
|
|
44
|
+
|
|
45
|
+
// On https://your.app/auth/callback:
|
|
46
|
+
const r = await fox.handleRedirect(); // null when the URL is not a Fox Login return
|
|
47
|
+
if (r?.status === "country_required") {
|
|
48
|
+
await fox.completeGoogleSignUp({ ticket: r.ticket, country: "TR" }); // ask the user first
|
|
49
|
+
} else if (r?.status === "mfa_required") {
|
|
50
|
+
await fox.verifyMfa({ mfaToken: r.mfaToken, code });
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Whether Google shows Fox Login's app or your own Google app is set in the dashboard; the code
|
|
55
|
+
is the same in both cases.
|
|
56
|
+
|
|
57
|
+
### Sign-up fields
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
const app = await fox.getAppConfig(); // sign-in methods and user fields of the application
|
|
61
|
+
// app.user_fields.fields.username.mode === "required" → show a required username input
|
|
62
|
+
await fox.signUp({ email, password, country: "TR", name, profile: { username: "ayse", plan: "pro" } });
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## On your server: check tokens and manage users
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import { verifyToken, FoxLoginAdmin } from "foxlogin/server";
|
|
69
|
+
|
|
70
|
+
const claims = await verifyToken(bearerToken, { applicationId: "app_…" });
|
|
71
|
+
// claims.sub = user id, claims.rgn = "TR", claims.labels = { store: "…" }
|
|
72
|
+
|
|
73
|
+
// A secret key (sk_live_…) belongs to one application. Copy it from the application's API keys tab.
|
|
74
|
+
const fox = new FoxLoginAdmin({ secretKey: process.env.FOXLOGIN_SECRET_KEY! });
|
|
75
|
+
const u = await fox.users.create("app_…", { email: "mehmet@anka.com.tr", country: "TR" });
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
A secret key works only inside its own application, within the role you gave it (Full access,
|
|
79
|
+
Read and write users, Read only). For work across applications, such as creating a new
|
|
80
|
+
application, use an organization API key (`fk_live_…`, page "API keys" in the dashboard):
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const org = new FoxLoginAdmin({ apiKey: process.env.FOXLOGIN_API_KEY! });
|
|
84
|
+
const app = await org.applications.create({ name: "Anka Market", region: "TR" });
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Keep both keys on your server. Never ship them to a browser or app.
|
|
88
|
+
|
|
89
|
+
`verifyToken` accepts only EdDSA (Ed25519) tokens issued by `https://api.foxlogin.app`, caches
|
|
90
|
+
the public keys for an hour and refetches them when it sees a new key id.
|
|
91
|
+
|
|
92
|
+
## Errors
|
|
93
|
+
|
|
94
|
+
Every failure throws `FoxLoginError` with `status`, `code` (`invalid_credentials`,
|
|
95
|
+
`invalid_code`, `rate_limited`, `email_exists`, `country_not_allowed`, …), `message`,
|
|
96
|
+
`retryable` and `retryAfter` (seconds).
|
|
97
|
+
|
|
98
|
+
## Other languages
|
|
99
|
+
|
|
100
|
+
Python, Go, PHP, Java, .NET, Ruby, Rust, Swift, Kotlin and Dart SDKs follow the same contract:
|
|
101
|
+
see [SDK-SPEC.md](SDK-SPEC.md).
|
|
102
|
+
|
|
103
|
+
## License
|
|
104
|
+
|
|
105
|
+
MIT © METANETSOFT
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { SignInResult, User } from "./types.js";
|
|
2
|
+
/** Where the session (refresh token and user) is kept between page loads. */
|
|
3
|
+
export interface SessionStorage {
|
|
4
|
+
get(key: string): string | null | Promise<string | null>;
|
|
5
|
+
set(key: string, value: string): void | Promise<void>;
|
|
6
|
+
remove(key: string): void | Promise<void>;
|
|
7
|
+
}
|
|
8
|
+
/** Keeps the session in memory only: signed out after a reload. The safe default. */
|
|
9
|
+
export declare function memoryStorage(): SessionStorage;
|
|
10
|
+
/** Keeps the session in `localStorage`. Opt in only if you accept XSS exposure of the refresh token. */
|
|
11
|
+
export declare function localStorageStorage(): SessionStorage;
|
|
12
|
+
export interface FoxLoginOptions {
|
|
13
|
+
/** `pk_live_<region>_…` from the dashboard. The region is read from it. */
|
|
14
|
+
publishableKey: string;
|
|
15
|
+
/** Override the region host (tests, self-hosting). */
|
|
16
|
+
baseUrl?: string;
|
|
17
|
+
storage?: SessionStorage;
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
}
|
|
20
|
+
export type AuthState = {
|
|
21
|
+
status: "signed_in";
|
|
22
|
+
user: User;
|
|
23
|
+
} | {
|
|
24
|
+
status: "signed_out";
|
|
25
|
+
};
|
|
26
|
+
/** `pk_live_eu_…` → `eu`. */
|
|
27
|
+
export declare function regionFromPublishableKey(key: string): string;
|
|
28
|
+
export interface FieldRule {
|
|
29
|
+
mode: "off" | "optional" | "required";
|
|
30
|
+
editable: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface AppConfig {
|
|
33
|
+
id: string;
|
|
34
|
+
name: string;
|
|
35
|
+
region: string;
|
|
36
|
+
sign_in: {
|
|
37
|
+
password: boolean;
|
|
38
|
+
email_code: boolean;
|
|
39
|
+
};
|
|
40
|
+
providers: {
|
|
41
|
+
google: {
|
|
42
|
+
enabled: boolean;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
user_fields: {
|
|
46
|
+
fields: Record<string, FieldRule>;
|
|
47
|
+
custom: {
|
|
48
|
+
key: string;
|
|
49
|
+
label: string;
|
|
50
|
+
type: "text" | "number" | "date" | "boolean" | "select" | "url";
|
|
51
|
+
mode: FieldRule["mode"];
|
|
52
|
+
editable: boolean;
|
|
53
|
+
options?: string[];
|
|
54
|
+
}[];
|
|
55
|
+
};
|
|
56
|
+
country_restriction: {
|
|
57
|
+
mode: "all" | "only_listed";
|
|
58
|
+
countries: string[];
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export declare class FoxLogin {
|
|
62
|
+
readonly baseUrl: string;
|
|
63
|
+
private readonly key;
|
|
64
|
+
private readonly storage;
|
|
65
|
+
private readonly fetchImpl;
|
|
66
|
+
private readonly storageKey;
|
|
67
|
+
private session;
|
|
68
|
+
private loaded;
|
|
69
|
+
private refreshing;
|
|
70
|
+
private listeners;
|
|
71
|
+
constructor(opts: FoxLoginOptions);
|
|
72
|
+
private load;
|
|
73
|
+
private post;
|
|
74
|
+
private save;
|
|
75
|
+
private clear;
|
|
76
|
+
private emit;
|
|
77
|
+
get state(): AuthState;
|
|
78
|
+
/** The signed-in user, or null. Await `ready()` first after a page load. */
|
|
79
|
+
get user(): User | null;
|
|
80
|
+
/** Resolves once the stored session has been read. */
|
|
81
|
+
ready(): Promise<void>;
|
|
82
|
+
/** Called on sign-in, refresh and sign-out. Returns an unsubscribe function. */
|
|
83
|
+
onChange(listener: (s: AuthState) => void): () => void;
|
|
84
|
+
private completeSignIn;
|
|
85
|
+
/**
|
|
86
|
+
* The application's public configuration: name, region, which sign-in methods are on, the
|
|
87
|
+
* user fields the sign-up form should show (off / optional / required) and the providers.
|
|
88
|
+
*/
|
|
89
|
+
getAppConfig(): Promise<AppConfig>;
|
|
90
|
+
/**
|
|
91
|
+
* Always resolves to `{status: "verification_sent"}`, also when the address already has an
|
|
92
|
+
* account. `profile` holds the values of the application's user fields (see `getAppConfig`).
|
|
93
|
+
*/
|
|
94
|
+
signUp(input: {
|
|
95
|
+
email: string;
|
|
96
|
+
password: string;
|
|
97
|
+
country: string;
|
|
98
|
+
name?: string;
|
|
99
|
+
profile?: Record<string, unknown>;
|
|
100
|
+
}): Promise<{
|
|
101
|
+
status: "verification_sent";
|
|
102
|
+
}>;
|
|
103
|
+
verifySignUp(input: {
|
|
104
|
+
email: string;
|
|
105
|
+
code: string;
|
|
106
|
+
}): Promise<SignInResult>;
|
|
107
|
+
signIn(input: {
|
|
108
|
+
email: string;
|
|
109
|
+
password: string;
|
|
110
|
+
}): Promise<SignInResult>;
|
|
111
|
+
/** Second step when a sign-in returned `mfa_required`: a TOTP or recovery code. */
|
|
112
|
+
verifyMfa(input: {
|
|
113
|
+
mfaToken: string;
|
|
114
|
+
code: string;
|
|
115
|
+
}): Promise<User>;
|
|
116
|
+
/** Emails a sign-in code. Always resolves to `{status: "code_sent"}`. */
|
|
117
|
+
sendSignInCode(input: {
|
|
118
|
+
email: string;
|
|
119
|
+
}): Promise<{
|
|
120
|
+
status: "code_sent";
|
|
121
|
+
}>;
|
|
122
|
+
/** Signs in with the emailed code (passwordless). */
|
|
123
|
+
signInWithCode(input: {
|
|
124
|
+
email: string;
|
|
125
|
+
code: string;
|
|
126
|
+
}): Promise<SignInResult>;
|
|
127
|
+
/** Emails a password reset code. Always resolves to `{status: "code_sent"}`. */
|
|
128
|
+
startPasswordReset(input: {
|
|
129
|
+
email: string;
|
|
130
|
+
}): Promise<{
|
|
131
|
+
status: "code_sent";
|
|
132
|
+
}>;
|
|
133
|
+
/** Sets the new password with the emailed code, ends all other sessions and signs in. */
|
|
134
|
+
confirmPasswordReset(input: {
|
|
135
|
+
email: string;
|
|
136
|
+
code: string;
|
|
137
|
+
password: string;
|
|
138
|
+
}): Promise<SignInResult>;
|
|
139
|
+
/**
|
|
140
|
+
* A valid access token, refreshed first when it expires within 60 seconds; null when signed
|
|
141
|
+
* out. Concurrent calls share one refresh (refresh tokens rotate, so two parallel refreshes
|
|
142
|
+
* would end the session).
|
|
143
|
+
*/
|
|
144
|
+
getToken(): Promise<string | null>;
|
|
145
|
+
/** Forces a refresh. Signs out on an invalid refresh token. */
|
|
146
|
+
refresh(): Promise<string | null>;
|
|
147
|
+
private doRefresh;
|
|
148
|
+
/**
|
|
149
|
+
* The URL that starts Google sign-in. `redirectUri` must be one of the application's
|
|
150
|
+
* redirect URLs. Fox Login picks the Google app itself (its own, or the application's own
|
|
151
|
+
* when set up in the dashboard), so this URL is the same in both modes.
|
|
152
|
+
*/
|
|
153
|
+
googleSignInUrl(input: {
|
|
154
|
+
redirectUri: string;
|
|
155
|
+
state?: string;
|
|
156
|
+
country?: string;
|
|
157
|
+
}): string;
|
|
158
|
+
/**
|
|
159
|
+
* Browser: sends the user to Google. A random `state` is kept in sessionStorage and checked
|
|
160
|
+
* by `handleRedirect` when the browser comes back to `redirectUri`.
|
|
161
|
+
*/
|
|
162
|
+
signInWithGoogle(input: {
|
|
163
|
+
redirectUri: string;
|
|
164
|
+
country?: string;
|
|
165
|
+
}): void;
|
|
166
|
+
/**
|
|
167
|
+
* Call on the page Google sign-in returns to (with its URL, by default `location.href`).
|
|
168
|
+
* Resolves to `null` when the URL is not a Fox Login return; otherwise signs in
|
|
169
|
+
* (`signed_in` / `mfa_required`), or asks for the user's country first
|
|
170
|
+
* (`country_required` + `ticket`, then call `completeGoogleSignUp`). Throws `FoxLoginError`
|
|
171
|
+
* with the code from `fox_error` when the sign-in did not finish.
|
|
172
|
+
*/
|
|
173
|
+
handleRedirect(url?: string): Promise<SignInResult | {
|
|
174
|
+
status: "country_required";
|
|
175
|
+
ticket: string;
|
|
176
|
+
} | null>;
|
|
177
|
+
/** New Google user: creates the account in the chosen country and signs in. */
|
|
178
|
+
completeGoogleSignUp(input: {
|
|
179
|
+
ticket: string;
|
|
180
|
+
country: string;
|
|
181
|
+
}): Promise<SignInResult>;
|
|
182
|
+
/** Ends the session on the server and locally. */
|
|
183
|
+
signOut(): Promise<void>;
|
|
184
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { FoxLoginError, request } from "./errors.js";
|
|
2
|
+
/** Keeps the session in memory only: signed out after a reload. The safe default. */
|
|
3
|
+
export function memoryStorage() {
|
|
4
|
+
const m = new Map();
|
|
5
|
+
return { get: (k) => m.get(k) ?? null, set: (k, v) => void m.set(k, v), remove: (k) => void m.delete(k) };
|
|
6
|
+
}
|
|
7
|
+
/** Keeps the session in `localStorage`. Opt in only if you accept XSS exposure of the refresh token. */
|
|
8
|
+
export function localStorageStorage() {
|
|
9
|
+
return {
|
|
10
|
+
get: (k) => globalThis.localStorage?.getItem(k) ?? null,
|
|
11
|
+
set: (k, v) => globalThis.localStorage?.setItem(k, v),
|
|
12
|
+
remove: (k) => globalThis.localStorage?.removeItem(k),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
/** `pk_live_eu_…` → `eu`. */
|
|
16
|
+
export function regionFromPublishableKey(key) {
|
|
17
|
+
const m = /^pk_(?:live|test)_([a-z]{2})_/.exec(key);
|
|
18
|
+
if (!m?.[1]) {
|
|
19
|
+
throw new FoxLoginError({ status: 0, code: "invalid_publishable_key", message: "The publishable key must look like pk_live_<region>_…" });
|
|
20
|
+
}
|
|
21
|
+
return m[1];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* End-user client: sign-up, sign-in, sessions. One instance per application.
|
|
25
|
+
*
|
|
26
|
+
* ```ts
|
|
27
|
+
* const fox = new FoxLogin({ publishableKey: "pk_live_eu_…" });
|
|
28
|
+
* await fox.signUp({ email, password, country: "TR" });
|
|
29
|
+
* await fox.verifySignUp({ email, code });
|
|
30
|
+
* const token = await fox.getToken(); // send to your backend as Bearer
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
const STATE_KEY = "foxlogin:google_state";
|
|
34
|
+
function randomState() {
|
|
35
|
+
const b = new Uint8Array(16);
|
|
36
|
+
globalThis.crypto.getRandomValues(b);
|
|
37
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
38
|
+
}
|
|
39
|
+
export class FoxLogin {
|
|
40
|
+
baseUrl;
|
|
41
|
+
key;
|
|
42
|
+
storage;
|
|
43
|
+
fetchImpl;
|
|
44
|
+
storageKey;
|
|
45
|
+
session = null;
|
|
46
|
+
loaded;
|
|
47
|
+
refreshing = null;
|
|
48
|
+
listeners = new Set();
|
|
49
|
+
constructor(opts) {
|
|
50
|
+
this.key = opts.publishableKey;
|
|
51
|
+
this.baseUrl = (opts.baseUrl ?? `https://${regionFromPublishableKey(opts.publishableKey)}.auth.foxlogin.app`).replace(/\/$/, "");
|
|
52
|
+
this.storage = opts.storage ?? memoryStorage();
|
|
53
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
54
|
+
this.storageKey = `foxlogin:${opts.publishableKey.slice(0, 24)}`;
|
|
55
|
+
this.loaded = this.load();
|
|
56
|
+
}
|
|
57
|
+
async load() {
|
|
58
|
+
const raw = await this.storage.get(this.storageKey);
|
|
59
|
+
if (raw) {
|
|
60
|
+
try {
|
|
61
|
+
this.session = JSON.parse(raw);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
await this.storage.remove(this.storageKey);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
post(path, body) {
|
|
69
|
+
return request(this.fetchImpl, `${this.baseUrl}${path}`, {
|
|
70
|
+
method: "POST",
|
|
71
|
+
headers: { "x-fox-publishable-key": this.key },
|
|
72
|
+
body,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async save(user, t) {
|
|
76
|
+
this.session = { user, refresh_token: t.refresh_token, access_token: t.access_token, expires_at: Date.now() + t.expires_in * 1000 };
|
|
77
|
+
await this.storage.set(this.storageKey, JSON.stringify(this.session));
|
|
78
|
+
this.emit();
|
|
79
|
+
}
|
|
80
|
+
async clear() {
|
|
81
|
+
const had = this.session !== null;
|
|
82
|
+
this.session = null;
|
|
83
|
+
await this.storage.remove(this.storageKey);
|
|
84
|
+
if (had)
|
|
85
|
+
this.emit();
|
|
86
|
+
}
|
|
87
|
+
emit() {
|
|
88
|
+
const s = this.state;
|
|
89
|
+
for (const l of this.listeners)
|
|
90
|
+
l(s);
|
|
91
|
+
}
|
|
92
|
+
get state() {
|
|
93
|
+
return this.session ? { status: "signed_in", user: this.session.user } : { status: "signed_out" };
|
|
94
|
+
}
|
|
95
|
+
/** The signed-in user, or null. Await `ready()` first after a page load. */
|
|
96
|
+
get user() {
|
|
97
|
+
return this.session?.user ?? null;
|
|
98
|
+
}
|
|
99
|
+
/** Resolves once the stored session has been read. */
|
|
100
|
+
ready() {
|
|
101
|
+
return this.loaded;
|
|
102
|
+
}
|
|
103
|
+
/** Called on sign-in, refresh and sign-out. Returns an unsubscribe function. */
|
|
104
|
+
onChange(listener) {
|
|
105
|
+
this.listeners.add(listener);
|
|
106
|
+
return () => this.listeners.delete(listener);
|
|
107
|
+
}
|
|
108
|
+
async completeSignIn(path, body) {
|
|
109
|
+
const r = await this.post(path, body);
|
|
110
|
+
if ("status" in r && r.status === "mfa_required") {
|
|
111
|
+
return { status: "mfa_required", mfaToken: r.mfa_token };
|
|
112
|
+
}
|
|
113
|
+
const s = r;
|
|
114
|
+
await this.save(s.user, s);
|
|
115
|
+
return { status: "signed_in", user: s.user };
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The application's public configuration: name, region, which sign-in methods are on, the
|
|
119
|
+
* user fields the sign-up form should show (off / optional / required) and the providers.
|
|
120
|
+
*/
|
|
121
|
+
getAppConfig() {
|
|
122
|
+
return request(this.fetchImpl, `${this.baseUrl}/v1/client/app`, { method: "GET", headers: { "x-fox-publishable-key": this.key } });
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Always resolves to `{status: "verification_sent"}`, also when the address already has an
|
|
126
|
+
* account. `profile` holds the values of the application's user fields (see `getAppConfig`).
|
|
127
|
+
*/
|
|
128
|
+
signUp(input) {
|
|
129
|
+
return this.post("/v1/client/sign_up", input);
|
|
130
|
+
}
|
|
131
|
+
verifySignUp(input) {
|
|
132
|
+
return this.completeSignIn("/v1/client/sign_up/verify", input);
|
|
133
|
+
}
|
|
134
|
+
signIn(input) {
|
|
135
|
+
return this.completeSignIn("/v1/client/sign_in", input);
|
|
136
|
+
}
|
|
137
|
+
/** Second step when a sign-in returned `mfa_required`: a TOTP or recovery code. */
|
|
138
|
+
async verifyMfa(input) {
|
|
139
|
+
const s = await this.post("/v1/client/sign_in/mfa", { mfa_token: input.mfaToken, code: input.code });
|
|
140
|
+
await this.save(s.user, s);
|
|
141
|
+
return s.user;
|
|
142
|
+
}
|
|
143
|
+
/** Emails a sign-in code. Always resolves to `{status: "code_sent"}`. */
|
|
144
|
+
sendSignInCode(input) {
|
|
145
|
+
return this.post("/v1/client/sign_in/email_code", input);
|
|
146
|
+
}
|
|
147
|
+
/** Signs in with the emailed code (passwordless). */
|
|
148
|
+
signInWithCode(input) {
|
|
149
|
+
return this.completeSignIn("/v1/client/sign_in/email_code/verify", input);
|
|
150
|
+
}
|
|
151
|
+
/** Emails a password reset code. Always resolves to `{status: "code_sent"}`. */
|
|
152
|
+
startPasswordReset(input) {
|
|
153
|
+
return this.post("/v1/client/password_reset", input);
|
|
154
|
+
}
|
|
155
|
+
/** Sets the new password with the emailed code, ends all other sessions and signs in. */
|
|
156
|
+
confirmPasswordReset(input) {
|
|
157
|
+
return this.completeSignIn("/v1/client/password_reset/confirm", input);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* A valid access token, refreshed first when it expires within 60 seconds; null when signed
|
|
161
|
+
* out. Concurrent calls share one refresh (refresh tokens rotate, so two parallel refreshes
|
|
162
|
+
* would end the session).
|
|
163
|
+
*/
|
|
164
|
+
async getToken() {
|
|
165
|
+
await this.loaded;
|
|
166
|
+
const s = this.session;
|
|
167
|
+
if (!s)
|
|
168
|
+
return null;
|
|
169
|
+
if (s.expires_at - Date.now() > 60_000)
|
|
170
|
+
return s.access_token;
|
|
171
|
+
return this.refresh();
|
|
172
|
+
}
|
|
173
|
+
/** Forces a refresh. Signs out on an invalid refresh token. */
|
|
174
|
+
refresh() {
|
|
175
|
+
this.refreshing ??= this.doRefresh().finally(() => {
|
|
176
|
+
this.refreshing = null;
|
|
177
|
+
});
|
|
178
|
+
return this.refreshing;
|
|
179
|
+
}
|
|
180
|
+
async doRefresh() {
|
|
181
|
+
await this.loaded;
|
|
182
|
+
const s = this.session;
|
|
183
|
+
if (!s)
|
|
184
|
+
return null;
|
|
185
|
+
try {
|
|
186
|
+
const t = await this.post("/v1/client/token", { refresh_token: s.refresh_token });
|
|
187
|
+
await this.save(s.user, t);
|
|
188
|
+
return t.access_token;
|
|
189
|
+
}
|
|
190
|
+
catch (e) {
|
|
191
|
+
if (e instanceof FoxLoginError && e.status === 401) {
|
|
192
|
+
await this.clear();
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
throw e;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The URL that starts Google sign-in. `redirectUri` must be one of the application's
|
|
200
|
+
* redirect URLs. Fox Login picks the Google app itself (its own, or the application's own
|
|
201
|
+
* when set up in the dashboard), so this URL is the same in both modes.
|
|
202
|
+
*/
|
|
203
|
+
googleSignInUrl(input) {
|
|
204
|
+
const q = new URLSearchParams({ publishable_key: this.key, redirect_uri: input.redirectUri });
|
|
205
|
+
if (input.state)
|
|
206
|
+
q.set("state", input.state);
|
|
207
|
+
if (input.country)
|
|
208
|
+
q.set("country", input.country);
|
|
209
|
+
return `${this.baseUrl}/v1/oauth/google/start?${q}`;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Browser: sends the user to Google. A random `state` is kept in sessionStorage and checked
|
|
213
|
+
* by `handleRedirect` when the browser comes back to `redirectUri`.
|
|
214
|
+
*/
|
|
215
|
+
signInWithGoogle(input) {
|
|
216
|
+
const state = randomState();
|
|
217
|
+
try {
|
|
218
|
+
globalThis.sessionStorage?.setItem(STATE_KEY, state);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
/* storage blocked: the state check is skipped */
|
|
222
|
+
}
|
|
223
|
+
globalThis.location.assign(this.googleSignInUrl({ ...input, state }));
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Call on the page Google sign-in returns to (with its URL, by default `location.href`).
|
|
227
|
+
* Resolves to `null` when the URL is not a Fox Login return; otherwise signs in
|
|
228
|
+
* (`signed_in` / `mfa_required`), or asks for the user's country first
|
|
229
|
+
* (`country_required` + `ticket`, then call `completeGoogleSignUp`). Throws `FoxLoginError`
|
|
230
|
+
* with the code from `fox_error` when the sign-in did not finish.
|
|
231
|
+
*/
|
|
232
|
+
async handleRedirect(url = globalThis.location?.href ?? "") {
|
|
233
|
+
const u = new URL(url);
|
|
234
|
+
const q = u.searchParams;
|
|
235
|
+
if (!q.has("fox_code") && !q.has("fox_status") && !q.has("fox_error"))
|
|
236
|
+
return null;
|
|
237
|
+
let expected = null;
|
|
238
|
+
try {
|
|
239
|
+
expected = globalThis.sessionStorage?.getItem(STATE_KEY) ?? null;
|
|
240
|
+
globalThis.sessionStorage?.removeItem(STATE_KEY);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
expected = null;
|
|
244
|
+
}
|
|
245
|
+
if (expected && q.get("state") !== expected) {
|
|
246
|
+
throw new FoxLoginError({ status: 400, code: "invalid_state", message: "The sign-in did not start in this browser. Start again.", retryable: false });
|
|
247
|
+
}
|
|
248
|
+
const err = q.get("fox_error");
|
|
249
|
+
if (err)
|
|
250
|
+
throw new FoxLoginError({ status: 400, code: err, message: `Google sign-in did not finish (${err}).`, retryable: err !== "access_denied" });
|
|
251
|
+
if (q.get("fox_status") === "country_required")
|
|
252
|
+
return { status: "country_required", ticket: q.get("fox_ticket") ?? "" };
|
|
253
|
+
return this.completeSignIn("/v1/client/oauth/token", { code: q.get("fox_code") });
|
|
254
|
+
}
|
|
255
|
+
/** New Google user: creates the account in the chosen country and signs in. */
|
|
256
|
+
completeGoogleSignUp(input) {
|
|
257
|
+
return this.completeSignIn("/v1/client/oauth/complete", input);
|
|
258
|
+
}
|
|
259
|
+
/** Ends the session on the server and locally. */
|
|
260
|
+
async signOut() {
|
|
261
|
+
await this.loaded;
|
|
262
|
+
const s = this.session;
|
|
263
|
+
await this.clear();
|
|
264
|
+
if (s) {
|
|
265
|
+
try {
|
|
266
|
+
await this.post("/v1/client/sign_out", { refresh_token: s.refresh_token });
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// Already signed out locally; the server session expires on its own.
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Every failed call throws this. `code` is stable and meant for programs; `message` is for people. */
|
|
2
|
+
export declare class FoxLoginError extends Error {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly code: string;
|
|
5
|
+
readonly retryable: boolean;
|
|
6
|
+
readonly retryAfter: number | null;
|
|
7
|
+
readonly region: string | null;
|
|
8
|
+
readonly details: Record<string, unknown>;
|
|
9
|
+
constructor(init: {
|
|
10
|
+
status: number;
|
|
11
|
+
code: string;
|
|
12
|
+
message: string;
|
|
13
|
+
retryable?: boolean;
|
|
14
|
+
retryAfter?: number | null;
|
|
15
|
+
region?: string | null;
|
|
16
|
+
details?: Record<string, unknown>;
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
type Fetch = typeof fetch;
|
|
20
|
+
/** JSON request helper shared by the client and the management API. */
|
|
21
|
+
export declare function request<T>(fetchImpl: Fetch, url: string, init: {
|
|
22
|
+
method: string;
|
|
23
|
+
headers: Record<string, string>;
|
|
24
|
+
body?: unknown;
|
|
25
|
+
}): Promise<T>;
|
|
26
|
+
export {};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Every failed call throws this. `code` is stable and meant for programs; `message` is for people. */
|
|
2
|
+
export class FoxLoginError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
code;
|
|
5
|
+
retryable;
|
|
6
|
+
retryAfter;
|
|
7
|
+
region;
|
|
8
|
+
details;
|
|
9
|
+
constructor(init) {
|
|
10
|
+
super(init.message);
|
|
11
|
+
this.name = "FoxLoginError";
|
|
12
|
+
this.status = init.status;
|
|
13
|
+
this.code = init.code;
|
|
14
|
+
this.retryable = init.retryable ?? false;
|
|
15
|
+
this.retryAfter = init.retryAfter ?? null;
|
|
16
|
+
this.region = init.region ?? null;
|
|
17
|
+
this.details = init.details ?? {};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** JSON request helper shared by the client and the management API. */
|
|
21
|
+
export async function request(fetchImpl, url, init) {
|
|
22
|
+
let res;
|
|
23
|
+
try {
|
|
24
|
+
res = await fetchImpl(url, {
|
|
25
|
+
method: init.method,
|
|
26
|
+
headers: { accept: "application/json", ...(init.body !== undefined ? { "content-type": "application/json" } : {}), ...init.headers },
|
|
27
|
+
body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
catch (cause) {
|
|
31
|
+
throw new FoxLoginError({ status: 0, code: "network_error", message: `Could not reach Fox Login: ${String(cause)}`, retryable: true });
|
|
32
|
+
}
|
|
33
|
+
if (res.status === 204)
|
|
34
|
+
return undefined;
|
|
35
|
+
const text = await res.text();
|
|
36
|
+
let body = null;
|
|
37
|
+
try {
|
|
38
|
+
body = text ? JSON.parse(text) : null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
body = null;
|
|
42
|
+
}
|
|
43
|
+
if (!res.ok) {
|
|
44
|
+
const e = body?.error ?? {};
|
|
45
|
+
const retryAfterHeader = res.headers.get("retry-after");
|
|
46
|
+
throw new FoxLoginError({
|
|
47
|
+
status: res.status,
|
|
48
|
+
code: typeof e.code === "string" ? e.code : "http_error",
|
|
49
|
+
message: typeof e.message === "string" ? e.message : `HTTP ${res.status}`,
|
|
50
|
+
retryable: Boolean(e.retryable) || res.status === 429 || res.status >= 500,
|
|
51
|
+
retryAfter: retryAfterHeader ? Number(retryAfterHeader) : null,
|
|
52
|
+
region: typeof e.region === "string" ? e.region : null,
|
|
53
|
+
details: e.details && typeof e.details === "object" ? e.details : {},
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return body;
|
|
57
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { FoxLogin, memoryStorage, localStorageStorage, regionFromPublishableKey } from "./client.js";
|
|
2
|
+
export type { FoxLoginOptions, SessionStorage, AuthState, AppConfig, FieldRule } from "./client.js";
|
|
3
|
+
export { FoxLoginError } from "./errors.js";
|
|
4
|
+
export type { User, Session, TokenPair, SessionClaims, Region, SignInResult, MfaRequired } from "./types.js";
|
package/dist/index.js
ADDED
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { type JWTVerifyGetKey } from "jose";
|
|
2
|
+
import type { SessionClaims, User } from "./types.js";
|
|
3
|
+
export { FoxLoginError } from "./errors.js";
|
|
4
|
+
export type { SessionClaims, User, Region } from "./types.js";
|
|
5
|
+
export declare const ISSUER = "https://api.foxlogin.app";
|
|
6
|
+
export interface VerifyOptions {
|
|
7
|
+
/** Default https://api.foxlogin.app/.well-known/jwks.json */
|
|
8
|
+
jwksUrl?: string;
|
|
9
|
+
/** Reject tokens of other applications. */
|
|
10
|
+
applicationId?: string;
|
|
11
|
+
/** Inject a key set (tests, offline). */
|
|
12
|
+
keys?: JWTVerifyGetKey;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Verifies a session token on your backend without calling Fox Login for every request.
|
|
16
|
+
* EdDSA (Ed25519) only; checks issuer, expiry (60 s leeway) and optionally the application.
|
|
17
|
+
*/
|
|
18
|
+
export declare function verifyToken(token: string, opts?: VerifyOptions): Promise<SessionClaims>;
|
|
19
|
+
export interface Application {
|
|
20
|
+
id: string;
|
|
21
|
+
name: string;
|
|
22
|
+
region: string;
|
|
23
|
+
multi_region: boolean;
|
|
24
|
+
block: string;
|
|
25
|
+
sector: string | null;
|
|
26
|
+
user_countries: string[];
|
|
27
|
+
country_restriction: {
|
|
28
|
+
mode: "all" | "only_listed";
|
|
29
|
+
countries: string[];
|
|
30
|
+
};
|
|
31
|
+
publishable_key: string;
|
|
32
|
+
created_at: string;
|
|
33
|
+
}
|
|
34
|
+
export interface AdminOptions {
|
|
35
|
+
/**
|
|
36
|
+
* A secret key (`sk_live_…`) for one application, or an organization API key (`fk_live_…`)
|
|
37
|
+
* for all applications. Creating applications needs an organization key. Keep it on the server.
|
|
38
|
+
*/
|
|
39
|
+
apiKey?: string;
|
|
40
|
+
/** Same as `apiKey`; reads well with `process.env.FOXLOGIN_SECRET_KEY`. Wins when both are set. */
|
|
41
|
+
secretKey?: string;
|
|
42
|
+
baseUrl?: string;
|
|
43
|
+
fetch?: typeof fetch;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Management API client for your backend. Pass a secret key (`sk_live_…`) for one application,
|
|
47
|
+
* or an organization API key (`fk_live_…`) for all applications.
|
|
48
|
+
*/
|
|
49
|
+
export declare class FoxLoginAdmin {
|
|
50
|
+
private readonly base;
|
|
51
|
+
private readonly key;
|
|
52
|
+
private readonly fetchImpl;
|
|
53
|
+
constructor(opts: AdminOptions);
|
|
54
|
+
private call;
|
|
55
|
+
readonly applications: {
|
|
56
|
+
create: (input: {
|
|
57
|
+
name: string;
|
|
58
|
+
region: "EU" | "TR";
|
|
59
|
+
sector?: string;
|
|
60
|
+
userCountries?: string[];
|
|
61
|
+
countryRestriction?: {
|
|
62
|
+
mode: "all" | "only_listed";
|
|
63
|
+
countries: string[];
|
|
64
|
+
};
|
|
65
|
+
}) => Promise<Application>;
|
|
66
|
+
list: () => Promise<{
|
|
67
|
+
data: Application[];
|
|
68
|
+
}>;
|
|
69
|
+
get: (appId: string) => Promise<Application>;
|
|
70
|
+
};
|
|
71
|
+
readonly users: {
|
|
72
|
+
create: (appId: string, input: {
|
|
73
|
+
email: string;
|
|
74
|
+
country: string;
|
|
75
|
+
name?: string;
|
|
76
|
+
labels?: Record<string, string>;
|
|
77
|
+
password?: string;
|
|
78
|
+
emailVerified?: boolean;
|
|
79
|
+
}) => Promise<User>;
|
|
80
|
+
get: (appId: string, userId: string) => Promise<User>;
|
|
81
|
+
};
|
|
82
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
2
|
+
import { FoxLoginError, request } from "./errors.js";
|
|
3
|
+
export { FoxLoginError } from "./errors.js";
|
|
4
|
+
export const ISSUER = "https://api.foxlogin.app";
|
|
5
|
+
const DEFAULT_JWKS = `${ISSUER}/.well-known/jwks.json`;
|
|
6
|
+
const jwksCache = new Map();
|
|
7
|
+
/**
|
|
8
|
+
* Verifies a session token on your backend without calling Fox Login for every request.
|
|
9
|
+
* EdDSA (Ed25519) only; checks issuer, expiry (60 s leeway) and optionally the application.
|
|
10
|
+
*/
|
|
11
|
+
export async function verifyToken(token, opts = {}) {
|
|
12
|
+
const url = opts.jwksUrl ?? DEFAULT_JWKS;
|
|
13
|
+
let keys = opts.keys ?? jwksCache.get(url);
|
|
14
|
+
if (!keys) {
|
|
15
|
+
keys = createRemoteJWKSet(new URL(url), { cacheMaxAge: 60 * 60 * 1000, cooldownDuration: 30_000 });
|
|
16
|
+
jwksCache.set(url, keys);
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
const { payload } = await jwtVerify(token, keys, { algorithms: ["EdDSA", "Ed25519"], issuer: ISSUER, clockTolerance: 60 });
|
|
20
|
+
const claims = payload;
|
|
21
|
+
if (opts.applicationId && claims.app !== opts.applicationId) {
|
|
22
|
+
throw new FoxLoginError({ status: 401, code: "wrong_application", message: "The token belongs to another application." });
|
|
23
|
+
}
|
|
24
|
+
return claims;
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
if (e instanceof FoxLoginError)
|
|
28
|
+
throw e;
|
|
29
|
+
throw new FoxLoginError({ status: 401, code: "invalid_token", message: e instanceof Error ? e.message : "Invalid token." });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Management API client for your backend. Pass a secret key (`sk_live_…`) for one application,
|
|
34
|
+
* or an organization API key (`fk_live_…`) for all applications.
|
|
35
|
+
*/
|
|
36
|
+
export class FoxLoginAdmin {
|
|
37
|
+
base;
|
|
38
|
+
key;
|
|
39
|
+
fetchImpl;
|
|
40
|
+
constructor(opts) {
|
|
41
|
+
const key = opts.secretKey ?? opts.apiKey;
|
|
42
|
+
if (!key || !(key.startsWith("sk_") || key.startsWith("fk_"))) {
|
|
43
|
+
throw new FoxLoginError({
|
|
44
|
+
status: 0,
|
|
45
|
+
code: "invalid_api_key",
|
|
46
|
+
message: "Use a secret key (sk_live_…) or an organization API key (fk_live_…).",
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
this.key = key;
|
|
50
|
+
this.base = (opts.baseUrl ?? `${ISSUER}`).replace(/\/$/, "");
|
|
51
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
52
|
+
}
|
|
53
|
+
call(method, path, body) {
|
|
54
|
+
return request(this.fetchImpl, `${this.base}/v1${path}`, { method, headers: { authorization: `Bearer ${this.key}` }, body });
|
|
55
|
+
}
|
|
56
|
+
applications = {
|
|
57
|
+
create: (input) => this.call("POST", "/applications", {
|
|
58
|
+
name: input.name,
|
|
59
|
+
region: input.region,
|
|
60
|
+
sector: input.sector,
|
|
61
|
+
user_countries: input.userCountries ?? [],
|
|
62
|
+
country_restriction: input.countryRestriction,
|
|
63
|
+
}),
|
|
64
|
+
list: () => this.call("GET", "/applications"),
|
|
65
|
+
get: (appId) => this.call("GET", `/applications/${encodeURIComponent(appId)}`),
|
|
66
|
+
};
|
|
67
|
+
users = {
|
|
68
|
+
create: (appId, input) => this.call("POST", `/applications/${encodeURIComponent(appId)}/users`, {
|
|
69
|
+
email: input.email,
|
|
70
|
+
country: input.country,
|
|
71
|
+
name: input.name,
|
|
72
|
+
labels: input.labels ?? {},
|
|
73
|
+
password: input.password,
|
|
74
|
+
email_verified: input.emailVerified ?? false,
|
|
75
|
+
}),
|
|
76
|
+
get: (appId, userId) => this.call("GET", `/applications/${encodeURIComponent(appId)}/users/${encodeURIComponent(userId)}`),
|
|
77
|
+
};
|
|
78
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
export type Region = "EU" | "TR" | (string & {});
|
|
2
|
+
export interface User {
|
|
3
|
+
id: string;
|
|
4
|
+
region: Region;
|
|
5
|
+
email: string;
|
|
6
|
+
email_verified: boolean;
|
|
7
|
+
name: string | null;
|
|
8
|
+
country: string;
|
|
9
|
+
status: "active" | "locked";
|
|
10
|
+
labels: Record<string, string>;
|
|
11
|
+
/** Values of the application's user fields (username, phone, custom fields…). */
|
|
12
|
+
profile?: Record<string, unknown>;
|
|
13
|
+
created_at: string;
|
|
14
|
+
last_sign_in_at: string | null;
|
|
15
|
+
}
|
|
16
|
+
export interface TokenPair {
|
|
17
|
+
session_id: string;
|
|
18
|
+
access_token: string;
|
|
19
|
+
refresh_token: string;
|
|
20
|
+
token_type: "Bearer";
|
|
21
|
+
expires_in: number;
|
|
22
|
+
}
|
|
23
|
+
export interface Session extends TokenPair {
|
|
24
|
+
user: User;
|
|
25
|
+
}
|
|
26
|
+
export interface SessionClaims {
|
|
27
|
+
iss: string;
|
|
28
|
+
sub: string;
|
|
29
|
+
rgn: Region;
|
|
30
|
+
app: string;
|
|
31
|
+
sid: string;
|
|
32
|
+
labels: Record<string, string>;
|
|
33
|
+
iat: number;
|
|
34
|
+
exp: number;
|
|
35
|
+
}
|
|
36
|
+
/** Returned instead of a session when the user has two-factor authentication on. */
|
|
37
|
+
export interface MfaRequired {
|
|
38
|
+
status: "mfa_required";
|
|
39
|
+
mfa_token: string;
|
|
40
|
+
}
|
|
41
|
+
/** Result of a sign-in step: the signed-in user, or a second factor to ask for. */
|
|
42
|
+
export type SignInResult = {
|
|
43
|
+
status: "signed_in";
|
|
44
|
+
user: User;
|
|
45
|
+
} | {
|
|
46
|
+
status: "mfa_required";
|
|
47
|
+
mfaToken: string;
|
|
48
|
+
};
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foxlogin",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Fox Login SDK for browsers and Node.js: sign-up, sign-in, sessions, token verification and the Management API. User data stays in its own region (EU, TR).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "METANETSOFT",
|
|
7
|
+
"homepage": "https://foxlogin.app",
|
|
8
|
+
"repository": { "type": "git", "url": "git+https://github.com/METANETSOFT/foxloginjsdk.git" },
|
|
9
|
+
"bugs": { "url": "https://github.com/METANETSOFT/foxloginjsdk/issues" },
|
|
10
|
+
"keywords": ["auth", "authentication", "login", "jwt", "data-residency", "kvkk", "gdpr", "foxlogin"],
|
|
11
|
+
"type": "module",
|
|
12
|
+
"engines": { "node": ">=20" },
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"files": ["dist", "README.md", "LICENSE", "CHANGELOG.md"],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
|
|
17
|
+
"./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" }
|
|
18
|
+
},
|
|
19
|
+
"main": "./dist/index.js",
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "tsc -p tsconfig.json",
|
|
23
|
+
"test": "npm run build && node --test test/sdk.test.js",
|
|
24
|
+
"prepublishOnly": "npm test"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": { "jose": "^6.1.0" },
|
|
27
|
+
"devDependencies": { "typescript": "^5.9.0", "@types/node": "^22.0.0" }
|
|
28
|
+
}
|