@iglo.tech/iglo.base 0.0.0-stage → 1.0.1-rc.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +18 -0
  3. package/README.md +778 -2
  4. package/dist/iglo-base.es.mjs +4 -0
  5. package/dist/iglo-base.es.mjs.map +34 -0
  6. package/dist/ssr-astro.es.mjs +4 -0
  7. package/dist/ssr-astro.es.mjs.map +12 -0
  8. package/dist/ssr-browser-client.es.mjs +4 -0
  9. package/dist/ssr-browser-client.es.mjs.map +13 -0
  10. package/dist/ssr-browser.es.mjs +4 -0
  11. package/dist/ssr-browser.es.mjs.map +10 -0
  12. package/dist/ssr-next.es.mjs +4 -0
  13. package/dist/ssr-next.es.mjs.map +12 -0
  14. package/dist/ssr-nuxt.es.mjs +4 -0
  15. package/dist/ssr-nuxt.es.mjs.map +12 -0
  16. package/dist/ssr-react-router.es.mjs +4 -0
  17. package/dist/ssr-react-router.es.mjs.map +12 -0
  18. package/dist/ssr-sveltekit.es.mjs +4 -0
  19. package/dist/ssr-sveltekit.es.mjs.map +12 -0
  20. package/dist/ssr.es.mjs +4 -0
  21. package/dist/ssr.es.mjs.map +22 -0
  22. package/dist/types/src/Client.d.ts +233 -0
  23. package/dist/types/src/ClientResponseError.d.ts +22 -0
  24. package/dist/types/src/index.d.ts +18 -0
  25. package/dist/types/src/services/BackupService.d.ts +59 -0
  26. package/dist/types/src/services/BaseService.d.ts +8 -0
  27. package/dist/types/src/services/BatchService.d.ts +56 -0
  28. package/dist/types/src/services/CollectionService.d.ts +47 -0
  29. package/dist/types/src/services/CronService.d.ts +20 -0
  30. package/dist/types/src/services/CrudService.d.ts +85 -0
  31. package/dist/types/src/services/FileService.d.ts +19 -0
  32. package/dist/types/src/services/HealthService.d.ts +16 -0
  33. package/dist/types/src/services/LogService.d.ts +35 -0
  34. package/dist/types/src/services/RealtimeService.d.ts +124 -0
  35. package/dist/types/src/services/RecordService.d.ts +374 -0
  36. package/dist/types/src/services/SQLService.d.ts +21 -0
  37. package/dist/types/src/services/SettingsService.d.ts +46 -0
  38. package/dist/types/src/ssr/adapter.d.ts +133 -0
  39. package/dist/types/src/ssr/astro.d.ts +27 -0
  40. package/dist/types/src/ssr/browser-client.d.ts +100 -0
  41. package/dist/types/src/ssr/browser-token.d.ts +29 -0
  42. package/dist/types/src/ssr/browser.d.ts +1 -0
  43. package/dist/types/src/ssr/cache.d.ts +9 -0
  44. package/dist/types/src/ssr/cookies.d.ts +68 -0
  45. package/dist/types/src/ssr/csrf.d.ts +38 -0
  46. package/dist/types/src/ssr/index.d.ts +12 -0
  47. package/dist/types/src/ssr/next.d.ts +53 -0
  48. package/dist/types/src/ssr/no-store-fetch.d.ts +7 -0
  49. package/dist/types/src/ssr/nuxt.d.ts +41 -0
  50. package/dist/types/src/ssr/oauth2.d.ts +56 -0
  51. package/dist/types/src/ssr/popup.d.ts +14 -0
  52. package/dist/types/src/ssr/react-router.d.ts +53 -0
  53. package/dist/types/src/ssr/renew.d.ts +25 -0
  54. package/dist/types/src/ssr/server-client.d.ts +83 -0
  55. package/dist/types/src/ssr/superuser-client.d.ts +24 -0
  56. package/dist/types/src/ssr/sveltekit.d.ts +44 -0
  57. package/dist/types/src/ssr/types.d.ts +118 -0
  58. package/dist/types/src/stores/AsyncAuthStore.d.ts +52 -0
  59. package/dist/types/src/stores/BaseAuthStore.d.ts +104 -0
  60. package/dist/types/src/stores/LocalAuthStore.d.ts +48 -0
  61. package/dist/types/src/tools/cookie.d.ts +31 -0
  62. package/dist/types/src/tools/dtos.d.ts +122 -0
  63. package/dist/types/src/tools/formdata.d.ts +30 -0
  64. package/dist/types/src/tools/jwt.d.ts +14 -0
  65. package/dist/types/src/tools/legacy.d.ts +2 -0
  66. package/dist/types/src/tools/loose.d.ts +5 -0
  67. package/dist/types/src/tools/options.d.ts +91 -0
  68. package/dist/types/src/tools/refresh.d.ts +3 -0
  69. package/package.json +73 -4
