@enformik/auth 0.1.0 → 0.2.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 +3 -1
- package/dist/auth.d.ts +12 -1
- package/dist/auth.js +53 -39
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/types.d.ts +1 -1
- package/package.json +4 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Enformik
|
|
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
|
@@ -42,17 +42,19 @@ if (!auth.isAuthenticated()) {
|
|
|
42
42
|
| `config` | Okunan site yapılandırması (`appUrl`, `apiUrl`, `workspaceId`, `auth`…). |
|
|
43
43
|
| `isAuthenticated()` | Geçerli ya da yenilenebilir oturum var mı. |
|
|
44
44
|
| `login(returnTo?)` | Giriş sayfasına yönlendirir; `returnTo` giriş sonrası dönülecek yoldur. |
|
|
45
|
+
| `register(returnTo?)` | Hesap oluşturma sayfasına yönlendirir (sitede "kendi kendine kayıt" açıksa). Kişi parolasını e-postasına gelen bağlantıyla belirler, sonra `login()` ile girer. |
|
|
45
46
|
| `handleRedirect()` | Girişten dönüşü tamamlar; `{ returnTo }` ya da `null` döner. |
|
|
46
47
|
| `getAccessToken()` | Geçerli access token'ı döner, gerekirse yeniler (eşzamanlı çağrılar tek yenilemede birleşir). |
|
|
47
48
|
| `fetch(path, init?)` | Uygulamanın API'sini oturumla çağırır; 401'de bir kez yenileyip tekrarlar. |
|
|
48
49
|
| `getUser()` | ID token'dan `{ sub, email?, name? }` — yalnızca arayüzde göstermek içindir. |
|
|
50
|
+
| `deleteAccount()` | Kullanıcının kendi hesabını kalıcı siler (KVKK silme hakkı) ve yerel oturumu temizler; kullanıcının oluşturduğu kayıtlar silinmez. Başarısızsa `account_delete_failed` hatası atar. |
|
|
49
51
|
| `logout()` | Oturumu siler ve giriş sayfasından çıkış yaptırır. |
|
|
50
52
|
|
|
51
53
|
Seçenekler (`AuthOptions`): `config` (nesne ya da adres; varsayılan `/_enformik/config.json`), `redirectPath` (varsayılan `/callback`), `postLogoutPath` (varsayılan `/`), `storage` (`'session'` varsayılan, `'local'` ya da kendi `getItem/setItem/removeItem` nesneniz).
|
|
52
54
|
|
|
53
55
|
`redirectPath` sitenizin kayıtlı dönüş adreslerinden biri olmalıdır: `/`, `/callback`, `/auth/callback`, `/login/callback`.
|
|
54
56
|
|
|
55
|
-
Hatalar `EnformikAuthError` olarak atılır; `code` alanı: `not_configured`, `state_mismatch`, `no_pending_login`, `login_rejected`, `token_exchange_failed`, `not_authenticated`.
|
|
57
|
+
Hatalar `EnformikAuthError` olarak atılır; `code` alanı: `not_configured`, `state_mismatch`, `no_pending_login`, `login_rejected`, `token_exchange_failed`, `not_authenticated`, `account_delete_failed`.
|
|
56
58
|
|
|
57
59
|
## Güvenlik notları
|
|
58
60
|
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AuthConfig, type AuthOptions, type AuthUser, type SiteConfig } from './types';
|
|
1
|
+
import { type AuthConfig, type AuthOptions, type AuthUser, type SiteConfig } from './types.js';
|
|
2
2
|
export interface Auth {
|
|
3
3
|
/** Okunan site yapılandırması (`auth` bloğu doludur; yoksa `createAuth` zaten `not_configured` verir). */
|
|
4
4
|
readonly config: SiteConfig & {
|
|
@@ -8,6 +8,11 @@ export interface Auth {
|
|
|
8
8
|
isAuthenticated(): boolean;
|
|
9
9
|
/** Giriş sayfasına yönlendirir. `returnTo`: giriş sonrası dönülecek yol (varsayılan: şu anki yol). */
|
|
10
10
|
login(returnTo?: string): Promise<void>;
|
|
11
|
+
/**
|
|
12
|
+
* Hesap oluşturma sayfasına yönlendirir (sitede "kendi kendine kayıt" açıksa; kapalıysa sayfa bunu bildirir). Kişi parolasını e-postasına
|
|
13
|
+
* gelen bağlantıyla belirler, sonra `login()` ile girer; sayfadaki "Giriş yapın" bağlantısı da aynı `returnTo` ile girişe döner.
|
|
14
|
+
*/
|
|
15
|
+
register(returnTo?: string): Promise<void>;
|
|
11
16
|
/**
|
|
12
17
|
* Dönüş adresinde (`?code=&state=`) girişi tamamlar. Her sayfa yüklemesinde çağırmak güvenlidir: dönüş yoksa `null` döner.
|
|
13
18
|
* Başarıda `{ returnTo }` döner (sayfayı oraya yönlendirmek istemci koduna bırakılır).
|
|
@@ -21,6 +26,12 @@ export interface Auth {
|
|
|
21
26
|
fetch(path: string, init?: RequestInit): Promise<Response>;
|
|
22
27
|
/** ID token'dan kullanıcı bilgisi (yalnızca arayüz için). */
|
|
23
28
|
getUser(): AuthUser | null;
|
|
29
|
+
/**
|
|
30
|
+
* Kullanıcının kendi hesabını kalıcı siler (KVKK silme hakkı) ve yerel oturumu temizler; çağıran sonrasında kullanıcıyı bilgilendirip
|
|
31
|
+
* yönlendirmelidir. Hesap yalnızca web kullanıcısı rolündeyse silinir; başarısızsa `account_delete_failed` hatası atar. Kullanıcının
|
|
32
|
+
* oluşturduğu kayıtlar silinmez (hiçbir hesaba bağlı olmayan bir kimlikle kalır) — saklama politikası site sahibine aittir.
|
|
33
|
+
*/
|
|
34
|
+
deleteAccount(): Promise<void>;
|
|
24
35
|
/** Oturumu siler ve sağlayıcıdan çıkış yaptırır. */
|
|
25
36
|
logout(): Promise<void>;
|
|
26
37
|
}
|
package/dist/auth.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { challengeFor, randomString } from './pkce';
|
|
2
|
-
import { EnformikAuthError } from './types';
|
|
1
|
+
import { challengeFor, randomString } from './pkce.js';
|
|
2
|
+
import { EnformikAuthError } from './types.js';
|
|
3
3
|
const PENDING_KEY = 'enformik.auth.pending';
|
|
4
4
|
const TOKENS_KEY = 'enformik.auth.tokens';
|
|
5
5
|
const LEEWAY_MS = 30_000; // süresi dolmadan 30 sn önce yenile
|
|
@@ -105,25 +105,52 @@ export async function createAuth(opts = {}) {
|
|
|
105
105
|
return t.accessToken;
|
|
106
106
|
return (await refresh())?.accessToken ?? null;
|
|
107
107
|
};
|
|
108
|
+
const apiFetch = async (path, init = {}) => {
|
|
109
|
+
const base = cfg.apiUrl.replace(/\/$/, '');
|
|
110
|
+
const url = /^https?:\/\//i.test(path) ? path : base + (path.startsWith('/') ? path : '/' + path);
|
|
111
|
+
const call = async (token) => {
|
|
112
|
+
const h = new Headers(init.headers);
|
|
113
|
+
h.set('Authorization', 'Bearer ' + token);
|
|
114
|
+
if (cfg.workspaceId && !h.has('X-Tenant-ID'))
|
|
115
|
+
h.set('X-Tenant-ID', cfg.workspaceId);
|
|
116
|
+
return f(url, { ...init, headers: h });
|
|
117
|
+
};
|
|
118
|
+
let token = await getAccessToken();
|
|
119
|
+
if (!token)
|
|
120
|
+
throw new EnformikAuthError('not_authenticated', 'Oturum yok; önce giriş yapın.');
|
|
121
|
+
let res = await call(token);
|
|
122
|
+
if (res.status === 401) {
|
|
123
|
+
// Token sunucuda reddedildi (iptal/erken bitiş): bir kez yenile ve tekrar dene.
|
|
124
|
+
const t = await refresh();
|
|
125
|
+
if (!t)
|
|
126
|
+
throw new EnformikAuthError('not_authenticated', 'Oturum sona erdi; yeniden giriş yapın.');
|
|
127
|
+
token = t.accessToken;
|
|
128
|
+
res = await call(token);
|
|
129
|
+
}
|
|
130
|
+
return res;
|
|
131
|
+
};
|
|
132
|
+
// Giriş / kayıt sayfasına PKCE ile yönlendirir; ikisi de aynı bekleyen girişi (state + verifier) kullanır.
|
|
133
|
+
const startFlow = async (path, returnTo) => {
|
|
134
|
+
const verifier = randomString(32, cry);
|
|
135
|
+
const state = randomString(16, cry);
|
|
136
|
+
write(PENDING_KEY, { state, verifier, returnTo: returnTo ?? loc.href.slice(loc.origin.length) });
|
|
137
|
+
const q = new URLSearchParams({
|
|
138
|
+
client_id: a.clientId,
|
|
139
|
+
redirect_uri: redirectUri(),
|
|
140
|
+
code_challenge: await challengeFor(verifier, cry),
|
|
141
|
+
code_challenge_method: 'S256',
|
|
142
|
+
state,
|
|
143
|
+
});
|
|
144
|
+
loc.assign(a.gatewayUrl.replace(/\/$/, '') + path + '?' + q.toString());
|
|
145
|
+
};
|
|
108
146
|
return {
|
|
109
147
|
config: { ...cfg, auth: a },
|
|
110
148
|
isAuthenticated() {
|
|
111
149
|
const t = read(TOKENS_KEY);
|
|
112
150
|
return !!t && (t.expiresAt > now() || !!t.refreshToken);
|
|
113
151
|
},
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const state = randomString(16, cry);
|
|
117
|
-
write(PENDING_KEY, { state, verifier, returnTo: returnTo ?? loc.href.slice(loc.origin.length) });
|
|
118
|
-
const q = new URLSearchParams({
|
|
119
|
-
client_id: a.clientId,
|
|
120
|
-
redirect_uri: redirectUri(),
|
|
121
|
-
code_challenge: await challengeFor(verifier, cry),
|
|
122
|
-
code_challenge_method: 'S256',
|
|
123
|
-
state,
|
|
124
|
-
});
|
|
125
|
-
loc.assign(a.gatewayUrl.replace(/\/$/, '') + '/login?' + q.toString());
|
|
126
|
-
},
|
|
152
|
+
login: (returnTo) => startFlow('/login', returnTo),
|
|
153
|
+
register: (returnTo) => startFlow('/register', returnTo),
|
|
127
154
|
async handleRedirect() {
|
|
128
155
|
const q = new URLSearchParams(loc.search);
|
|
129
156
|
const err = q.get('error');
|
|
@@ -155,30 +182,7 @@ export async function createAuth(opts = {}) {
|
|
|
155
182
|
return { returnTo: pending.returnTo };
|
|
156
183
|
},
|
|
157
184
|
getAccessToken,
|
|
158
|
-
|
|
159
|
-
const base = cfg.apiUrl.replace(/\/$/, '');
|
|
160
|
-
const url = /^https?:\/\//i.test(path) ? path : base + (path.startsWith('/') ? path : '/' + path);
|
|
161
|
-
const call = async (token) => {
|
|
162
|
-
const h = new Headers(init.headers);
|
|
163
|
-
h.set('Authorization', 'Bearer ' + token);
|
|
164
|
-
if (cfg.workspaceId && !h.has('X-Tenant-ID'))
|
|
165
|
-
h.set('X-Tenant-ID', cfg.workspaceId);
|
|
166
|
-
return f(url, { ...init, headers: h });
|
|
167
|
-
};
|
|
168
|
-
let token = await getAccessToken();
|
|
169
|
-
if (!token)
|
|
170
|
-
throw new EnformikAuthError('not_authenticated', 'Oturum yok; önce giriş yapın.');
|
|
171
|
-
let res = await call(token);
|
|
172
|
-
if (res.status === 401) {
|
|
173
|
-
// Token sunucuda reddedildi (iptal/erken bitiş): bir kez yenile ve tekrar dene.
|
|
174
|
-
const t = await refresh();
|
|
175
|
-
if (!t)
|
|
176
|
-
throw new EnformikAuthError('not_authenticated', 'Oturum sona erdi; yeniden giriş yapın.');
|
|
177
|
-
token = t.accessToken;
|
|
178
|
-
res = await call(token);
|
|
179
|
-
}
|
|
180
|
-
return res;
|
|
181
|
-
},
|
|
185
|
+
fetch: apiFetch,
|
|
182
186
|
getUser() {
|
|
183
187
|
const id = read(TOKENS_KEY)?.idToken;
|
|
184
188
|
const c = id ? decodeJwtPayload(id) : null;
|
|
@@ -186,6 +190,16 @@ export async function createAuth(opts = {}) {
|
|
|
186
190
|
return null;
|
|
187
191
|
return { sub: c.sub, email: typeof c.email === 'string' ? c.email : undefined, name: typeof c.name === 'string' ? c.name : undefined };
|
|
188
192
|
},
|
|
193
|
+
async deleteAccount() {
|
|
194
|
+
const res = await apiFetch('/me/account', { method: 'DELETE' });
|
|
195
|
+
if (!res.ok) {
|
|
196
|
+
const body = (await res.json().catch(() => ({})));
|
|
197
|
+
throw new EnformikAuthError('account_delete_failed', body.message ?? `Hesap silinemedi (HTTP ${res.status}).`);
|
|
198
|
+
}
|
|
199
|
+
// Hesap artık yok: yerel oturumu sil (sağlayıcıda çıkış yaptırmaya gerek yok).
|
|
200
|
+
store.removeItem(TOKENS_KEY);
|
|
201
|
+
store.removeItem(PENDING_KEY);
|
|
202
|
+
},
|
|
189
203
|
async logout() {
|
|
190
204
|
const idToken = read(TOKENS_KEY)?.idToken;
|
|
191
205
|
store.removeItem(TOKENS_KEY);
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createAuth } from './auth';
|
|
2
|
-
export type { Auth } from './auth';
|
|
3
|
-
export { EnformikAuthError } from './types';
|
|
4
|
-
export type { AuthConfig, AuthErrorCode, AuthOptions, AuthUser, KeyValueStorage, SiteConfig } from './types';
|
|
1
|
+
export { createAuth } from './auth.js';
|
|
2
|
+
export type { Auth } from './auth.js';
|
|
3
|
+
export { EnformikAuthError } from './types.js';
|
|
4
|
+
export type { AuthConfig, AuthErrorCode, AuthOptions, AuthUser, KeyValueStorage, SiteConfig } from './types.js';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { createAuth } from './auth';
|
|
2
|
-
export { EnformikAuthError } from './types';
|
|
1
|
+
export { createAuth } from './auth.js';
|
|
2
|
+
export { EnformikAuthError } from './types.js';
|
package/dist/types.d.ts
CHANGED
|
@@ -24,7 +24,7 @@ export interface AuthUser {
|
|
|
24
24
|
email?: string;
|
|
25
25
|
name?: string;
|
|
26
26
|
}
|
|
27
|
-
export type AuthErrorCode = 'not_configured' | 'state_mismatch' | 'no_pending_login' | 'login_rejected' | 'token_exchange_failed' | 'not_authenticated';
|
|
27
|
+
export type AuthErrorCode = 'not_configured' | 'state_mismatch' | 'no_pending_login' | 'login_rejected' | 'token_exchange_failed' | 'not_authenticated' | 'account_delete_failed';
|
|
28
28
|
export declare class EnformikAuthError extends Error {
|
|
29
29
|
readonly code: AuthErrorCode;
|
|
30
30
|
constructor(code: AuthErrorCode, message: string);
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@enformik/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Enformik web sitesi girişi: tarayıcı için OIDC yetkilendirme kodu + PKCE istemcisi (sıfır bağımlılık).",
|
|
5
|
-
"license": "
|
|
5
|
+
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.js",
|
|
8
8
|
"types": "dist/index.d.ts",
|
|
@@ -24,7 +24,8 @@
|
|
|
24
24
|
"build": "tsc -p tsconfig.build.json",
|
|
25
25
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
26
26
|
"test": "vitest run",
|
|
27
|
-
"prepublishOnly": "npm run build && npm test"
|
|
27
|
+
"prepublishOnly": "npm run build && npm test && npm run smoke",
|
|
28
|
+
"smoke": "node --input-type=module -e \"const m = await import('./dist/index.js'); if (typeof m.createAuth !== 'function') throw new Error('createAuth yok')\""
|
|
28
29
|
},
|
|
29
30
|
"devDependencies": {
|
|
30
31
|
"@types/node": "^22.10.0",
|