@altenginenet/sdk 0.0.0-stage → 0.1.2
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 +429 -2
- package/dist/auth.cjs +312 -0
- package/dist/auth.cjs.map +1 -0
- package/dist/auth.d.cts +1 -0
- package/dist/auth.d.ts +1 -0
- package/dist/auth.js +11 -0
- package/dist/auth.js.map +1 -0
- package/dist/channel.cjs +249 -0
- package/dist/channel.cjs.map +1 -0
- package/dist/channel.d.cts +1 -0
- package/dist/channel.d.ts +1 -0
- package/dist/channel.js +7 -0
- package/dist/channel.js.map +1 -0
- package/dist/chunk-6Q4X4E7X.js +291 -0
- package/dist/chunk-6Q4X4E7X.js.map +1 -0
- package/dist/chunk-NAQQAMY7.js +225 -0
- package/dist/chunk-NAQQAMY7.js.map +1 -0
- package/dist/client-rCIrl668.d.cts +201 -0
- package/dist/client-rCIrl668.d.ts +201 -0
- package/dist/index.cjs +1974 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1951 -0
- package/dist/index.d.ts +1951 -0
- package/dist/index.js +1431 -0
- package/dist/index.js.map +1 -0
- package/dist/socket-DqIm8vll.d.cts +144 -0
- package/dist/socket-DqIm8vll.d.ts +144 -0
- package/examples/first-write.mjs +14 -0
- package/package.json +85 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/channel/socket.ts"],"sourcesContent":["/** ChannelSocket — the browser/edge WebSocket subscriber for altengine channels.\n *\n * Standalone and browser-safe: no API keys, no other SDK imports. Your backend\n * mints a subscriber token (`ChannelClient.createToken`) and hands the response\n * (`{token, ws_endpoint, protocols}`) to the page; the socket does the rest — connect, auto-reconnect with backoff,\n * token re-mint on reconnect, resubscribe, and keepalive pings.\n */\n\nimport type { ChannelMessage } from \"./types.js\";\n\nexport type SocketState = \"idle\" | \"connecting\" | \"open\" | \"reconnecting\" | \"closed\";\n\nexport interface SocketToken {\n token: string;\n /** Subscribe URL without the token, from the token response. */\n ws_endpoint?: string;\n /** Subprotocols that carry the token, from the token response. */\n protocols?: string[];\n /** @deprecated The subscribe URL with the token in its query string. Used only when the\n * response has no `ws_endpoint` (an older server). */\n ws_url?: string;\n}\n\n/** The subprotocol offered alongside the token, and the one the server answers with. */\nconst WS_PROTOCOL = \"altengine.v1\";\nconst WS_TOKEN_PROTOCOL_PREFIX = \"altengine.token.\";\n\nexport interface ChannelSocketOptions {\n /** Called before every connection attempt (including reconnects) so tokens are\n * always fresh. Return the token-mint response (or `{token}` with `url` set). */\n getToken: () => Promise<SocketToken> | SocketToken;\n /** Explicit subscribe URL (`wss://…/v1/channel/<instance>/subscribe`) when the token\n * response has no `ws_endpoint`. The token is sent as a subprotocol, not in the URL. */\n url?: string;\n /** Subset of the token's channels to subscribe on connect (default: all). */\n channels?: string[];\n /** WebSocket constructor for runtimes without a global one. */\n webSocket?: new (url: string, protocols?: string | string[]) => WebSocket;\n /** Keepalive ping interval in ms (default 30000, at most 60000). A silent\n * connection past ~1.5 intervals is treated as dead and reconnected. */\n pingIntervalMs?: number;\n /** Reconnect backoff base/cap in ms (defaults 250 / 30000). */\n backoffBaseMs?: number;\n backoffMaxMs?: number;\n}\n\nexport interface SocketEvents {\n message: ChannelMessage;\n state: SocketState;\n error: Error;\n /** Channels the server would not subscribe this socket to — on open or on a subscribe() —\n * because a channel or user limit was reached. They stay requested and are tried again on\n * the next reconnect. */\n refused: string[];\n}\n\ntype Listener<T> = (payload: T) => void;\n\n// readyState values, spelled out rather than read off the global `WebSocket`: Node 20 has no\n// global one (that is what the `webSocket` option is for), and `WebSocket.OPEN` there is a\n// ReferenceError the first time a connected socket is checked.\nconst CONNECTING = 0;\nconst OPEN = 1;\n\nexport class ChannelSocket {\n private readonly opts: ChannelSocketOptions;\n private readonly listeners: { [K in keyof SocketEvents]: Set<Listener<SocketEvents[K]>> } = {\n message: new Set(),\n state: new Set(),\n error: new Set(),\n refused: new Set(),\n };\n\n private ws?: WebSocket;\n private stateValue: SocketState = \"idle\";\n private desired = new Set<string>();\n private explicitChannels: boolean;\n private closedByUser = false;\n private attempts = 0;\n private pingTimer?: ReturnType<typeof setInterval>;\n private lastActivity = 0;\n private reconnectTimer?: ReturnType<typeof setTimeout>;\n private pendingSubscribes: { channels: string[]; resolve: (channels: string[]) => void; reject: (e: Error) => void }[] = [];\n private pendingPublishes: { resolve: (delivered: number) => void; reject: (e: Error) => void }[] = [];\n\n constructor(opts: ChannelSocketOptions) {\n this.opts = opts;\n this.explicitChannels = opts.channels !== undefined;\n for (const c of opts.channels ?? []) this.desired.add(c);\n }\n\n get state(): SocketState {\n return this.stateValue;\n }\n\n on<K extends keyof SocketEvents>(event: K, fn: Listener<SocketEvents[K]>): () => void {\n this.listeners[event].add(fn);\n return () => this.listeners[event].delete(fn);\n }\n\n private emit<K extends keyof SocketEvents>(event: K, payload: SocketEvents[K]): void {\n for (const fn of this.listeners[event]) fn(payload);\n }\n\n private setState(s: SocketState): void {\n if (this.stateValue === s) return;\n this.stateValue = s;\n this.emit(\"state\", s);\n }\n\n /** Connect (resolves once the socket is open). Reconnects automatically until\n * `close()` is called. */\n async connect(): Promise<void> {\n this.closedByUser = false;\n if (this.ws && (this.ws.readyState === OPEN || this.ws.readyState === CONNECTING)) return;\n await this.dial();\n }\n\n /** Stop reconnecting and close the connection. */\n close(): void {\n this.closedByUser = true;\n if (this.reconnectTimer) clearTimeout(this.reconnectTimer);\n this.stopPing();\n this.failPending(new Error(\"socket closed\"));\n this.ws?.close(1000, \"client close\");\n this.ws = undefined;\n this.setState(\"closed\");\n }\n\n /** Subscribe to more channels (tracked and re-applied after reconnects).\n * Resolves with the server's ack. */\n async subscribe(channels: string[]): Promise<string[]> {\n for (const c of channels) this.desired.add(c);\n this.explicitChannels = true;\n if (!this.isOpen()) return [...this.desired];\n return new Promise<string[]>((resolve, reject) => {\n this.pendingSubscribes.push({ channels, resolve, reject });\n this.send({ type: \"subscribe\", channels });\n });\n }\n\n /** Unsubscribe from channels. */\n unsubscribe(channels: string[]): void {\n for (const c of channels) this.desired.delete(c);\n this.explicitChannels = true;\n if (this.isOpen()) this.send({ type: \"unsubscribe\", channels });\n }\n\n /** Publish over the socket (requires a ws-capable `publish` token). Resolves\n * with the delivered count from the server's ack. */\n async publish(channel: string, data: unknown): Promise<number> {\n if (!this.isOpen()) throw new Error(\"socket is not open\");\n return new Promise<number>((resolve, reject) => {\n this.pendingPublishes.push({ resolve, reject });\n this.send({ type: \"publish\", channel, data });\n });\n }\n\n // --- internals ---\n\n private isOpen(): boolean {\n return !!this.ws && this.ws.readyState === OPEN;\n }\n\n private send(frame: unknown): void {\n this.ws?.send(typeof frame === \"string\" ? frame : JSON.stringify(frame));\n }\n\n /** Where to dial, and with which subprotocols. The token travels as a subprotocol\n * (`altengine.token.<token>`, beside `altengine.v1`), never in the URL — except against an\n * older server whose response has only `ws_url`, which is opened as it is. */\n private target(tok: SocketToken): { url: string; protocols?: string[] } {\n const endpoint = tok.ws_endpoint ?? (tok.ws_url ? undefined : this.opts.url);\n let url: URL;\n let protocols: string[] | undefined;\n if (endpoint) {\n url = new URL(endpoint);\n protocols = tok.protocols?.length ? tok.protocols : [WS_PROTOCOL, WS_TOKEN_PROTOCOL_PREFIX + tok.token];\n } else if (tok.ws_url) {\n url = new URL(tok.ws_url);\n if (!url.searchParams.has(\"token\")) url.searchParams.set(\"token\", tok.token);\n } else {\n throw new Error(\"no WebSocket URL: token response had no ws_endpoint and no url option was set\");\n }\n // Narrow the initial subscription to the explicitly requested subset.\n if (this.explicitChannels && this.desired.size) {\n url.searchParams.set(\"channels\", [...this.desired].join(\",\"));\n }\n return { url: url.toString(), protocols };\n }\n\n private async dial(): Promise<void> {\n this.setState(this.attempts === 0 ? \"connecting\" : \"reconnecting\");\n let tok: SocketToken;\n try {\n tok = await this.opts.getToken();\n } catch (err) {\n this.emit(\"error\", err instanceof Error ? err : new Error(String(err)));\n this.scheduleReconnect();\n return;\n }\n\n const WS = this.opts.webSocket ?? (globalThis.WebSocket as typeof WebSocket | undefined);\n if (!WS) throw new Error(\"no WebSocket implementation; pass { webSocket } (e.g. `ws` on Node < 22)\");\n\n await new Promise<void>((resolve) => {\n let settled = false;\n const { url, protocols } = this.target(tok);\n const ws = protocols ? new WS(url, protocols) : new WS(url);\n this.ws = ws;\n\n ws.onopen = () => {\n settled = true;\n this.attempts = 0;\n this.lastActivity = Date.now();\n this.setState(\"open\");\n this.startPing();\n resolve();\n };\n ws.onmessage = (ev: MessageEvent) => this.handleMessage(ev);\n ws.onerror = () => {\n // onclose always follows; error details aren't portable across runtimes.\n };\n ws.onclose = (ev: CloseEvent) => {\n this.stopPing();\n this.failPending(new Error(`socket closed (${ev.code})`));\n if (!settled) {\n settled = true;\n resolve();\n }\n if (!this.closedByUser) this.scheduleReconnect();\n };\n });\n }\n\n private handleMessage(ev: MessageEvent): void {\n this.lastActivity = Date.now();\n const raw = typeof ev.data === \"string\" ? ev.data : \"\";\n if (raw === \"pong\" || raw === \"ping\") return;\n let frame: any;\n try {\n frame = JSON.parse(raw);\n } catch {\n return;\n }\n switch (frame?.type) {\n case \"subscribed\": {\n // Only settle the oldest pending subscribe if this ack covers its channels —\n // an unsolicited ack (e.g. for the connect-time ?channels= subscription)\n // arriving late must not steal a runtime subscribe()'s resolution.\n // A refused channel is answered too, so it counts as covered; the promise resolves with\n // the channels actually admitted.\n const refused: string[] = Array.isArray(frame.refused) ? frame.refused : [];\n const head = this.pendingSubscribes[0];\n const acked = new Set<string>([...(frame.channels ?? []), ...refused]);\n if (head && head.channels.every((c) => acked.has(c))) {\n this.pendingSubscribes.shift()!.resolve(frame.channels ?? []);\n }\n if (refused.length) this.emit(\"refused\", refused);\n return;\n }\n case \"published\":\n this.pendingPublishes.shift()?.resolve(frame.delivered ?? 0);\n return;\n case \"error\": {\n const err = new Error(typeof frame.error === \"string\" ? frame.error : JSON.stringify(frame.error));\n // An error ack settles the oldest pending request, if any.\n (this.pendingPublishes.shift() ?? this.pendingSubscribes.shift())?.reject(err);\n this.emit(\"error\", err);\n return;\n }\n default:\n if (frame && typeof frame.channel === \"string\" && frame.type === undefined) {\n this.emit(\"message\", frame as ChannelMessage);\n }\n }\n }\n\n private startPing(): void {\n // The server closes (4408) a connection that pinged and then stops for 15 minutes.\n const interval = Math.min(this.opts.pingIntervalMs ?? 30_000, 60_000);\n this.stopPing();\n this.pingTimer = setInterval(() => {\n if (!this.isOpen()) return;\n if (Date.now() - this.lastActivity > interval * 1.5) {\n // Dead connection: no traffic (not even pongs). Force a reconnect.\n this.ws?.close(4000, \"keepalive timeout\");\n return;\n }\n this.send(\"ping\");\n }, interval);\n }\n\n private stopPing(): void {\n if (this.pingTimer) clearInterval(this.pingTimer);\n this.pingTimer = undefined;\n }\n\n private scheduleReconnect(): void {\n if (this.closedByUser) return;\n const base = this.opts.backoffBaseMs ?? 250;\n const cap = this.opts.backoffMaxMs ?? 30_000;\n const delay = Math.min(base * 2 ** this.attempts, cap) * (0.5 + Math.random() * 0.5);\n this.attempts++;\n this.setState(\"reconnecting\");\n this.reconnectTimer = setTimeout(() => void this.dial(), delay);\n }\n\n private failPending(err: Error): void {\n for (const p of this.pendingSubscribes.splice(0)) p.reject(err);\n for (const p of this.pendingPublishes.splice(0)) p.reject(err);\n }\n}\n\nexport type { ChannelMessage } from \"./types.js\";\n"],"mappings":";AAwBA,IAAM,cAAc;AACpB,IAAM,2BAA2B;AAoCjC,IAAM,aAAa;AACnB,IAAM,OAAO;AAEN,IAAM,gBAAN,MAAoB;AAAA,EACR;AAAA,EACA,YAA2E;AAAA,IAC1F,SAAS,oBAAI,IAAI;AAAA,IACjB,OAAO,oBAAI,IAAI;AAAA,IACf,OAAO,oBAAI,IAAI;AAAA,IACf,SAAS,oBAAI,IAAI;AAAA,EACnB;AAAA,EAEQ;AAAA,EACA,aAA0B;AAAA,EAC1B,UAAU,oBAAI,IAAY;AAAA,EAC1B;AAAA,EACA,eAAe;AAAA,EACf,WAAW;AAAA,EACX;AAAA,EACA,e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C1E,eAAK,KAAK,WAAW,KAAuB;AAAA,QAC9C;AAAA,IACJ;AAAA,EACF;AAAA,EAEQ,YAAkB;AAExB,UAAM,WAAW,KAAK,IAAI,KAAK,KAAK,kBAAkB,KAAQ,GAAM;AACpE,SAAK,SAAS;AACd,SAAK,YAAY,YAAY,MAAM;AACjC,UAAI,CAAC,KAAK,OAAO,EAAG;AACpB,UAAI,KAAK,IAAI,IAAI,KAAK,eAAe,WAAW,KAAK;AAEnD,aAAK,IAAI,MAAM,KAAM,mBAAmB;AACxC;AAAA,MACF;AACA,WAAK,KAAK,MAAM;AAAA,IAClB,GAAG,QAAQ;AAAA,EACb;AAAA,EAEQ,WAAiB;AACvB,QAAI,KAAK,UAAW,eAAc,KAAK,SAAS;AAChD,SAAK,YAAY;AAAA,EACnB;AAAA,EAEQ,oBAA0B;AAChC,QAAI,KAAK,aAAc;AACvB,UAAM,OAAO,KAAK,KAAK,iBAAiB;AACxC,UAAM,MAAM,KAAK,KAAK,gBAAgB;AACtC,UAAM,QAAQ,KAAK,IAAI,OAAO,KAAK,KAAK,UAAU,GAAG,KAAK,MAAM,KAAK,OAAO,IAAI;AAChF,SAAK;AACL,SAAK,SAAS,cAAc;AAC5B,SAAK,iBAAiB,WAAW,MAAM,KAAK,KAAK,KAAK,GAAG,KAAK;AAAA,EAChE;AAAA,EAEQ,YAAY,KAAkB;AACpC,eAAW,KAAK,KAAK,kBAAkB,OAAO,CAAC,EAAG,GAAE,OAAO,GAAG;AAC9D,eAAW,KAAK,KAAK,iBAAiB,OAAO,CAAC,EAAG,GAAE,OAAO,GAAG;AAAA,EAC/D;AACF;","names":[]}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** Where the signed-in session is kept between page loads. Implement this to use
|
|
2
|
+
* cookies, IndexedDB, React Native's AsyncStorage (via a sync cache), or nothing
|
|
3
|
+
* at all. The default picks `localStorage` in the browser and falls back to an
|
|
4
|
+
* in-memory store everywhere else (Node, SSR, private-mode failures). */
|
|
5
|
+
interface TokenStorage {
|
|
6
|
+
get(key: string): string | null;
|
|
7
|
+
set(key: string, value: string): void;
|
|
8
|
+
remove(key: string): void;
|
|
9
|
+
}
|
|
10
|
+
/** A `TokenStorage` that forgets everything when the process/tab goes away. */
|
|
11
|
+
declare function memoryStorage(): TokenStorage;
|
|
12
|
+
/** `localStorage` when it's present AND writable, else an in-memory store.
|
|
13
|
+
* Safari private mode throws on `setItem`, so this probes with a real write. */
|
|
14
|
+
declare function defaultStorage(): TokenStorage;
|
|
15
|
+
|
|
16
|
+
/** Auth wire types. Field names are wire-verbatim (snake_case) — they double as
|
|
17
|
+
* the API reference for `/v1/auth/{instance}`. */
|
|
18
|
+
/** One field the instance's sign-up form collects. The field whose `key` equals
|
|
19
|
+
* `AuthConfig.identity_field` is the unique login handle; every other field is
|
|
20
|
+
* stored on the user's `claims`. */
|
|
21
|
+
interface AuthField {
|
|
22
|
+
key: string;
|
|
23
|
+
type: "email" | "string" | "number" | "boolean";
|
|
24
|
+
required: boolean;
|
|
25
|
+
label?: string;
|
|
26
|
+
}
|
|
27
|
+
/** The instance's public, client-safe sign-in configuration (`GET /config`).
|
|
28
|
+
* Safe to fetch before authenticating — it contains no secrets. */
|
|
29
|
+
interface AuthConfig {
|
|
30
|
+
instance: string;
|
|
31
|
+
allow_signup: boolean;
|
|
32
|
+
/** Which collected field is the unique login handle (e.g. "email", "username"). */
|
|
33
|
+
identity_field: string;
|
|
34
|
+
fields: AuthField[];
|
|
35
|
+
captcha: {
|
|
36
|
+
enabled: boolean;
|
|
37
|
+
site_key?: string;
|
|
38
|
+
};
|
|
39
|
+
methods: {
|
|
40
|
+
password: boolean;
|
|
41
|
+
passkeys: boolean;
|
|
42
|
+
passwordless: boolean;
|
|
43
|
+
totp: boolean;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** An end user of your app (not an altengine account).
|
|
47
|
+
*
|
|
48
|
+
* `profile` holds the fields the user supplied at sign-up (name, etc.), read in
|
|
49
|
+
* access rules as `$auth.profile.X` — self-asserted, never authoritative. `claims`
|
|
50
|
+
* is server/admin-set only, read as `$auth.claims.X` — authoritative, safe to
|
|
51
|
+
* authorize on. A user can never write `claims`, which is what makes it safe to
|
|
52
|
+
* base access rules on it. */
|
|
53
|
+
interface AuthUser {
|
|
54
|
+
uid: string;
|
|
55
|
+
identifier: string;
|
|
56
|
+
profile?: Record<string, unknown>;
|
|
57
|
+
claims?: Record<string, unknown>;
|
|
58
|
+
totpEnabled?: boolean;
|
|
59
|
+
}
|
|
60
|
+
/** Tokens returned by sign-up / sign-in / refresh. `expires_at` and
|
|
61
|
+
* `refresh_expires_at` are unix SECONDS. */
|
|
62
|
+
interface AuthTokens {
|
|
63
|
+
id_token: string;
|
|
64
|
+
refresh_token: string;
|
|
65
|
+
expires_at: number;
|
|
66
|
+
refresh_expires_at: number;
|
|
67
|
+
}
|
|
68
|
+
/** A completed sign-in: tokens plus the user they belong to. */
|
|
69
|
+
interface AuthSession extends AuthTokens {
|
|
70
|
+
user: AuthUser;
|
|
71
|
+
}
|
|
72
|
+
/** Returned instead of tokens when the account has two-factor enabled. Exchange
|
|
73
|
+
* `mfa_token` plus the authenticator code at `POST /2fa/verify`. */
|
|
74
|
+
interface MfaChallenge {
|
|
75
|
+
mfa_required: true;
|
|
76
|
+
mfa_token: string;
|
|
77
|
+
}
|
|
78
|
+
/** The two possible outcomes of a sign-in attempt. */
|
|
79
|
+
type SignInResult = {
|
|
80
|
+
status: "signed_in";
|
|
81
|
+
session: AuthSession;
|
|
82
|
+
} | {
|
|
83
|
+
status: "mfa_required";
|
|
84
|
+
mfaToken: string;
|
|
85
|
+
};
|
|
86
|
+
/** Persisted session shape (what a `TokenStorage` holds). */
|
|
87
|
+
interface StoredSession {
|
|
88
|
+
id_token: string;
|
|
89
|
+
refresh_token: string;
|
|
90
|
+
expires_at: number;
|
|
91
|
+
user: AuthUser | null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** AuthClient — the browser-side identity client for `/v1/auth/{instance}`.
|
|
95
|
+
*
|
|
96
|
+
* This is the piece that lets a client-side app talk to altengine with **no
|
|
97
|
+
* backend of its own**: the end user signs in here, and the resulting `id_token`
|
|
98
|
+
* is what Datastore/Channel requests carry. Access rules on the auth instance
|
|
99
|
+
* decide what that user may read and write.
|
|
100
|
+
*
|
|
101
|
+
* Deliberately self-contained and API-key-free (like `ChannelSocket`) so it is
|
|
102
|
+
* safe to ship to a browser — see the `@altenginenet/sdk/auth` subpath export.
|
|
103
|
+
*
|
|
104
|
+
* ```ts
|
|
105
|
+
* import { AuthClient } from "@altenginenet/sdk/auth";
|
|
106
|
+
* import { AltEngine } from "@altenginenet/sdk";
|
|
107
|
+
*
|
|
108
|
+
* const auth = new AuthClient({ instance: "myapp-auth" });
|
|
109
|
+
* await auth.signIn("alice@example.com", "hunter2");
|
|
110
|
+
*
|
|
111
|
+
* // Hand the client to the SDK: every request now carries the user's token.
|
|
112
|
+
* const ae = new AltEngine({ auth });
|
|
113
|
+
* const { documents } = await ae.datastore("myapp").query("posts", { limit: 20 });
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
|
|
117
|
+
interface AuthClientOptions {
|
|
118
|
+
/** The auth instance name, e.g. "myapp-auth". */
|
|
119
|
+
instance: string;
|
|
120
|
+
/** API origin override. Resolution order: this → `dev: true` → production. */
|
|
121
|
+
baseUrl?: string;
|
|
122
|
+
/** Target the local emulator (`altengine dev`) at `http://127.0.0.1:9191`. */
|
|
123
|
+
dev?: boolean;
|
|
124
|
+
/** Where to persist the session (default: `localStorage`, else in-memory).
|
|
125
|
+
* Pass `memoryStorage()` to keep the session out of storage entirely. */
|
|
126
|
+
storage?: TokenStorage;
|
|
127
|
+
/** Storage key prefix, so several apps/instances can share one origin.
|
|
128
|
+
* Defaults to `altengine.auth.<instance>`. */
|
|
129
|
+
storageKey?: string;
|
|
130
|
+
/** Custom fetch (tests, polyfills). Defaults to `globalThis.fetch`. */
|
|
131
|
+
fetch?: typeof globalThis.fetch;
|
|
132
|
+
/** Refresh the id_token this many seconds before it expires (default 30). */
|
|
133
|
+
refreshSkewSeconds?: number;
|
|
134
|
+
}
|
|
135
|
+
type Listener = (user: AuthUser | null) => void;
|
|
136
|
+
declare class AuthClient {
|
|
137
|
+
readonly instance: string;
|
|
138
|
+
readonly baseUrl: string;
|
|
139
|
+
private readonly base;
|
|
140
|
+
private readonly storage;
|
|
141
|
+
private readonly key;
|
|
142
|
+
private readonly fetchImpl;
|
|
143
|
+
private readonly skew;
|
|
144
|
+
private readonly listeners;
|
|
145
|
+
private session;
|
|
146
|
+
/** In-flight refresh, so concurrent requests share one round trip. */
|
|
147
|
+
private refreshing;
|
|
148
|
+
constructor(opts: AuthClientOptions);
|
|
149
|
+
/** The signed-in user, or null. Reads persisted state, so it survives reloads. */
|
|
150
|
+
get user(): AuthUser | null;
|
|
151
|
+
get isSignedIn(): boolean;
|
|
152
|
+
/** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */
|
|
153
|
+
onChange(fn: Listener): () => void;
|
|
154
|
+
private emit;
|
|
155
|
+
private load;
|
|
156
|
+
private save;
|
|
157
|
+
private adopt;
|
|
158
|
+
private call;
|
|
159
|
+
/** The instance's public sign-in configuration — which fields the sign-up form
|
|
160
|
+
* collects, which one is the login identity, and which methods are enabled.
|
|
161
|
+
* Fetch this to render a sign-in UI that matches the instance's settings. */
|
|
162
|
+
config(): Promise<AuthConfig>;
|
|
163
|
+
/** Create an account. Pass the configured sign-up fields plus `password`,
|
|
164
|
+
* e.g. `{ email, name, password }`. Signs the new user in. */
|
|
165
|
+
signUp(fields: Record<string, unknown>): Promise<AuthSession>;
|
|
166
|
+
/** Sign in with the identity field + password. When the account has two-factor
|
|
167
|
+
* enabled this resolves to `{ status: "mfa_required" }` and you must call
|
|
168
|
+
* {@link verifyMfa} with the code — no tokens are issued until then. */
|
|
169
|
+
signIn(identifier: string, password: string): Promise<SignInResult>;
|
|
170
|
+
/** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */
|
|
171
|
+
verifyMfa(mfaToken: string, code: string): Promise<AuthSession>;
|
|
172
|
+
/** Start passwordless sign-in: emails a one-time code. Always resolves — the
|
|
173
|
+
* server never reveals whether the account exists. */
|
|
174
|
+
passwordlessStart(identifier: string): Promise<void>;
|
|
175
|
+
/** Finish passwordless sign-in with the emailed code. */
|
|
176
|
+
passwordlessVerify(identifier: string, code: string): Promise<SignInResult>;
|
|
177
|
+
/** Start a password reset: emails a one-time code. Always resolves. */
|
|
178
|
+
passwordResetStart(identifier: string): Promise<void>;
|
|
179
|
+
/** Finish a password reset with the emailed code and a new password. */
|
|
180
|
+
passwordResetVerify(identifier: string, code: string, password: string): Promise<void>;
|
|
181
|
+
/** The signed-in user, re-read from the server (picks up claim changes). */
|
|
182
|
+
me(): Promise<AuthUser>;
|
|
183
|
+
/** Revoke the refresh token server-side and clear local state. Always clears
|
|
184
|
+
* locally, even if the network call fails. */
|
|
185
|
+
signOut(): Promise<void>;
|
|
186
|
+
/** Force a refresh-token rotation and return the new id_token. */
|
|
187
|
+
refresh(): Promise<string>;
|
|
188
|
+
/**
|
|
189
|
+
* The current id_token, refreshed first if it is expired or about to be.
|
|
190
|
+
* Returns `undefined` when nobody is signed in. This is the `TokenProvider`
|
|
191
|
+
* the SDK calls before every Datastore/Search/Channel request — pass the
|
|
192
|
+
* client as `new AltEngine({ auth })` and tokens stay fresh automatically.
|
|
193
|
+
*
|
|
194
|
+
* Concurrent callers share a single refresh. If the refresh fails because the
|
|
195
|
+
* session is truly gone (401/403), local state is cleared so the app can react
|
|
196
|
+
* via {@link onChange} instead of retrying forever.
|
|
197
|
+
*/
|
|
198
|
+
getToken(): Promise<string | undefined>;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export { AuthClient as A, type MfaChallenge as M, type SignInResult as S, type TokenStorage as T, type AuthClientOptions as a, type AuthConfig as b, type AuthField as c, type AuthSession as d, type AuthTokens as e, type AuthUser as f, type StoredSession as g, defaultStorage as h, memoryStorage as m };
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** Where the signed-in session is kept between page loads. Implement this to use
|
|
2
|
+
* cookies, IndexedDB, React Native's AsyncStorage (via a sync cache), or nothing
|
|
3
|
+
* at all. The default picks `localStorage` in the browser and falls back to an
|
|
4
|
+
* in-memory store everywhere else (Node, SSR, private-mode failures). */
|
|
5
|
+
interface TokenStorage {
|
|
6
|
+
get(key: string): string | null;
|
|
7
|
+
set(key: string, value: string): void;
|
|
8
|
+
remove(key: string): void;
|
|
9
|
+
}
|
|
10
|
+
/** A `TokenStorage` that forgets everything when the process/tab goes away. */
|
|
11
|
+
declare function memoryStorage(): TokenStorage;
|
|
12
|
+
/** `localStorage` when it's present AND writable, else an in-memory store.
|
|
13
|
+
* Safari private mode throws on `setItem`, so this probes with a real write. */
|
|
14
|
+
declare function defaultStorage(): TokenStorage;
|
|
15
|
+
|
|
16
|
+
/** Auth wire types. Field names are wire-verbatim (snake_case) — they double as
|
|
17
|
+
* the API reference for `/v1/auth/{instance}`. */
|
|
18
|
+
/** One field the instance's sign-up form collects. The field whose `key` equals
|
|
19
|
+
* `AuthConfig.identity_field` is the unique login handle; every other field is
|
|
20
|
+
* stored on the user's `claims`. */
|
|
21
|
+
interface AuthField {
|
|
22
|
+
key: string;
|
|
23
|
+
type: "email" | "string" | "number" | "boolean";
|
|
24
|
+
required: boolean;
|
|
25
|
+
label?: string;
|
|
26
|
+
}
|
|
27
|
+
/** The instance's public, client-safe sign-in configuration (`GET /config`).
|
|
28
|
+
* Safe to fetch before authenticating — it contains no secrets. */
|
|
29
|
+
interface AuthConfig {
|
|
30
|
+
instance: string;
|
|
31
|
+
allow_signup: boolean;
|
|
32
|
+
/** Which collected field is the unique login handle (e.g. "email", "username"). */
|
|
33
|
+
identity_field: string;
|
|
34
|
+
fields: AuthField[];
|
|
35
|
+
captcha: {
|
|
36
|
+
enabled: boolean;
|
|
37
|
+
site_key?: string;
|
|
38
|
+
};
|
|
39
|
+
methods: {
|
|
40
|
+
password: boolean;
|
|
41
|
+
passkeys: boolean;
|
|
42
|
+
passwordless: boolean;
|
|
43
|
+
totp: boolean;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** An end user of your app (not an altengine account).
|
|
47
|
+
*
|
|
48
|
+
* `profile` holds the fields the user supplied at sign-up (name, etc.), read in
|
|
49
|
+
* access rules as `$auth.profile.X` — self-asserted, never authoritative. `claims`
|
|
50
|
+
* is server/admin-set only, read as `$auth.claims.X` — authoritative, safe to
|
|
51
|
+
* authorize on. A user can never write `claims`, which is what makes it safe to
|
|
52
|
+
* base access rules on it. */
|
|
53
|
+
interface AuthUser {
|
|
54
|
+
uid: string;
|
|
55
|
+
identifier: string;
|
|
56
|
+
profile?: Record<string, unknown>;
|
|
57
|
+
claims?: Record<string, unknown>;
|
|
58
|
+
totpEnabled?: boolean;
|
|
59
|
+
}
|
|
60
|
+
/** Tokens returned by sign-up / sign-in / refresh. `expires_at` and
|
|
61
|
+
* `refresh_expires_at` are unix SECONDS. */
|
|
62
|
+
interface AuthTokens {
|
|
63
|
+
id_token: string;
|
|
64
|
+
refresh_token: string;
|
|
65
|
+
expires_at: number;
|
|
66
|
+
refresh_expires_at: number;
|
|
67
|
+
}
|
|
68
|
+
/** A completed sign-in: tokens plus the user they belong to. */
|
|
69
|
+
interface AuthSession extends AuthTokens {
|
|
70
|
+
user: AuthUser;
|
|
71
|
+
}
|
|
72
|
+
/** Returned instead of tokens when the account has two-factor enabled. Exchange
|
|
73
|
+
* `mfa_token` plus the authenticator code at `POST /2fa/verify`. */
|
|
74
|
+
interface MfaChallenge {
|
|
75
|
+
mfa_required: true;
|
|
76
|
+
mfa_token: string;
|
|
77
|
+
}
|
|
78
|
+
/** The two possible outcomes of a sign-in attempt. */
|
|
79
|
+
type SignInResult = {
|
|
80
|
+
status: "signed_in";
|
|
81
|
+
session: AuthSession;
|
|
82
|
+
} | {
|
|
83
|
+
status: "mfa_required";
|
|
84
|
+
mfaToken: string;
|
|
85
|
+
};
|
|
86
|
+
/** Persisted session shape (what a `TokenStorage` holds). */
|
|
87
|
+
interface StoredSession {
|
|
88
|
+
id_token: string;
|
|
89
|
+
refresh_token: string;
|
|
90
|
+
expires_at: number;
|
|
91
|
+
user: AuthUser | null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** AuthClient — the browser-side identity client for `/v1/auth/{instance}`.
|
|
95
|
+
*
|
|
96
|
+
* This is the piece that lets a client-side app talk to altengine with **no
|
|
97
|
+
* backend of its own**: the end user signs in here, and the resulting `id_token`
|
|
98
|
+
* is what Datastore/Channel requests carry. Access rules on the auth instance
|
|
99
|
+
* decide what that user may read and write.
|
|
100
|
+
*
|
|
101
|
+
* Deliberately self-contained and API-key-free (like `ChannelSocket`) so it is
|
|
102
|
+
* safe to ship to a browser — see the `@altenginenet/sdk/auth` subpath export.
|
|
103
|
+
*
|
|
104
|
+
* ```ts
|
|
105
|
+
* import { AuthClient } from "@altenginenet/sdk/auth";
|
|
106
|
+
* import { AltEngine } from "@altenginenet/sdk";
|
|
107
|
+
*
|
|
108
|
+
* const auth = new AuthClient({ instance: "myapp-auth" });
|
|
109
|
+
* await auth.signIn("alice@example.com", "hunter2");
|
|
110
|
+
*
|
|
111
|
+
* // Hand the client to the SDK: every request now carries the user's token.
|
|
112
|
+
* const ae = new AltEngine({ auth });
|
|
113
|
+
* const { documents } = await ae.datastore("myapp").query("posts", { limit: 20 });
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
|
|
117
|
+
interface AuthClientOptions {
|
|
118
|
+
/** The auth instance name, e.g. "myapp-auth". */
|
|
119
|
+
instance: string;
|
|
120
|
+
/** API origin override. Resolution order: this → `dev: true` → production. */
|
|
121
|
+
baseUrl?: string;
|
|
122
|
+
/** Target the local emulator (`altengine dev`) at `http://127.0.0.1:9191`. */
|
|
123
|
+
dev?: boolean;
|
|
124
|
+
/** Where to persist the session (default: `localStorage`, else in-memory).
|
|
125
|
+
* Pass `memoryStorage()` to keep the session out of storage entirely. */
|
|
126
|
+
storage?: TokenStorage;
|
|
127
|
+
/** Storage key prefix, so several apps/instances can share one origin.
|
|
128
|
+
* Defaults to `altengine.auth.<instance>`. */
|
|
129
|
+
storageKey?: string;
|
|
130
|
+
/** Custom fetch (tests, polyfills). Defaults to `globalThis.fetch`. */
|
|
131
|
+
fetch?: typeof globalThis.fetch;
|
|
132
|
+
/** Refresh the id_token this many seconds before it expires (default 30). */
|
|
133
|
+
refreshSkewSeconds?: number;
|
|
134
|
+
}
|
|
135
|
+
type Listener = (user: AuthUser | null) => void;
|
|
136
|
+
declare class AuthClient {
|
|
137
|
+
readonly instance: string;
|
|
138
|
+
readonly baseUrl: string;
|
|
139
|
+
private readonly base;
|
|
140
|
+
private readonly storage;
|
|
141
|
+
private readonly key;
|
|
142
|
+
private readonly fetchImpl;
|
|
143
|
+
private readonly skew;
|
|
144
|
+
private readonly listeners;
|
|
145
|
+
private session;
|
|
146
|
+
/** In-flight refresh, so concurrent requests share one round trip. */
|
|
147
|
+
private refreshing;
|
|
148
|
+
constructor(opts: AuthClientOptions);
|
|
149
|
+
/** The signed-in user, or null. Reads persisted state, so it survives reloads. */
|
|
150
|
+
get user(): AuthUser | null;
|
|
151
|
+
get isSignedIn(): boolean;
|
|
152
|
+
/** Subscribe to sign-in/sign-out. Returns an unsubscribe function. */
|
|
153
|
+
onChange(fn: Listener): () => void;
|
|
154
|
+
private emit;
|
|
155
|
+
private load;
|
|
156
|
+
private save;
|
|
157
|
+
private adopt;
|
|
158
|
+
private call;
|
|
159
|
+
/** The instance's public sign-in configuration — which fields the sign-up form
|
|
160
|
+
* collects, which one is the login identity, and which methods are enabled.
|
|
161
|
+
* Fetch this to render a sign-in UI that matches the instance's settings. */
|
|
162
|
+
config(): Promise<AuthConfig>;
|
|
163
|
+
/** Create an account. Pass the configured sign-up fields plus `password`,
|
|
164
|
+
* e.g. `{ email, name, password }`. Signs the new user in. */
|
|
165
|
+
signUp(fields: Record<string, unknown>): Promise<AuthSession>;
|
|
166
|
+
/** Sign in with the identity field + password. When the account has two-factor
|
|
167
|
+
* enabled this resolves to `{ status: "mfa_required" }` and you must call
|
|
168
|
+
* {@link verifyMfa} with the code — no tokens are issued until then. */
|
|
169
|
+
signIn(identifier: string, password: string): Promise<SignInResult>;
|
|
170
|
+
/** Complete a two-factor challenge from {@link signIn} or {@link passwordlessVerify}. */
|
|
171
|
+
verifyMfa(mfaToken: string, code: string): Promise<AuthSession>;
|
|
172
|
+
/** Start passwordless sign-in: emails a one-time code. Always resolves — the
|
|
173
|
+
* server never reveals whether the account exists. */
|
|
174
|
+
passwordlessStart(identifier: string): Promise<void>;
|
|
175
|
+
/** Finish passwordless sign-in with the emailed code. */
|
|
176
|
+
passwordlessVerify(identifier: string, code: string): Promise<SignInResult>;
|
|
177
|
+
/** Start a password reset: emails a one-time code. Always resolves. */
|
|
178
|
+
passwordResetStart(identifier: string): Promise<void>;
|
|
179
|
+
/** Finish a password reset with the emailed code and a new password. */
|
|
180
|
+
passwordResetVerify(identifier: string, code: string, password: string): Promise<void>;
|
|
181
|
+
/** The signed-in user, re-read from the server (picks up claim changes). */
|
|
182
|
+
me(): Promise<AuthUser>;
|
|
183
|
+
/** Revoke the refresh token server-side and clear local state. Always clears
|
|
184
|
+
* locally, even if the network call fails. */
|
|
185
|
+
signOut(): Promise<void>;
|
|
186
|
+
/** Force a refresh-token rotation and return the new id_token. */
|
|
187
|
+
refresh(): Promise<string>;
|
|
188
|
+
/**
|
|
189
|
+
* The current id_token, refreshed first if it is expired or about to be.
|
|
190
|
+
* Returns `undefined` when nobody is signed in. This is the `TokenProvider`
|
|
191
|
+
* the SDK calls before every Datastore/Search/Channel request — pass the
|
|
192
|
+
* client as `new AltEngine({ auth })` and tokens stay fresh automatically.
|
|
193
|
+
*
|
|
194
|
+
* Concurrent callers share a single refresh. If the refresh fails because the
|
|
195
|
+
* session is truly gone (401/403), local state is cleared so the app can react
|
|
196
|
+
* via {@link onChange} instead of retrying forever.
|
|
197
|
+
*/
|
|
198
|
+
getToken(): Promise<string | undefined>;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export { AuthClient as A, type MfaChallenge as M, type SignInResult as S, type TokenStorage as T, type AuthClientOptions as a, type AuthConfig as b, type AuthField as c, type AuthSession as d, type AuthTokens as e, type AuthUser as f, type StoredSession as g, defaultStorage as h, memoryStorage as m };
|