@@ -0,0 +1,53 @@
1
+ import { type AdapterOptions, type RequestSession } from "./adapter.js";
2
+ export interface ReactRouterAuth {
3
+ /**
4
+ * For a loader, action or resource route. Returns `{ response }` when the CSRF guard or an
5
+ * adapter route answers the request: return that response as it is. Otherwise returns `{ session,
6
+ * headers }`: the resumed session, and a `headers()` function. Call `headers()` when the route
7
+ * builds its response, as the last step before it returns: it reads the cookies written up to
8
+ * that call, so a sign-in or sign-out made later in the handler is not in an earlier call's
9
+ * result. The route returns its data with it, for example `data(value, { headers: headers() })`
10
+ * or `redirect(url, { headers: headers() })`. The route module must also export
11
+ * `sessionHeaders` as `headers` (see `sessionHeaders`), or React Router drops the no-cache
12
+ * headers. So does every route with an `ErrorBoundary` (at least the root route): when a session
13
+ * route throws the response, React Router takes the headers from the boundary route.
14
+ */
15
+ session(request: Request): Promise<{
16
+ session: RequestSession;
17
+ headers(): Headers;
18
+ } | {
19
+ response: Response;
20
+ }>;
21
+ }
22
+ /** The arguments React Router passes to a route's `headers` function. */
23
+ export interface RouteHeadersArgs {
24
+ loaderHeaders: Headers;
25
+ actionHeaders: Headers;
26
+ parentHeaders: Headers;
27
+ errorHeaders?: Headers;
28
+ }
29
+ /**
30
+ * The `headers` function of a route that uses the session, and of every route with an
31
+ * `ErrorBoundary` (at least the root route). The route re-exports it:
32
+ * `export { sessionHeaders as headers } from "@iglo.tech/iglo.base/ssr/react-router";`
33
+ *
34
+ * React Router builds the headers of a page and of a `.data` response from the route's `headers`
35
+ * export. A route without one copies only the Set-Cookie lines of its loader's and action's
36
+ * headers, so the no-cache headers that `headers()` returns would be lost. This function starts
37
+ * from the parent headers, as React Router does by default, and adds the no-cache headers when the
38
+ * loader, the action or the error response carries them. Nothing is kept between calls.
39
+ *
40
+ * The error headers are the thrown response's headers, passed to the boundary route only. When a
41
+ * session route throws `data(…, { headers: headers() })`, the boundary route (the root, in the
42
+ * default template) renders it and gets those headers as `errorHeaders`, not the session route.
43
+ * A boundary route without this export drops them. On an anonymous request the error headers carry
44
+ * no no-store, so the page stays cacheable.
45
+ */
46
+ export declare function sessionHeaders({ loaderHeaders, actionHeaders, parentHeaders, errorHeaders, }: RouteHeadersArgs): Headers;
47
+ /**
48
+ * The React Router adapter. The options carry the app's session cache and superuser client, which
49
+ * it creates once; nothing here keeps state between requests.
50
+ *
51
+ * @throws {TypeError} without a superuser client and without `readableCookie: true`
52
+ */
53
+ export declare function createReactRouterAuth(options: AdapterOptions): ReactRouterAuth;
@@ -0,0 +1,25 @@
1
+ import type { SuperuserClient } from "./superuser-client.js";
2
+ import type { CreateServerClientOptions, MintBrowserTokenOptions } from "./types.js";
3
+ export interface BrowserTokenRenewOptions extends Omit<CreateServerClientOptions, "cookies" | "request" | "origin">, MintBrowserTokenOptions {
4
+ /** Origins besides the request's own that may call the route (see `checkOrigin`). */
5
+ allowedOrigins?: readonly string[];
6
+ /** Mints with `impersonate`. Without it the server client must be in fallback mode. */
7
+ superuser?: SuperuserClient;
8
+ }
9
+ /**
10
+ * The adapter route that renews a browser token: `POST` from the same origin, with the session
11
+ * cookie. It resumes the session through `createServerClient` and checks it with iglo.base
12
+ * (`auth.verify()`): a session revoked since its last check is refused here, though the cache
13
+ * still holds it. On success it answers `200 { token, record, expiresAt, serverTime }` with a
14
+ * freshly minted token, and the session cookie is rewritten if the session was refreshed.
15
+ *
16
+ * Answers: `401` when there is no valid session (the cookie is cleared when iglo.base revoked it,
17
+ * or when impersonate answers `404`: the user was deleted after the check, so the session is
18
+ * over), `403` for a foreign origin, `405` for another method, and `503` when iglo.base cannot be
19
+ * reached, when the session check fails for another reason, or when impersonate answers `401` or
20
+ * `403` (the superuser credentials were refused: missing, expired, revoked, or not a superuser's)
21
+ * or fails for another reason. A `503` keeps the session cookie: the user's session is fine, and
22
+ * an operator's credential problem must not sign every user out. A missing configuration (no
23
+ * superuser client and no `readableCookie`) throws before any request to iglo.base is made.
24
+ */
25
+ export declare function handleBrowserTokenRenew(request: Request, { allowedOrigins, superuser, duration, ...options }: BrowserTokenRenewOptions): Promise<Response>;
@@ -0,0 +1,83 @@
1
+ import Client from "../Client.js";
2
+ import { type AuthRecord } from "../stores/BaseAuthStore.js";
3
+ import type { SendOptions } from "../tools/options.js";
4
+ import type { Loose } from "../tools/loose.js";
5
+ import type { CookieAdapter, CompleteOAuth2Result, CreateServerClientOptions, StartOAuth2Options } from "./types.js";
6
+ export declare class ServerClient extends Client {
7
+ readonly cookies: CookieAdapter;
8
+ private readonly _cookieName;
9
+ private readonly _isSecure;
10
+ private readonly _readable;
11
+ private readonly _options;
12
+ private readonly _clock;
13
+ private _clockOffsetMs;
14
+ private _initialized;
15
+ private _applying;
16
+ private _lastToken;
17
+ readonly auth: {
18
+ /** Checks the session with iglo.base now, bypassing the cache. Throws when it is not valid. */
19
+ verify: () => Promise<AuthRecord>;
20
+ };
21
+ constructor(options: CreateServerClientOptions);
22
+ /** Whether the session cookie is readable by page JavaScript (`readableCookie`, the fallback). */
23
+ get readableCookie(): boolean;
24
+ /**
25
+ * iglo.base's clock in milliseconds, as the last response's `Date` header read it (this
26
+ * process's clock when no response has said yet).
27
+ */
28
+ serverNow(): number;
29
+ /**
30
+ * Every request goes through here: `cache: "no-store"` is applied at the fetch layer,
31
+ * and the server's clock and the collection lifetime are read from each response.
32
+ */
33
+ send<T = Loose>(path: string, options: SendOptions): Promise<T>;
34
+ /** Reads the cookie, then checks or refreshes the session. */
35
+ init(): Promise<this>;
36
+ /**
37
+ * OAuth2 redirect flow, step 1 (docs/design/13-ssr.md, "OAuth2"). Reads the provider's
38
+ * authorization URL, which carries the server's `state` and PKCE challenge, and stores the
39
+ * state, the PKCE verifier, the provider and `redirectTo` in the temporary cookie (10 minutes).
40
+ * Returns the URL with `callbackUrl` as its `redirect_uri`. The caller redirects to it and
41
+ * applies the adapter's cookies to that response.
42
+ *
43
+ * @throws {OAuth2Error} `unknown-provider`, `unsupported-provider` (a POST callback, such as
44
+ * Sign in with Apple), `invalid-callback` or `no-cookie-writer`
45
+ * @throws {ClientResponseError} when iglo.base refuses the auth methods
46
+ */
47
+ startOAuth2(provider: string, options: StartOAuth2Options): Promise<string>;
48
+ /**
49
+ * OAuth2 redirect flow, step 2: the callback route. Reads `code`, `state` and `error` from the
50
+ * callback URL and checks `state` against the temporary cookie. On success it exchanges the
51
+ * code, which writes the session cookie as any sign-in does. The temporary cookie is deleted
52
+ * on every outcome. Failures are returned, not thrown, with `redirectTo` for the caller.
53
+ *
54
+ * @throws only for failures that are not about this sign-in (a network error, a bug)
55
+ */
56
+ completeOAuth2(input: string | URL | {
57
+ url: string;
58
+ }): Promise<CompleteOAuth2Result>;
59
+ private _readOAuth2Cookie;
60
+ private _finishOAuth2;
61
+ /** The cookie rules of this client's session cookie, for the cookies that follow it. */
62
+ private _cookieSettings;
63
+ private _loadCookieAndCheck;
64
+ private _checkSession;
65
+ /** One `auth-refresh` for the token. Runs once per flight; see `RefreshOutcome`. */
66
+ private _requestRefresh;
67
+ private _applyOutcome;
68
+ /** Sets the auth store without triggering the listener; optionally writes the cookie. */
69
+ private _setLocalSession;
70
+ /** A change made by the app on this client: update the cache and the cookie. */
71
+ private _saveSession;
72
+ /** Ends the session on this client: the auth store, the cache entry and the cookie. */
73
+ private _dropSession;
74
+ private _applyLocally;
75
+ private _writeCookie;
76
+ private _writeCookies;
77
+ /**
78
+ * Learns the server's clock from every response, and the collection's token lifetime from
79
+ * a session response (see `SESSION_RESPONSE_PATH`).
80
+ */
81
+ private _observeResponse;
82
+ }
83
+ export declare function createServerClient(options: CreateServerClientOptions): Promise<ServerClient>;
@@ -0,0 +1,24 @@
1
+ import Client from "../Client.js";
2
+ import type { RecordModel } from "../tools/dtos.js";
3
+ import type { SendOptions } from "../tools/options.js";
4
+ import type { Loose } from "../tools/loose.js";
5
+ import type { CreateSuperuserClientOptions } from "./types.js";
6
+ export declare class SuperuserClient extends Client {
7
+ private readonly _options;
8
+ private readonly _clock;
9
+ private _clockOffsetMs;
10
+ constructor(options: CreateSuperuserClientOptions);
11
+ /** iglo.base's clock in milliseconds, as the last response's `Date` header read it. */
12
+ serverNow(): number;
13
+ /**
14
+ * Overriding send ensures cache: 'no-store' and custom fetch stick
15
+ * even if application code assigns pb.beforeSend.
16
+ */
17
+ send<T = Loose>(path: string, options: SendOptions): Promise<T>;
18
+ init(): Promise<this>;
19
+ impersonate(collectionOrRecord: string | RecordModel, recordIdOrDuration?: string | number, duration?: number): Promise<{
20
+ token: string;
21
+ record: RecordModel;
22
+ }>;
23
+ }
24
+ export declare function createSuperuserClient(options: CreateSuperuserClientOptions): Promise<SuperuserClient>;
@@ -0,0 +1,44 @@
1
+ import { type BrowserToken, type ServerClient } from "./index.js";
2
+ import { type AdapterOptions } from "./adapter.js";
3
+ export interface SvelteKitCookies {
4
+ getAll(): Array<{
5
+ name: string;
6
+ value: string;
7
+ }>;
8
+ set(name: string, value: string, options: {
9
+ path: string;
10
+ httpOnly?: boolean;
11
+ sameSite?: boolean | "lax" | "strict" | "none";
12
+ secure?: boolean;
13
+ maxAge?: number;
14
+ expires?: Date;
15
+ domain?: string;
16
+ }): void;
17
+ }
18
+ export interface SvelteKitEvent {
19
+ request: Request;
20
+ url: URL;
21
+ cookies: SvelteKitCookies;
22
+ locals: object;
23
+ }
24
+ export interface SvelteKitAuth {
25
+ /**
26
+ * Use as `export const handle = auth.handle` (or inside `sequence()`). Resumes the session, sets
27
+ * `event.locals.pb` and `event.locals.pbBrowserToken`, answers the adapter routes and the CSRF
28
+ * guard, then calls `resolve(event)`.
29
+ */
30
+ handle(input: {
31
+ event: SvelteKitEvent;
32
+ resolve(event: SvelteKitEvent): Promise<Response>;
33
+ }): Promise<Response>;
34
+ }
35
+ /** What the handle hook puts on `event.locals`; the app declares it in its `App.Locals` type. */
36
+ export interface SvelteKitLocals {
37
+ pb: ServerClient;
38
+ pbBrowserToken: () => Promise<BrowserToken | null>;
39
+ }
40
+ /**
41
+ * Creates the SvelteKit auth. Throws a `TypeError` without a superuser client and without
42
+ * `readableCookie: true` (see `resolveAdapterOptions`).
43
+ */
44
+ export declare function createSvelteKitAuth(options: AdapterOptions): SvelteKitAuth;
@@ -0,0 +1,118 @@
1
+ import type { SerializeOptions } from "../tools/cookie.js";
2
+ import type { AuthRecord } from "../stores/BaseAuthStore.js";
3
+ import type { RecordAuthResponse } from "../services/RecordService.js";
4
+ import type { ClientResponseError } from "../ClientResponseError.js";
5
+ import type { OAuth2Error } from "./oauth2.js";
6
+ export interface Cookie {
7
+ name: string;
8
+ value: string;
9
+ }
10
+ export interface CookieToSet {
11
+ name: string;
12
+ value: string;
13
+ options?: SerializeOptions;
14
+ }
15
+ export type CookieValueMap = Record<string, string>;
16
+ export interface CookieAdapter {
17
+ getAll: () => Cookie[] | Promise<Cookie[]> | CookieValueMap | Promise<CookieValueMap>;
18
+ setAll?: (cookies: CookieToSet[], headers?: Record<string, string>) => void | Promise<void>;
19
+ /**
20
+ * Whether the app's own request is https (set by adapters that know the request).
21
+ * The session cookie is `Secure` and `__Host-` prefixed unless this is false.
22
+ */
23
+ isSecure?: boolean;
24
+ }
25
+ export interface SessionCacheEntry {
26
+ record: AuthRecord;
27
+ checkedAt: number;
28
+ }
29
+ export interface SessionCache {
30
+ get(token: string): Promise<SessionCacheEntry | undefined>;
31
+ set(token: string, record: AuthRecord, checkedAt?: number): Promise<void>;
32
+ delete(token: string): Promise<void>;
33
+ clear(): void;
34
+ runSingleFlight<T>(token: string, fn: () => Promise<T>): Promise<T>;
35
+ readonly size: number;
36
+ readonly ttl: number;
37
+ readonly maxEntries: number;
38
+ clockOffsetMs?: number;
39
+ getCollectionLifetime(collectionId: string): number | undefined;
40
+ setCollectionLifetime(collectionId: string, lifetimeSec: number): void;
41
+ }
42
+ export interface SessionCacheOptions {
43
+ ttl?: number;
44
+ maxEntries?: number;
45
+ clock?: () => number;
46
+ }
47
+ export interface CreateServerClientOptions {
48
+ url: string;
49
+ cookies: CookieAdapter;
50
+ cookieName?: string;
51
+ sessionCache?: SessionCache;
52
+ secure?: boolean;
53
+ origin?: string;
54
+ request?: Request;
55
+ cookieOptions?: Partial<SerializeOptions>;
56
+ /**
57
+ * Fallback without superuser credentials (docs/design/13-ssr.md, "Browser client and realtime"):
58
+ * the session cookie is written without `HttpOnly`, so the browser client can read it. Weaker
59
+ * against XSS than the default: any script on the page can read the session token.
60
+ */
61
+ readableCookie?: boolean;
62
+ lang?: string;
63
+ clock?: () => number;
64
+ fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise<Response>;
65
+ }
66
+ /** What a page needs to start a browser client: a short-lived token and the user's record. */
67
+ export interface BrowserToken {
68
+ token: string;
69
+ record: AuthRecord;
70
+ /** When the token expires, in milliseconds since the epoch (from its `exp` claim). */
71
+ expiresAt: number;
72
+ /**
73
+ * The server's clock when the token was minted, in milliseconds since the epoch: iglo.base's
74
+ * `Date` header as the minting client read it. The browser client measures its own clock
75
+ * against it, so a device clock that is off does not shorten or stretch the token's life.
76
+ */
77
+ serverTime: number;
78
+ }
79
+ export interface MintBrowserTokenOptions {
80
+ /** Lifetime of the minted token in seconds (default 900, 15 minutes). */
81
+ duration?: number;
82
+ }
83
+ export interface CreateSuperuserClientOptions {
84
+ url: string;
85
+ email?: string;
86
+ password?: string;
87
+ token?: string;
88
+ autoRefreshThreshold?: number;
89
+ lang?: string;
90
+ fetch?: (url: RequestInfo | URL, config?: RequestInit) => Promise<Response>;
91
+ /** The clock (default `Date.now`), for tests. */
92
+ clock?: () => number;
93
+ }
94
+ export interface RequestCookieAdapter extends CookieAdapter {
95
+ isSecure: boolean;
96
+ getAll: () => Cookie[];
97
+ setAll: (cookiesToSet: CookieToSet[], headers?: Record<string, string>) => void;
98
+ applyToResponse: (response: Response) => Response;
99
+ readonly queuedCookies: CookieToSet[];
100
+ readonly queuedHeaders: Record<string, string>;
101
+ }
102
+ export interface StartOAuth2Options {
103
+ /** The app's callback URL, as registered with the provider (an absolute http(s) URL). */
104
+ callbackUrl: string;
105
+ /** Where the user goes after sign-in: a same-origin path. Anything else becomes `/`. */
106
+ redirectTo?: string;
107
+ /** The auth collection (default `users`). */
108
+ collection?: string;
109
+ }
110
+ export type CompleteOAuth2Result = {
111
+ ok: true;
112
+ redirectTo: string;
113
+ auth: RecordAuthResponse;
114
+ } | {
115
+ ok: false;
116
+ redirectTo: string;
117
+ error: OAuth2Error | ClientResponseError;
118
+ };
@@ -0,0 +1,52 @@
1
+ import { BaseAuthStore, type AuthRecord } from "./BaseAuthStore.js";
2
+ export type AsyncSaveFunc = (serializedPayload: string) => Promise<void>;
3
+ export type AsyncClearFunc = () => Promise<void>;
4
+ /**
5
+ * AsyncAuthStore is a helper auth store implementation
6
+ * that could be used with any external async persistent layer
7
+ * (key-value db, local file, etc.).
8
+ *
9
+ * Here is an example with the React Native AsyncStorage package:
10
+ *
11
+ * ```
12
+ * import AsyncStorage from "@react-native-async-storage/async-storage";
13
+ * import PocketBase, { AsyncAuthStore } from "pocketbase";
14
+ *
15
+ * const store = new AsyncAuthStore({
16
+ * save: async (serialized) => AsyncStorage.setItem("pb_auth", serialized),
17
+ * initial: AsyncStorage.getItem("pb_auth"),
18
+ * });
19
+ *
20
+ * const pb = new PocketBase("https://example.com", store)
21
+ * ```
22
+ */
23
+ export declare class AsyncAuthStore extends BaseAuthStore {
24
+ private saveFunc;
25
+ private clearFunc?;
26
+ private queue;
27
+ constructor(config: {
28
+ save: AsyncSaveFunc;
29
+ clear?: AsyncClearFunc;
30
+ initial?: string | Promise<unknown>;
31
+ });
32
+ /**
33
+ * @inheritdoc
34
+ */
35
+ save(token: string, record?: AuthRecord): void;
36
+ /**
37
+ * @inheritdoc
38
+ */
39
+ clear(): void;
40
+ /**
41
+ * Initializes the auth store state.
42
+ */
43
+ private _loadInitial;
44
+ /**
45
+ * Appends an async function to the queue.
46
+ */
47
+ private _enqueue;
48
+ /**
49
+ * Starts the queue processing.
50
+ */
51
+ private _dequeue;
52
+ }
@@ -0,0 +1,104 @@
1
+ import { type SerializeOptions } from "../tools/cookie.js";
2
+ import { type RecordModel } from "../tools/dtos.js";
3
+ export type AuthRecord = RecordModel | null;
4
+ export type AuthModel = AuthRecord;
5
+ export type OnStoreChangeFunc = (token: string, record: AuthRecord) => void;
6
+ /**
7
+ * Base AuthStore class that stores the auth state in runtime memory (aka. only for the duration of the store instane).
8
+ *
9
+ * Usually you wouldn't use it directly and instead use the builtin LocalAuthStore, AsyncAuthStore
10
+ * or extend it with your own custom implementation.
11
+ */
12
+ export declare class BaseAuthStore {
13
+ protected baseToken: string;
14
+ protected baseModel: AuthRecord;
15
+ private _onChangeCallbacks;
16
+ /**
17
+ * Retrieves the stored token (if any).
18
+ */
19
+ get token(): string;
20
+ /**
21
+ * Retrieves the stored model data (if any).
22
+ */
23
+ get record(): AuthRecord;
24
+ /**
25
+ * @deprecated use `record` instead.
26
+ */
27
+ get model(): AuthRecord;
28
+ /**
29
+ * Loosely checks if the store has valid token (aka. existing and unexpired exp claim).
30
+ */
31
+ get isValid(): boolean;
32
+ /**
33
+ * Loosely checks whether the currently loaded store state is for superuser.
34
+ *
35
+ * Alternatively you can also compare directly `pb.authStore.record?.collectionName`.
36
+ */
37
+ get isSuperuser(): boolean;
38
+ /**
39
+ * @deprecated use `isSuperuser` instead or simply check the record.collectionName property.
40
+ */
41
+ get isAdmin(): boolean;
42
+ /**
43
+ * @deprecated use `!isSuperuser` instead or simply check the record.collectionName property.
44
+ */
45
+ get isAuthRecord(): boolean;
46
+ /**
47
+ * Saves the provided new token and model data in the auth store.
48
+ */
49
+ save(token: string, record?: AuthRecord): void;
50
+ /**
51
+ * Removes the stored token and model data form the auth store.
52
+ */
53
+ clear(): void;
54
+ /**
55
+ * Parses the provided cookie string and updates the store state
56
+ * with the cookie's token and model data.
57
+ *
58
+ * NB! This function doesn't validate the token or its data.
59
+ * Usually this isn't a concern if you are interacting only with the
60
+ * PocketBase API because it has the proper server-side security checks in place,
61
+ * but if you are using the store `isValid` state for permission controls
62
+ * in a node server (eg. SSR), then it is recommended to call `authRefresh()`
63
+ * after loading the cookie to ensure an up-to-date token and model state.
64
+ * For example:
65
+ *
66
+ * ```js
67
+ * pb.authStore.loadFromCookie("cookie string...");
68
+ *
69
+ * try {
70
+ * // get an up-to-date auth store state by veryfing and refreshing the loaded auth model (if any)
71
+ * pb.authStore.isValid && await pb.collection('users').authRefresh();
72
+ * } catch {
73
+ * // clear the auth store on failed refresh
74
+ * pb.authStore.clear();
75
+ * }
76
+ * ```
77
+ */
78
+ loadFromCookie(cookie: string, key?: string): void;
79
+ /**
80
+ * Exports the current store state as cookie string.
81
+ *
82
+ * By default the following optional attributes are added:
83
+ * - Secure
84
+ * - HttpOnly
85
+ * - SameSite=Strict
86
+ * - Path=/
87
+ * - Expires={the token expiration date}
88
+ *
89
+ * NB! If the generated cookie exceeds 4096 bytes, this method will
90
+ * strip the model data to the bare minimum to try to fit within the
91
+ * recommended size in https://www.rfc-editor.org/rfc/rfc6265#section-6.1.
92
+ */
93
+ exportToCookie(options?: SerializeOptions, key?: string): string;
94
+ /**
95
+ * Register a callback function that will be called on store change.
96
+ *
97
+ * You can set the `fireImmediately` argument to true in order to invoke
98
+ * the provided callback right after registration.
99
+ *
100
+ * Returns a removal function that you could call to "unsubscribe" from the changes.
101
+ */
102
+ onChange(callback: OnStoreChangeFunc, fireImmediately?: boolean): () => void;
103
+ protected triggerChange(): void;
104
+ }
@@ -0,0 +1,48 @@
1
+ import { BaseAuthStore, type AuthRecord } from "./BaseAuthStore.js";
2
+ /**
3
+ * The default token store for browsers with auto fallback
4
+ * to runtime/memory if local storage is undefined (e.g. in node env).
5
+ */
6
+ export declare class LocalAuthStore extends BaseAuthStore {
7
+ private storageFallback;
8
+ private storageKey;
9
+ constructor(storageKey?: string);
10
+ /**
11
+ * @inheritdoc
12
+ */
13
+ get token(): string;
14
+ /**
15
+ * @inheritdoc
16
+ */
17
+ get record(): AuthRecord;
18
+ /**
19
+ * @deprecated use `record` instead.
20
+ */
21
+ get model(): AuthRecord;
22
+ /**
23
+ * @inheritdoc
24
+ */
25
+ save(token: string, record?: AuthRecord): void;
26
+ /**
27
+ * @inheritdoc
28
+ */
29
+ clear(): void;
30
+ /**
31
+ * Retrieves `key` from the browser's local storage
32
+ * (or runtime/memory if local storage is undefined).
33
+ */
34
+ private _storageGet;
35
+ /**
36
+ * Stores a new data in the browser's local storage
37
+ * (or runtime/memory if local storage is undefined).
38
+ */
39
+ private _storageSet;
40
+ /**
41
+ * Removes `key` from the browser's local storage and the runtime/memory.
42
+ */
43
+ private _storageRemove;
44
+ /**
45
+ * Updates the current store state on localStorage change.
46
+ */
47
+ private _bindStorageEvent;
48
+ }
@@ -0,0 +1,31 @@
1
+ import type { LooseObject } from "./loose.js";
2
+ export interface ParseOptions {
3
+ decode?: (val: string) => string;
4
+ }
5
+ /**
6
+ * Parses the given cookie header string into an object
7
+ * The object has the various cookies as keys(names) => values
8
+ */
9
+ export declare function cookieParse(str: string, options?: ParseOptions): LooseObject;
10
+ export interface SerializeOptions {
11
+ encode?: (val: string | number | boolean) => string;
12
+ maxAge?: number;
13
+ domain?: string;
14
+ path?: string;
15
+ expires?: Date;
16
+ httpOnly?: boolean;
17
+ secure?: boolean;
18
+ priority?: string;
19
+ sameSite?: boolean | string;
20
+ }
21
+ /**
22
+ * Serialize data into a cookie header.
23
+ *
24
+ * Serialize the a name value pair into a cookie string suitable for
25
+ * http headers. An optional options object specified cookie parameters.
26
+ *
27
+ * ```js
28
+ * cookieSerialize('foo', 'bar', { httpOnly: true }) // "foo=bar; httpOnly"
29
+ * ```
30
+ */
31
+ export declare function cookieSerialize(name: string, val: string, options?: SerializeOptions): string;