@ghostdagger/ghostlink-server 0.1.0-beta.1 → 0.1.0-beta.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ghostdagger/ghostlink-server
2
2
 
3
- Node 24 authentication verification, Web handlers, Node HTTP adapter and durable SQLite sessions for Ghostlink.
3
+ Node 24 authentication verification, Web handlers, Node HTTP adapter and durable SQLite or Postgres/Neon sessions for Ghostlink.
4
4
 
5
5
  ```ts
6
6
  import { createGhostlinkServer, createSqliteStorage, createNodeHandler } from '@ghostdagger/ghostlink-server';
@@ -17,6 +17,30 @@ const auth = createGhostlinkServer({
17
17
 
18
18
  Mount `/auth/ghostlink/{session,challenge,verify,logout}` on the same origin. The Node adapter validates Host and uses the socket peer for rate limits. Reverse proxies must preserve the trusted host. `getSession` supplies identity, not application authorization or CSRF protection for your own mutations.
19
19
 
20
+ ## Postgres / Neon
21
+
22
+ Supply a `pg.Pool` or `@neondatabase/serverless.Pool` connected to a writable primary. Install your chosen driver separately. The adapter owns neither the driver nor the pool. Use separate entry points to avoid importing SQLite:
23
+
24
+ ```ts
25
+ import { Pool } from '@neondatabase/serverless'; // Or 'pg'
26
+ import { createGhostlinkServer } from '@ghostdagger/ghostlink-server/server';
27
+ import { createPostgresStorage, migratePostgresStorage } from '@ghostdagger/ghostlink-server/postgres';
28
+
29
+ const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 3 });
30
+ // Run in a deployment migration step, before traffic (not on every request):
31
+ await migratePostgresStorage(pool, { schema: 'ghostlink' });
32
+ const storage = createPostgresStorage(pool, { schema: 'ghostlink' });
33
+ const auth = createGhostlinkServer({
34
+ origin: 'https://app.example', loginUri: 'https://app.example/login',
35
+ networks: ['testnet-11'], storage,
36
+ });
37
+ // Shutdown after active requests: await pool.end(); storage has no close().
38
+ ```
39
+
40
+ The versioned migration is idempotent and serialized across clients. Use a separate schema/database per application and environment, TLS, server-only credentials, and a bounded pool. READ COMMITTED transactions and browser-row locks coordinate challenge replacement, single-use verification, rotation, and logout across server instances. Session activity and rate limits update atomically. Failures do not grant access or automatically retry an uncertain login commit. Read replicas and the HTTP-only Neon `neon()` function are not supported.
41
+
42
+ See the [Postgres guide](https://github.com/ghostdagger-labs/ghostlink/blob/main/docs/integration/postgres.md) and [complete Next.js/Vercel + Neon example](https://github.com/ghostdagger-labs/ghostlink/tree/main/examples/vercel-neon) for migrations, permissions, pool lifecycle, WASM packaging, environment setup, and testing. The Postgres adapter and dedicated entry points are included starting with `0.1.0-beta.2`. Existing SQLite root imports remain supported, with an additional `/sqlite` entry point.
43
+
20
44
  Defaults: five-minute browser-bound single-use challenges, official Kaspa Schnorr/address checks, 24-hour absolute / 30-minute idle sessions, hashed opaque tokens, HttpOnly/Secure/SameSite=Lax host cookies, CSRF, origin checks, 16-KiB body limit, and persistent rate limits. HTTP requires explicit `allowInsecureLocalhost: true` and a loopback origin. No edge-runtime support.
21
45
 
22
46
  Only standard Schnorr public-key addresses are accepted. Keys can be extracted from those addresses for manual Kaspium login. Server verification prevents replay and enforces the intended message/account/network, but generic message signing is not phishing-resistant. The profile is proposed; no CACAO interoperability or independent audit is claimed.
@@ -0,0 +1,138 @@
1
+ // src/postgres.ts
2
+ function namespace(options) {
3
+ const schema = options.schema ?? "ghostlink";
4
+ if (!/^[a-z_][a-z0-9_]{0,62}$/.test(schema) || schema === "public" || schema.startsWith("pg_") || schema === "information_schema") {
5
+ throw new Error("Use a dedicated lowercase Postgres schema name (at most 63 characters).");
6
+ }
7
+ return `"${schema}"`;
8
+ }
9
+ async function connection(pool, work) {
10
+ const client = await pool.connect();
11
+ try {
12
+ return await work(client);
13
+ } finally {
14
+ client.release();
15
+ }
16
+ }
17
+ async function transaction(pool, work) {
18
+ const client = await pool.connect();
19
+ let destroy = false;
20
+ try {
21
+ await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
22
+ const result = await work(client);
23
+ await client.query("COMMIT");
24
+ return result;
25
+ } catch (error) {
26
+ try {
27
+ await client.query("ROLLBACK");
28
+ } catch {
29
+ destroy = true;
30
+ }
31
+ throw error;
32
+ } finally {
33
+ client.release(destroy);
34
+ }
35
+ }
36
+ async function migratePostgresStorage(pool, options = {}) {
37
+ const ns = namespace(options);
38
+ await transaction(pool, async (client) => {
39
+ await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", [`ghostlink:migrate:${ns}`]);
40
+ await client.query(`CREATE SCHEMA IF NOT EXISTS ${ns}`);
41
+ await client.query(`CREATE TABLE IF NOT EXISTS ${ns}.schema_version (singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton), version INTEGER NOT NULL)`);
42
+ const version = (await client.query(`SELECT version FROM ${ns}.schema_version WHERE singleton=TRUE`)).rows[0]?.version;
43
+ if (version !== void 0 && version !== 1) throw new Error("Unsupported Ghostlink Postgres storage schema.");
44
+ if (version === 1) return;
45
+ await client.query(`
46
+ CREATE TABLE ${ns}.browsers (hash TEXT PRIMARY KEY, csrf TEXT NOT NULL, expires BIGINT NOT NULL);
47
+ CREATE INDEX ON ${ns}.browsers (expires);
48
+ CREATE TABLE ${ns}.challenges (
49
+ id TEXT PRIMARY KEY, browser TEXT NOT NULL UNIQUE REFERENCES ${ns}.browsers(hash) ON DELETE CASCADE,
50
+ expires BIGINT NOT NULL, data JSONB NOT NULL
51
+ );
52
+ CREATE INDEX ON ${ns}.challenges (expires);
53
+ CREATE TABLE ${ns}.sessions (
54
+ hash TEXT PRIMARY KEY, browser TEXT NOT NULL UNIQUE REFERENCES ${ns}.browsers(hash) ON DELETE CASCADE,
55
+ expires BIGINT NOT NULL, last_seen BIGINT NOT NULL, data JSONB NOT NULL, receipt JSONB NOT NULL
56
+ );
57
+ CREATE INDEX ON ${ns}.sessions (expires);
58
+ CREATE TABLE ${ns}.limits (key TEXT PRIMARY KEY, expires BIGINT NOT NULL, count BIGINT NOT NULL);
59
+ CREATE INDEX ON ${ns}.limits (expires);
60
+ INSERT INTO ${ns}.schema_version (version) VALUES (1);
61
+ `);
62
+ });
63
+ }
64
+ function createPostgresStorage(pool, options = {}) {
65
+ const ns = namespace(options);
66
+ const query = (sql, values) => connection(pool, (client) => client.query(sql, values));
67
+ const lockBrowser = async (client, hash) => (await client.query(`SELECT expires FROM ${ns}.browsers WHERE hash=$1 FOR UPDATE`, [hash])).rows[0];
68
+ return {
69
+ async getBrowser(hash, now) {
70
+ const row = (await query(`SELECT hash, csrf, expires FROM ${ns}.browsers WHERE hash=$1 AND expires>$2`, [hash, now])).rows[0];
71
+ return row ? { hash: row.hash, csrf: row.csrf, expiresAt: Number(row.expires) } : null;
72
+ },
73
+ async putBrowser(browser) {
74
+ await query(`INSERT INTO ${ns}.browsers (hash, csrf, expires) VALUES ($1, $2, $3)`, [browser.hash, browser.csrf, browser.expiresAt]);
75
+ },
76
+ async putChallenge(challenge) {
77
+ await transaction(pool, async (client) => {
78
+ if (!await lockBrowser(client, challenge.browserHash)) throw new Error("Unknown Ghostlink browser.");
79
+ await client.query(`DELETE FROM ${ns}.challenges WHERE browser=$1`, [challenge.browserHash]);
80
+ await client.query(
81
+ `INSERT INTO ${ns}.challenges (id, browser, expires, data) VALUES ($1, $2, $3, $4::jsonb)`,
82
+ [challenge.id, challenge.browserHash, Date.parse(challenge.expiresAt), JSON.stringify(challenge)]
83
+ );
84
+ });
85
+ },
86
+ async getChallenge(id, browserHash) {
87
+ const row = (await query(`SELECT data FROM ${ns}.challenges WHERE id=$1 AND browser=$2`, [id, browserHash])).rows[0];
88
+ return row ? row.data : null;
89
+ },
90
+ async commitLogin(id, browserHash, now, record) {
91
+ return transaction(pool, async (client) => {
92
+ const browser = await lockBrowser(client, browserHash);
93
+ if (!browser || Number(browser.expires) <= now || record.browserHash !== browserHash) return false;
94
+ const consumed = await client.query(`DELETE FROM ${ns}.challenges WHERE id=$1 AND browser=$2 AND expires>$3 RETURNING id`, [id, browserHash, now]);
95
+ if (!consumed.rows.length) return false;
96
+ await client.query(`DELETE FROM ${ns}.sessions WHERE browser=$1`, [browserHash]);
97
+ await client.query(
98
+ `INSERT INTO ${ns}.sessions (hash, browser, expires, last_seen, data, receipt) VALUES ($1, $2, $3, $4, $5::jsonb, $6::jsonb)`,
99
+ [record.hash, browserHash, Date.parse(record.session.expiresAt), record.lastSeen, JSON.stringify(record.session), JSON.stringify(record.receipt)]
100
+ );
101
+ return true;
102
+ });
103
+ },
104
+ async getSession(hash, browserHash, now, idleMs) {
105
+ const row = (await query(`UPDATE ${ns}.sessions SET last_seen=GREATEST(last_seen, $3)
106
+ WHERE hash=$1 AND browser=$2 AND expires>$3 AND last_seen>$3::bigint-$4::bigint
107
+ AND EXISTS (SELECT 1 FROM ${ns}.browsers WHERE hash=$2 AND expires>$3)
108
+ RETURNING data, expires, last_seen`, [hash, browserHash, now, idleMs])).rows[0];
109
+ return row ? { ...row.data, idleExpiresAt: new Date(Math.min(Number(row.expires), Number(row.last_seen) + idleMs)).toISOString() } : null;
110
+ },
111
+ async revokeBrowser(browserHash) {
112
+ await transaction(pool, async (client) => {
113
+ if (!await lockBrowser(client, browserHash)) return;
114
+ await client.query(`DELETE FROM ${ns}.challenges WHERE browser=$1`, [browserHash]);
115
+ await client.query(`DELETE FROM ${ns}.sessions WHERE browser=$1`, [browserHash]);
116
+ });
117
+ },
118
+ async consumeRateLimit(key, now, windowMs, maximum) {
119
+ const row = (await query(`INSERT INTO ${ns}.limits AS limits (key, expires, count) VALUES ($1, $2, 1)
120
+ ON CONFLICT (key) DO UPDATE SET
121
+ count=CASE WHEN limits.expires<=$3 THEN 1 ELSE limits.count+1 END,
122
+ expires=CASE WHEN limits.expires<=$3 THEN EXCLUDED.expires ELSE limits.expires END
123
+ RETURNING count`, [key, now + windowMs, now])).rows[0];
124
+ return Number(row.count) <= maximum;
125
+ },
126
+ async prune(now) {
127
+ await query(`DELETE FROM ${ns}.browsers WHERE expires<=$1`, [now]);
128
+ await query(`DELETE FROM ${ns}.challenges WHERE expires<=$1`, [now]);
129
+ await query(`DELETE FROM ${ns}.sessions WHERE expires<=$1`, [now]);
130
+ await query(`DELETE FROM ${ns}.limits WHERE expires<=$1`, [now]);
131
+ }
132
+ };
133
+ }
134
+
135
+ export {
136
+ migratePostgresStorage,
137
+ createPostgresStorage
138
+ };
@@ -0,0 +1,203 @@
1
+ // src/server.ts
2
+ import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
3
+ import { PROFILE, NETWORKS, serializeLoginMessage, isNetwork, chainId, GhostlinkError as GhostlinkError2 } from "@ghostdagger/ghostlink-core";
4
+
5
+ // src/crypto.ts
6
+ import { createRequire } from "node:module";
7
+ import { addressPrefix, accountId, GhostlinkError } from "@ghostdagger/ghostlink-core";
8
+ var require2 = createRequire(import.meta.url);
9
+ var kaspa = require2("../vendor/kaspa/kaspa.js");
10
+ function validateKaspaAddress(value, network) {
11
+ let address;
12
+ let key;
13
+ try {
14
+ if (!kaspa.Address.validate(value)) throw new GhostlinkError("INVALID_REQUEST", "The address checksum is invalid. Copy the full receiving address directly from your wallet.");
15
+ address = new kaspa.Address(value);
16
+ if (address.prefix !== addressPrefix(network) || address.toString() !== value) throw new GhostlinkError("INVALID_REQUEST", "The address does not match the selected network or canonical address format.");
17
+ if (address.version !== "PubKey") throw new GhostlinkError("INVALID_REQUEST", "This address type is not supported. Use a standard Schnorr public-key address.");
18
+ key = kaspa.XOnlyPublicKey.fromAddress(address);
19
+ return { address: value, accountId: accountId(value, network), publicKey: key.toString() };
20
+ } catch (error) {
21
+ if (error instanceof GhostlinkError) throw error;
22
+ throw new GhostlinkError("INVALID_REQUEST", "Enter a valid Schnorr public-key address for the selected network.");
23
+ } finally {
24
+ key?.free();
25
+ address?.free();
26
+ }
27
+ }
28
+ function verifyKaspaSignature(input) {
29
+ let publicKey;
30
+ let derived;
31
+ try {
32
+ const account = validateKaspaAddress(input.address, input.network);
33
+ if (!/^[a-f0-9]{128}$/.test(input.signature)) return false;
34
+ publicKey = new kaspa.PublicKey(input.publicKey ?? account.publicKey);
35
+ derived = publicKey.toAddress(input.network);
36
+ if (derived.toString() !== input.address) return false;
37
+ return kaspa.verifyMessage({ message: input.message, signature: input.signature, publicKey });
38
+ } catch {
39
+ return false;
40
+ } finally {
41
+ derived?.free();
42
+ publicKey?.free();
43
+ }
44
+ }
45
+
46
+ // src/server.ts
47
+ var token = () => randomBytes(32).toString("hex");
48
+ var hash = (value) => createHash("sha256").update(value).digest("hex");
49
+ var equal = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
50
+ var hexToken = (s) => typeof s === "string" && /^[a-f0-9]{64}$/.test(s);
51
+ function cookies(request) {
52
+ const result = /* @__PURE__ */ Object.create(null);
53
+ for (const part of (request.headers.get("cookie") ?? "").split(";")) {
54
+ const i = part.indexOf("=");
55
+ if (i < 0) continue;
56
+ const name = part.slice(0, i).trim();
57
+ result[name] = name in result ? "" : part.slice(i + 1).trim();
58
+ }
59
+ return result;
60
+ }
61
+ async function boundedJson(request) {
62
+ if (!/^application\/json(?:\s*;|$)/i.test(request.headers.get("content-type") ?? "")) throw new GhostlinkError2("INVALID_REQUEST", "Expected application/json.");
63
+ if (Number(request.headers.get("content-length") ?? 0) > 16384) throw new GhostlinkError2("INVALID_REQUEST", "Request is too large.");
64
+ const reader = request.body?.getReader();
65
+ if (!reader) throw new GhostlinkError2("INVALID_REQUEST", "Missing request body.");
66
+ let bytes = 0;
67
+ const parts = [];
68
+ while (true) {
69
+ const next = await reader.read();
70
+ if (next.done) break;
71
+ bytes += next.value.length;
72
+ if (bytes > 16384) {
73
+ await reader.cancel();
74
+ throw new GhostlinkError2("INVALID_REQUEST", "Request is too large.");
75
+ }
76
+ parts.push(next.value);
77
+ }
78
+ try {
79
+ const value = JSON.parse(Buffer.concat(parts).toString("utf8"));
80
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
81
+ return value;
82
+ } catch {
83
+ throw new GhostlinkError2("INVALID_REQUEST", "Invalid JSON request.");
84
+ }
85
+ }
86
+ function createGhostlinkServer(config) {
87
+ const origin = new URL(config.origin);
88
+ const uri = new URL(config.loginUri);
89
+ if (origin.origin !== config.origin || uri.origin !== origin.origin || uri.username || uri.password || uri.hash) throw new Error("Configure an exact trusted origin and a same-origin login URI.");
90
+ const insecure = origin.protocol === "http:" && !!config.allowInsecureLocalhost && ["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname);
91
+ if (origin.protocol !== "https:" && !insecure) throw new Error("HTTPS is required except for explicitly configured loopback development.");
92
+ const prefix = config.prefix ?? "/auth/ghostlink";
93
+ if (!/^\/[a-zA-Z0-9/_-]+$/.test(prefix) || prefix.endsWith("/")) throw new Error("Invalid authentication path prefix.");
94
+ const store = config.storage;
95
+ const now = config.now ?? Date.now;
96
+ const challengeTtl = config.challengeTtlMs ?? 3e5;
97
+ const sessionTtl = config.sessionTtlMs ?? 864e5;
98
+ const idleTtl = config.idleTtlMs ?? 18e5;
99
+ const skew = config.clockSkewMs ?? 3e4;
100
+ for (const v of [challengeTtl, sessionTtl, idleTtl]) if (!Number.isSafeInteger(v) || v <= 0) throw new Error("Session and challenge durations must be positive integers.");
101
+ if (challengeTtl > 3e5 || !Number.isSafeInteger(skew) || skew < 0 || skew > 3e4) throw new Error("Challenge duration or clock skew exceeds the profile limit.");
102
+ const networks = config.networks ?? NETWORKS;
103
+ if (!networks.length || networks.some((n) => !isNetwork(n))) throw new Error("Configure supported Kaspa networks.");
104
+ const browserName = insecure ? "ghostlink-browser" : "__Host-ghostlink-browser";
105
+ const sessionName = insecure ? "ghostlink-session" : "__Host-ghostlink-session";
106
+ const browserTtl = Math.max(6048e5, sessionTtl);
107
+ function cookie(name, value, maxAge) {
108
+ return `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(maxAge / 1e3)}${insecure ? "" : "; Secure"}`;
109
+ }
110
+ function response(data, status = 200, setCookies = []) {
111
+ const headers = new Headers({ "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Vary": "Cookie, Origin" });
112
+ for (const c of setCookies) headers.append("Set-Cookie", c);
113
+ return new Response(JSON.stringify(data), { status, headers });
114
+ }
115
+ function checkOrigin(request) {
116
+ if (new URL(request.url).origin !== origin.origin || request.headers.get("sec-fetch-site") === "cross-site") throw new GhostlinkError2("INVALID_REQUEST", "Untrusted request origin.");
117
+ const supplied = request.headers.get("origin");
118
+ if (supplied !== null && supplied !== origin.origin || request.method !== "GET" && supplied !== origin.origin) throw new GhostlinkError2("INVALID_REQUEST", "Untrusted request origin.");
119
+ }
120
+ async function browserFor(request) {
121
+ const value = cookies(request)[browserName];
122
+ return hexToken(value) ? store.getBrowser(hash(value), now()) : null;
123
+ }
124
+ async function getSession(request) {
125
+ const b = await browserFor(request);
126
+ const value = cookies(request)[sessionName];
127
+ if (!b || !hexToken(value)) return null;
128
+ return store.getSession(hash(value), b.hash, now(), idleTtl);
129
+ }
130
+ async function handle(request, context = {}) {
131
+ try {
132
+ checkOrigin(request);
133
+ const path = new URL(request.url).pathname;
134
+ if (!path.startsWith(`${prefix}/`)) return response({ error: "Not found." }, 404);
135
+ const endpoint = path.slice(prefix.length);
136
+ if (!["/session", "/challenge", "/verify", "/logout"].includes(endpoint)) return response({ error: "Not found." }, 404);
137
+ if (endpoint === "/session" && request.method !== "GET" || endpoint !== "/session" && request.method !== "POST") return response({ error: "Method not allowed." }, 405);
138
+ const time = now();
139
+ if (!await store.consumeRateLimit(`peer:${hash(context.ip ?? "shared")}`, time, 6e4, 180)) return response({ code: "SERVER_ERROR", error: "Too many requests. Wait a minute and try again." }, 429);
140
+ await store.prune(time);
141
+ let browser = await browserFor(request);
142
+ if (endpoint === "/session") {
143
+ const setCookies = [];
144
+ if (!browser) {
145
+ const value2 = token();
146
+ browser = { hash: hash(value2), csrf: token(), expiresAt: time + browserTtl };
147
+ await store.putBrowser(browser);
148
+ setCookies.push(cookie(browserName, value2, browserTtl));
149
+ }
150
+ const session2 = await getSession(request);
151
+ return response({ session: session2, csrfToken: browser.csrf }, 200, setCookies);
152
+ }
153
+ const csrf = request.headers.get("x-ghostlink-csrf") ?? "";
154
+ if (!browser || !hexToken(csrf) || !equal(csrf, browser.csrf)) return response({ code: "UNAUTHENTICATED", error: "Reload this application before signing in." }, 403);
155
+ if (!await store.consumeRateLimit(`browser:${browser.hash}`, time, 6e4, 30)) return response({ code: "SERVER_ERROR", error: "Too many requests. Wait a minute and try again." }, 429);
156
+ const body = await boundedJson(request);
157
+ if (endpoint === "/logout") {
158
+ await store.revokeBrowser(browser.hash);
159
+ return response({ ok: true }, 200, [cookie(sessionName, "", 0)]);
160
+ }
161
+ if (endpoint === "/challenge") {
162
+ if (!isNetwork(body.network) || !networks.includes(body.network) || typeof body.address !== "string") throw new GhostlinkError2("INVALID_REQUEST", "Unsupported account or network.");
163
+ const a = validateKaspaAddress(body.address, body.network);
164
+ const expiresAt = new Date(time + challengeTtl).toISOString();
165
+ const message = serializeLoginMessage({ domain: origin.host, address: a.address, network: body.network, uri: uri.href, nonce: token(), issuedAt: new Date(time).toISOString(), expiresAt });
166
+ const record = { id: token(), profile: PROFILE, message, address: a.address, network: body.network, expiresAt, issuedAt: time, browserHash: browser.hash };
167
+ await store.putChallenge(record);
168
+ const { browserHash: _browser, issuedAt: _issued, ...challenge2 } = record;
169
+ return response(challenge2);
170
+ }
171
+ if (!hexToken(body.challengeId) || typeof body.message !== "string" || body.message.length > 2e3 || typeof body.signature !== "string" || !/^[a-f0-9]{128}$/.test(body.signature) || body.publicKey !== void 0 && (typeof body.publicKey !== "string" || !/^(?:[a-fA-F0-9]{64}|0[23][a-fA-F0-9]{64})$/.test(body.publicKey))) throw new GhostlinkError2("INVALID_REQUEST", "Invalid verification request.");
172
+ const challenge = await store.getChallenge(body.challengeId, browser.hash);
173
+ if (!challenge || Date.parse(challenge.expiresAt) <= time || challenge.issuedAt > time + skew) throw new GhostlinkError2("EXPIRED", "The challenge expired or was already used. Generate a new message.");
174
+ if (body.message !== challenge.message || !networks.includes(challenge.network)) throw new GhostlinkError2("INVALID_SIGNATURE", "The signed message does not match this login request.");
175
+ if (!verifyKaspaSignature({ address: challenge.address, network: challenge.network, message: challenge.message, signature: body.signature, publicKey: body.publicKey })) throw new GhostlinkError2("INVALID_SIGNATURE", "The signature does not match the signing address and message.");
176
+ const verifiedTime = now();
177
+ const value = token();
178
+ const session = { accountId: validateKaspaAddress(challenge.address, challenge.network).accountId, address: challenge.address, network: challenge.network, chainId: chainId(challenge.network), issuedAt: new Date(verifiedTime).toISOString(), expiresAt: new Date(verifiedTime + sessionTtl).toISOString(), idleExpiresAt: new Date(verifiedTime + Math.min(idleTtl, sessionTtl)).toISOString() };
179
+ const committed = await store.commitLogin(challenge.id, browser.hash, verifiedTime, { hash: hash(value), browserHash: browser.hash, lastSeen: verifiedTime, session, receipt: { profile: PROFILE, message: challenge.message, signature: body.signature, publicKey: body.publicKey } });
180
+ if (!committed) throw new GhostlinkError2("EXPIRED", "The challenge expired or was already used. Generate a new message.");
181
+ return response(session, 200, [cookie(sessionName, value, sessionTtl)]);
182
+ } catch (error) {
183
+ if (error instanceof GhostlinkError2) return response({ code: error.code, error: error.message }, error.code === "INVALID_REQUEST" ? 400 : 401);
184
+ return response({ code: "SERVER_ERROR", error: "The authentication service could not complete this request." }, 500);
185
+ }
186
+ }
187
+ return {
188
+ /** Handle session/challenge/verify/logout Web requests under prefix. Pass trusted peer metadata for rate limits; returns HTTP failures as Responses. */
189
+ handle,
190
+ /** Read identity from request cookies, returning null if missing/expired. Refreshes idle expiry. Does not enforce application authorization, origin checks, or CSRF for your own routes. */
191
+ getSession,
192
+ /** Validated public origin used for audience and Host checks. */
193
+ origin: origin.origin,
194
+ /** Authentication route prefix; mount these routes on the same origin as the browser app. */
195
+ prefix
196
+ };
197
+ }
198
+
199
+ export {
200
+ validateKaspaAddress,
201
+ verifyKaspaSignature,
202
+ createGhostlinkServer
203
+ };
@@ -0,0 +1,100 @@
1
+ // src/sqlite.ts
2
+ import { DatabaseSync } from "node:sqlite";
3
+ import { mkdirSync, chmodSync } from "node:fs";
4
+ import { dirname } from "node:path";
5
+ function createSqliteStorage(filename) {
6
+ if (filename !== ":memory:") mkdirSync(dirname(filename), { recursive: true, mode: 448 });
7
+ const db = new DatabaseSync(filename);
8
+ if (filename !== ":memory:") chmodSync(filename, 384);
9
+ db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;");
10
+ const version = db.prepare("PRAGMA user_version").get().user_version;
11
+ if (version > 1) {
12
+ db.close();
13
+ throw new Error("Unsupported Ghostlink storage schema.");
14
+ }
15
+ db.exec(`
16
+ CREATE TABLE IF NOT EXISTS browsers (hash TEXT PRIMARY KEY, csrf TEXT NOT NULL, expires INTEGER NOT NULL);
17
+ CREATE TABLE IF NOT EXISTS challenges (id TEXT PRIMARY KEY, browser TEXT NOT NULL REFERENCES browsers(hash) ON DELETE CASCADE, expires INTEGER NOT NULL, data TEXT NOT NULL);
18
+ CREATE INDEX IF NOT EXISTS challenges_browser ON challenges(browser);
19
+ CREATE TABLE IF NOT EXISTS sessions (hash TEXT PRIMARY KEY, browser TEXT NOT NULL REFERENCES browsers(hash) ON DELETE CASCADE, expires INTEGER NOT NULL, last_seen INTEGER NOT NULL, data TEXT NOT NULL, receipt TEXT NOT NULL);
20
+ CREATE INDEX IF NOT EXISTS sessions_browser ON sessions(browser);
21
+ CREATE TABLE IF NOT EXISTS limits (key TEXT PRIMARY KEY, expires INTEGER NOT NULL, count INTEGER NOT NULL);
22
+ PRAGMA user_version=1;
23
+ `);
24
+ function transaction(work) {
25
+ db.exec("BEGIN IMMEDIATE");
26
+ try {
27
+ const result = work();
28
+ db.exec("COMMIT");
29
+ return result;
30
+ } catch (e) {
31
+ db.exec("ROLLBACK");
32
+ throw e;
33
+ }
34
+ }
35
+ return {
36
+ async getBrowser(hash, now) {
37
+ const r = db.prepare("SELECT hash, csrf, expires AS expiresAt FROM browsers WHERE hash=? AND expires>?").get(hash, now);
38
+ return r ? r : null;
39
+ },
40
+ async putBrowser(b) {
41
+ db.prepare("INSERT INTO browsers VALUES (?, ?, ?)").run(b.hash, b.csrf, b.expiresAt);
42
+ },
43
+ async putChallenge(c) {
44
+ transaction(() => {
45
+ db.prepare("DELETE FROM challenges WHERE browser=?").run(c.browserHash);
46
+ db.prepare("INSERT INTO challenges VALUES (?, ?, ?, ?)").run(c.id, c.browserHash, Date.parse(c.expiresAt), JSON.stringify(c));
47
+ });
48
+ },
49
+ async getChallenge(id, browserHash) {
50
+ const r = db.prepare("SELECT data FROM challenges WHERE id=? AND browser=?").get(id, browserHash);
51
+ return r ? JSON.parse(r.data) : null;
52
+ },
53
+ async commitLogin(id, browserHash, now, record) {
54
+ return transaction(() => {
55
+ const browser = db.prepare("SELECT hash FROM browsers WHERE hash=? AND expires>?").get(browserHash, now);
56
+ if (!browser) return false;
57
+ const consumed = db.prepare("DELETE FROM challenges WHERE id=? AND browser=? AND expires>? RETURNING id").get(id, browserHash, now);
58
+ if (!consumed) return false;
59
+ db.prepare("DELETE FROM sessions WHERE browser=?").run(browserHash);
60
+ db.prepare("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?)").run(record.hash, browserHash, Date.parse(record.session.expiresAt), record.lastSeen, JSON.stringify(record.session), JSON.stringify(record.receipt));
61
+ return true;
62
+ });
63
+ },
64
+ async getSession(hash, browserHash, now, idleMs) {
65
+ return transaction(() => {
66
+ const r = db.prepare("SELECT data, expires FROM sessions WHERE hash=? AND browser=? AND expires>? AND last_seen>?").get(hash, browserHash, now, now - idleMs);
67
+ if (!r) return null;
68
+ db.prepare("UPDATE sessions SET last_seen=? WHERE hash=?").run(now, hash);
69
+ return { ...JSON.parse(r.data), idleExpiresAt: new Date(Math.min(r.expires, now + idleMs)).toISOString() };
70
+ });
71
+ },
72
+ async revokeBrowser(hash) {
73
+ transaction(() => {
74
+ db.prepare("DELETE FROM challenges WHERE browser=?").run(hash);
75
+ db.prepare("DELETE FROM sessions WHERE browser=?").run(hash);
76
+ });
77
+ },
78
+ async consumeRateLimit(key, now, windowMs, maximum) {
79
+ return transaction(() => {
80
+ db.prepare("INSERT INTO limits VALUES (?, ?, 1) ON CONFLICT(key) DO UPDATE SET count=CASE WHEN expires<=? THEN 1 ELSE count+1 END, expires=CASE WHEN expires<=? THEN excluded.expires ELSE expires END").run(key, now + windowMs, now, now);
81
+ return Number(db.prepare("SELECT count FROM limits WHERE key=?").get(key).count) <= maximum;
82
+ });
83
+ },
84
+ async prune(now) {
85
+ transaction(() => {
86
+ db.prepare("DELETE FROM browsers WHERE expires<=?").run(now);
87
+ db.prepare("DELETE FROM challenges WHERE expires<=?").run(now);
88
+ db.prepare("DELETE FROM sessions WHERE expires<=?").run(now);
89
+ db.prepare("DELETE FROM limits WHERE expires<=?").run(now);
90
+ });
91
+ },
92
+ close() {
93
+ db.close();
94
+ }
95
+ };
96
+ }
97
+
98
+ export {
99
+ createSqliteStorage
100
+ };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,10 @@
1
- import { Network, AuthChallenge, AuthSession } from '@ghostdagger/ghostlink-core';
1
+ import { Network } from '@ghostdagger/ghostlink-core';
2
+ import { G as GhostlinkStorage } from './storage-BazI-SH0.js';
3
+ export { B as BrowserRecord, C as ChallengeRecord, S as SessionRecord } from './storage-BazI-SH0.js';
4
+ export { createSqliteStorage } from './sqlite.js';
5
+ export { PostgresConnection, PostgresPool, PostgresStorageOptions, createPostgresStorage, migratePostgresStorage } from './postgres.js';
6
+ import { createGhostlinkServer } from './server.js';
7
+ export { GhostlinkServerConfig, RequestContext } from './server.js';
2
8
  import { IncomingMessage, ServerResponse } from 'node:http';
3
9
 
4
10
  /** Validate a canonical Schnorr public-key address/checksum for the network with the official SDK. Returns identity and hex public key; throws INVALID_REQUEST for unsupported or invalid addresses. */
@@ -16,100 +22,10 @@ declare function verifyKaspaSignature(input: {
16
22
  publicKey?: string;
17
23
  }): boolean;
18
24
 
19
- interface BrowserRecord {
20
- hash: string;
21
- csrf: string;
22
- expiresAt: number;
23
- }
24
- interface ChallengeRecord extends AuthChallenge {
25
- browserHash: string;
26
- issuedAt: number;
27
- }
28
- interface SessionRecord {
29
- hash: string;
30
- browserHash: string;
31
- session: AuthSession;
32
- lastSeen: number;
33
- receipt: {
34
- profile: string;
35
- message: string;
36
- signature: string;
37
- publicKey?: string;
38
- };
39
- }
40
- /** All times are Unix milliseconds. commitLogin MUST atomically consume the challenge and create the session. */
41
- interface GhostlinkStorage {
42
- /** Look up an unexpired browser record by its hashed cookie token. */
43
- getBrowser(hash: string, now: number): Promise<BrowserRecord | null>;
44
- /** Persist the browser binding and CSRF token. */
45
- putBrowser(browser: BrowserRecord): Promise<void>;
46
- /** Store the new challenge, replacing outstanding challenges for the same browser. */
47
- putChallenge(challenge: ChallengeRecord): Promise<void>;
48
- /** Look up a challenge only within its bound browser. commitLogin must still enforce expiry. */
49
- getChallenge(id: string, browserHash: string): Promise<ChallengeRecord | null>;
50
- /** Atomically consume one unexpired challenge and replace the browser's session. Return false if already consumed, expired, or browser binding is invalid. */
51
- commitLogin(challengeId: string, browserHash: string, now: number, session: SessionRecord): Promise<boolean>;
52
- /** Return null for expired/wrong-browser sessions; otherwise refresh lastSeen and idleExpiresAt, capped by absolute expiry. All time arguments are milliseconds. */
53
- getSession(hash: string, browserHash: string, now: number, idleMs: number): Promise<AuthSession | null>;
54
- /** Revoke all sessions and outstanding challenges for this browser. */
55
- revokeBrowser(browserHash: string): Promise<void>;
56
- /** Atomically consume a request in the given millisecond window; false means the maximum was exceeded. */
57
- consumeRateLimit(key: string, now: number, windowMs: number, maximum: number): Promise<boolean>;
58
- /** Remove expired records. now is Unix milliseconds. */
59
- prune(now: number): Promise<void>;
60
- /** Optional synchronous shutdown. The storage creator owns calling this when no requests remain. */
61
- close?(): void;
62
- }
63
-
64
- /** Reusable behavioral checks for a new storage adapter. Run against an isolated, empty test database. */
65
- declare function assertStorageConformance(store: GhostlinkStorage): Promise<void>;
66
-
67
- /** Open a Node 24 SQLite store, creating parent directories and schema as needed. Use :memory: for isolated tests; otherwise persist this file. The caller must close the store on shutdown. */
68
- declare function createSqliteStorage(filename: string): GhostlinkStorage;
69
-
70
- /** Trusted authentication policy. Origin/network configuration must agree with the browser client. */
71
- interface GhostlinkServerConfig {
72
- /** Exact public HTTP(S) origin, including port when present; no path or trailing slash. */
73
- origin: string;
74
- /** Absolute same-origin URI included in login messages; no credentials or fragment. */
75
- loginUri: string;
76
- /** Persistence adapter. Its creator owns shutdown; use createSqliteStorage for the supplied Node backend. */
77
- storage: GhostlinkStorage;
78
- /** Nonempty allowed network list. Defaults to mainnet, testnet-10, and testnet-11. */
79
- networks?: readonly Network[];
80
- /** Authentication route prefix without a trailing slash. Defaults to /auth/ghostlink. */
81
- prefix?: string;
82
- /** Permit HTTP only for localhost/loopback development. Defaults to false; public origins require HTTPS. */
83
- allowInsecureLocalhost?: boolean;
84
- /** Challenge lifetime in milliseconds. Defaults to 300_000 (5 minutes); must be positive and at most 300_000. */
85
- challengeTtlMs?: number;
86
- /** Absolute session lifetime in milliseconds. Defaults to 86_400_000 (24 hours); must be a positive safe integer. */
87
- sessionTtlMs?: number;
88
- /** Idle session lifetime in milliseconds. Defaults to 1_800_000 (30 minutes); successful getSession calls refresh it, capped by absolute expiry. */
89
- idleTtlMs?: number;
90
- /** Future-issued challenge tolerance in milliseconds. Defaults to 30_000; allowed range is 0–30_000. */
91
- clockSkewMs?: number;
92
- /** Clock returning Unix milliseconds. Defaults to Date.now; override for deterministic tests. */
93
- now?: () => number;
94
- }
95
- /** Request metadata supplied by a trusted server adapter. */
96
- interface RequestContext {
97
- ip?: string;
98
- }
99
- /** Create Node authentication handlers with cookie sessions, CSRF checks, and signature verification. Validates policy immediately; does not start an HTTP listener or own storage shutdown. */
100
- declare function createGhostlinkServer(config: GhostlinkServerConfig): {
101
- /** Handle session/challenge/verify/logout Web requests under prefix. Pass trusted peer metadata for rate limits; returns HTTP failures as Responses. */
102
- handle: (request: Request, context?: RequestContext) => Promise<Response>;
103
- /** Read identity from request cookies, returning null if missing/expired. Refreshes idle expiry. Does not enforce application authorization, origin checks, or CSRF for your own routes. */
104
- getSession: (request: Request) => Promise<AuthSession | null>;
105
- /** Validated public origin used for audience and Host checks. */
106
- origin: string;
107
- /** Authentication route prefix; mount these routes on the same origin as the browser app. */
108
- prefix: string;
109
- };
25
+ /** Reusable behavioral checks against an isolated, empty test database. Supply a second adapter/connection to the same database to check cross-instance behavior. */
26
+ declare function assertStorageConformance(store: GhostlinkStorage, peer?: GhostlinkStorage): Promise<void>;
110
27
 
111
28
  /** Adapt Ghostlink Web handlers to Node HTTP. Mount under server.prefix; validates Host, limits bodies to 16 KiB, forwards cookies, and uses the socket peer for rate limits. Reverse proxies must preserve Host. */
112
29
  declare function createNodeHandler(server: ReturnType<typeof createGhostlinkServer>): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
113
30
 
114
- export { assertStorageConformance, createGhostlinkServer, createNodeHandler, createSqliteStorage, validateKaspaAddress, verifyKaspaSignature };
115
- export type { BrowserRecord, ChallengeRecord, GhostlinkServerConfig, GhostlinkStorage, RequestContext, SessionRecord };
31
+ export { GhostlinkStorage, assertStorageConformance, createGhostlinkServer, createNodeHandler, validateKaspaAddress, verifyKaspaSignature };
package/dist/index.js CHANGED
@@ -1,46 +1,18 @@
1
- // src/crypto.ts
2
- import { createRequire } from "node:module";
3
- import { addressPrefix, accountId, GhostlinkError } from "@ghostdagger/ghostlink-core";
4
- var require2 = createRequire(import.meta.url);
5
- var kaspa = require2("../vendor/kaspa/kaspa.js");
6
- function validateKaspaAddress(value, network) {
7
- let address;
8
- let key;
9
- try {
10
- if (!kaspa.Address.validate(value)) throw new GhostlinkError("INVALID_REQUEST", "The address checksum is invalid. Copy the full receiving address directly from your wallet.");
11
- address = new kaspa.Address(value);
12
- if (address.prefix !== addressPrefix(network) || address.toString() !== value) throw new GhostlinkError("INVALID_REQUEST", "The address does not match the selected network or canonical address format.");
13
- if (address.version !== "PubKey") throw new GhostlinkError("INVALID_REQUEST", "This address type is not supported. Use a standard Schnorr public-key address.");
14
- key = kaspa.XOnlyPublicKey.fromAddress(address);
15
- return { address: value, accountId: accountId(value, network), publicKey: key.toString() };
16
- } catch (error) {
17
- if (error instanceof GhostlinkError) throw error;
18
- throw new GhostlinkError("INVALID_REQUEST", "Enter a valid Schnorr public-key address for the selected network.");
19
- } finally {
20
- key?.free();
21
- address?.free();
22
- }
23
- }
24
- function verifyKaspaSignature(input) {
25
- let publicKey;
26
- let derived;
27
- try {
28
- const account = validateKaspaAddress(input.address, input.network);
29
- if (!/^[a-f0-9]{128}$/.test(input.signature)) return false;
30
- publicKey = new kaspa.PublicKey(input.publicKey ?? account.publicKey);
31
- derived = publicKey.toAddress(input.network);
32
- if (derived.toString() !== input.address) return false;
33
- return kaspa.verifyMessage({ message: input.message, signature: input.signature, publicKey });
34
- } catch {
35
- return false;
36
- } finally {
37
- derived?.free();
38
- publicKey?.free();
39
- }
40
- }
1
+ import {
2
+ createPostgresStorage,
3
+ migratePostgresStorage
4
+ } from "./chunk-44GVNLDI.js";
5
+ import {
6
+ createGhostlinkServer,
7
+ validateKaspaAddress,
8
+ verifyKaspaSignature
9
+ } from "./chunk-DAQY4RJN.js";
10
+ import {
11
+ createSqliteStorage
12
+ } from "./chunk-XMINHYKA.js";
41
13
 
42
14
  // src/storage-conformance.ts
43
- async function assertStorageConformance(store) {
15
+ async function assertStorageConformance(store, peer = store) {
44
16
  const assert = (condition, message) => {
45
17
  if (!condition) throw new Error(`Storage conformance: ${message}`);
46
18
  };
@@ -49,17 +21,18 @@ async function assertStorageConformance(store) {
49
21
  await store.putBrowser({ hash: "browser-b", csrf: "csrf", expiresAt: now + 1e4 });
50
22
  const challenge = { id: "challenge-a", browserHash: "browser-a", profile: "ghostlink-kaspa-v1", address: "fixture-address", network: "testnet-11", message: "fixture", issuedAt: now, expiresAt: new Date(now + 1e3).toISOString() };
51
23
  await store.putChallenge(challenge);
52
- assert(await store.getChallenge(challenge.id, "browser-b") === null, "challenge binding");
24
+ assert(await peer.getChallenge(challenge.id, "browser-b") === null, "challenge binding");
53
25
  const session = { hash: "session-a", browserHash: "browser-a", lastSeen: now, session: { address: "fixture-address", accountId: "fixture-account", chainId: "kaspa:testnet-11", network: "testnet-11", issuedAt: new Date(now).toISOString(), expiresAt: new Date(now + 4e3).toISOString(), idleExpiresAt: new Date(now + 2e3).toISOString() }, receipt: { profile: "ghostlink-kaspa-v1", message: "fixture", signature: "fixture" } };
54
- const results = await Promise.all([store.commitLogin(challenge.id, "browser-a", now, session), store.commitLogin(challenge.id, "browser-a", now, { ...session, hash: "session-other" })]);
26
+ assert(!await peer.commitLogin(challenge.id, "browser-b", now, { ...session, browserHash: "browser-b" }), "commit browser binding");
27
+ const results = await Promise.all([store.commitLogin(challenge.id, "browser-a", now, session), peer.commitLogin(challenge.id, "browser-a", now, { ...session, hash: "session-other" })]);
55
28
  assert(results.filter(Boolean).length === 1, "single atomic challenge consumption");
56
29
  const winningHash = results[0] ? session.hash : "session-other";
57
- assert(await store.getSession(winningHash, "browser-b", now, 2e3) === null, "session binding");
58
- assert(await store.getSession(winningHash, "browser-a", now + 1999, 2e3) !== null, "session idle refresh");
30
+ assert(await peer.getSession(winningHash, "browser-b", now, 2e3) === null, "session binding");
31
+ assert(await peer.getSession(winningHash, "browser-a", now + 1999, 2e3) !== null, "session idle refresh");
59
32
  assert(await store.getSession(winningHash, "browser-a", now + 3999, 2e3) === null, "idle expiry");
60
33
  assert(await store.getSession(winningHash, "browser-a", now + 4e3, 5e3) === null, "absolute expiry");
61
34
  await store.putChallenge(challenge);
62
- await store.revokeBrowser("browser-a");
35
+ await peer.revokeBrowser("browser-a");
63
36
  assert(await store.getChallenge(challenge.id, "browser-a") === null, "revoke outstanding challenges");
64
37
  assert(await store.getSession(winningHash, "browser-a", now, 2e3) === null, "revoke sessions");
65
38
  await store.putChallenge(challenge);
@@ -67,262 +40,23 @@ async function assertStorageConformance(store) {
67
40
  assert(await store.consumeRateLimit("fixture-limit", now, 1e3, 1), "first rate-limit request");
68
41
  assert(!await store.consumeRateLimit("fixture-limit", now, 1e3, 1), "rate-limit enforcement");
69
42
  assert(await store.consumeRateLimit("fixture-limit", now + 1e3, 1e3, 1), "rate-limit reset");
43
+ const limited = await Promise.all(Array.from({ length: 12 }, (_, i) => (i % 2 ? peer : store).consumeRateLimit("concurrent-limit", now, 1e3, 3)));
44
+ assert(limited.filter(Boolean).length === 3, "atomic rate limits across instances");
45
+ await store.putChallenge(challenge);
46
+ await peer.putChallenge({ ...challenge, id: "replacement" });
47
+ assert(await store.getChallenge(challenge.id, "browser-a") === null, "challenge replacement");
48
+ assert(await store.commitLogin("replacement", "browser-a", now, session), "replacement login");
49
+ await peer.putChallenge({ ...challenge, id: "rotation" });
50
+ assert(await peer.commitLogin("rotation", "browser-a", now, { ...session, hash: "rotated" }), "session rotation");
51
+ assert(await store.getSession(session.hash, "browser-a", now, 2e3) === null, "old session invalidation");
52
+ assert((await store.getSession("rotated", "browser-a", now + 3999, 5e3))?.idleExpiresAt === session.session.expiresAt, "idle expiry capped by absolute expiry");
53
+ await store.putBrowser({ hash: "expired-browser", csrf: "csrf", expiresAt: now });
54
+ await store.putChallenge({ ...challenge, id: "expired-binding", browserHash: "expired-browser" });
55
+ assert(!await peer.commitLogin("expired-binding", "expired-browser", now, { ...session, browserHash: "expired-browser" }), "expired binding at commit");
70
56
  await store.prune(now + 1e4);
71
57
  assert(await store.getBrowser("browser-a", now) === null, "expired browser pruning");
72
58
  }
73
59
 
74
- // src/sqlite.ts
75
- import { DatabaseSync } from "node:sqlite";
76
- import { mkdirSync, chmodSync } from "node:fs";
77
- import { dirname } from "node:path";
78
- function createSqliteStorage(filename) {
79
- if (filename !== ":memory:") mkdirSync(dirname(filename), { recursive: true, mode: 448 });
80
- const db = new DatabaseSync(filename);
81
- if (filename !== ":memory:") chmodSync(filename, 384);
82
- db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;");
83
- const version = db.prepare("PRAGMA user_version").get().user_version;
84
- if (version > 1) {
85
- db.close();
86
- throw new Error("Unsupported Ghostlink storage schema.");
87
- }
88
- db.exec(`
89
- CREATE TABLE IF NOT EXISTS browsers (hash TEXT PRIMARY KEY, csrf TEXT NOT NULL, expires INTEGER NOT NULL);
90
- CREATE TABLE IF NOT EXISTS challenges (id TEXT PRIMARY KEY, browser TEXT NOT NULL REFERENCES browsers(hash) ON DELETE CASCADE, expires INTEGER NOT NULL, data TEXT NOT NULL);
91
- CREATE INDEX IF NOT EXISTS challenges_browser ON challenges(browser);
92
- CREATE TABLE IF NOT EXISTS sessions (hash TEXT PRIMARY KEY, browser TEXT NOT NULL REFERENCES browsers(hash) ON DELETE CASCADE, expires INTEGER NOT NULL, last_seen INTEGER NOT NULL, data TEXT NOT NULL, receipt TEXT NOT NULL);
93
- CREATE INDEX IF NOT EXISTS sessions_browser ON sessions(browser);
94
- CREATE TABLE IF NOT EXISTS limits (key TEXT PRIMARY KEY, expires INTEGER NOT NULL, count INTEGER NOT NULL);
95
- PRAGMA user_version=1;
96
- `);
97
- function transaction(work) {
98
- db.exec("BEGIN IMMEDIATE");
99
- try {
100
- const result = work();
101
- db.exec("COMMIT");
102
- return result;
103
- } catch (e) {
104
- db.exec("ROLLBACK");
105
- throw e;
106
- }
107
- }
108
- return {
109
- async getBrowser(hash2, now) {
110
- const r = db.prepare("SELECT hash, csrf, expires AS expiresAt FROM browsers WHERE hash=? AND expires>?").get(hash2, now);
111
- return r ? r : null;
112
- },
113
- async putBrowser(b) {
114
- db.prepare("INSERT INTO browsers VALUES (?, ?, ?)").run(b.hash, b.csrf, b.expiresAt);
115
- },
116
- async putChallenge(c) {
117
- transaction(() => {
118
- db.prepare("DELETE FROM challenges WHERE browser=?").run(c.browserHash);
119
- db.prepare("INSERT INTO challenges VALUES (?, ?, ?, ?)").run(c.id, c.browserHash, Date.parse(c.expiresAt), JSON.stringify(c));
120
- });
121
- },
122
- async getChallenge(id, browserHash) {
123
- const r = db.prepare("SELECT data FROM challenges WHERE id=? AND browser=?").get(id, browserHash);
124
- return r ? JSON.parse(r.data) : null;
125
- },
126
- async commitLogin(id, browserHash, now, record) {
127
- return transaction(() => {
128
- const browser = db.prepare("SELECT hash FROM browsers WHERE hash=? AND expires>?").get(browserHash, now);
129
- if (!browser) return false;
130
- const consumed = db.prepare("DELETE FROM challenges WHERE id=? AND browser=? AND expires>? RETURNING id").get(id, browserHash, now);
131
- if (!consumed) return false;
132
- db.prepare("DELETE FROM sessions WHERE browser=?").run(browserHash);
133
- db.prepare("INSERT INTO sessions VALUES (?, ?, ?, ?, ?, ?)").run(record.hash, browserHash, Date.parse(record.session.expiresAt), record.lastSeen, JSON.stringify(record.session), JSON.stringify(record.receipt));
134
- return true;
135
- });
136
- },
137
- async getSession(hash2, browserHash, now, idleMs) {
138
- return transaction(() => {
139
- const r = db.prepare("SELECT data, expires FROM sessions WHERE hash=? AND browser=? AND expires>? AND last_seen>?").get(hash2, browserHash, now, now - idleMs);
140
- if (!r) return null;
141
- db.prepare("UPDATE sessions SET last_seen=? WHERE hash=?").run(now, hash2);
142
- return { ...JSON.parse(r.data), idleExpiresAt: new Date(Math.min(r.expires, now + idleMs)).toISOString() };
143
- });
144
- },
145
- async revokeBrowser(hash2) {
146
- transaction(() => {
147
- db.prepare("DELETE FROM challenges WHERE browser=?").run(hash2);
148
- db.prepare("DELETE FROM sessions WHERE browser=?").run(hash2);
149
- });
150
- },
151
- async consumeRateLimit(key, now, windowMs, maximum) {
152
- return transaction(() => {
153
- db.prepare("INSERT INTO limits VALUES (?, ?, 1) ON CONFLICT(key) DO UPDATE SET count=CASE WHEN expires<=? THEN 1 ELSE count+1 END, expires=CASE WHEN expires<=? THEN excluded.expires ELSE expires END").run(key, now + windowMs, now, now);
154
- return Number(db.prepare("SELECT count FROM limits WHERE key=?").get(key).count) <= maximum;
155
- });
156
- },
157
- async prune(now) {
158
- transaction(() => {
159
- db.prepare("DELETE FROM browsers WHERE expires<=?").run(now);
160
- db.prepare("DELETE FROM challenges WHERE expires<=?").run(now);
161
- db.prepare("DELETE FROM sessions WHERE expires<=?").run(now);
162
- db.prepare("DELETE FROM limits WHERE expires<=?").run(now);
163
- });
164
- },
165
- close() {
166
- db.close();
167
- }
168
- };
169
- }
170
-
171
- // src/server.ts
172
- import { randomBytes, createHash, timingSafeEqual } from "node:crypto";
173
- import { PROFILE, NETWORKS, serializeLoginMessage, isNetwork, chainId, GhostlinkError as GhostlinkError2 } from "@ghostdagger/ghostlink-core";
174
- var token = () => randomBytes(32).toString("hex");
175
- var hash = (value) => createHash("sha256").update(value).digest("hex");
176
- var equal = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
177
- var hexToken = (s) => typeof s === "string" && /^[a-f0-9]{64}$/.test(s);
178
- function cookies(request) {
179
- const result = /* @__PURE__ */ Object.create(null);
180
- for (const part of (request.headers.get("cookie") ?? "").split(";")) {
181
- const i = part.indexOf("=");
182
- if (i < 0) continue;
183
- const name = part.slice(0, i).trim();
184
- result[name] = name in result ? "" : part.slice(i + 1).trim();
185
- }
186
- return result;
187
- }
188
- async function boundedJson(request) {
189
- if (!/^application\/json(?:\s*;|$)/i.test(request.headers.get("content-type") ?? "")) throw new GhostlinkError2("INVALID_REQUEST", "Expected application/json.");
190
- if (Number(request.headers.get("content-length") ?? 0) > 16384) throw new GhostlinkError2("INVALID_REQUEST", "Request is too large.");
191
- const reader = request.body?.getReader();
192
- if (!reader) throw new GhostlinkError2("INVALID_REQUEST", "Missing request body.");
193
- let bytes = 0;
194
- const parts = [];
195
- while (true) {
196
- const next = await reader.read();
197
- if (next.done) break;
198
- bytes += next.value.length;
199
- if (bytes > 16384) {
200
- await reader.cancel();
201
- throw new GhostlinkError2("INVALID_REQUEST", "Request is too large.");
202
- }
203
- parts.push(next.value);
204
- }
205
- try {
206
- const value = JSON.parse(Buffer.concat(parts).toString("utf8"));
207
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
208
- return value;
209
- } catch {
210
- throw new GhostlinkError2("INVALID_REQUEST", "Invalid JSON request.");
211
- }
212
- }
213
- function createGhostlinkServer(config) {
214
- const origin = new URL(config.origin);
215
- const uri = new URL(config.loginUri);
216
- if (origin.origin !== config.origin || uri.origin !== origin.origin || uri.username || uri.password || uri.hash) throw new Error("Configure an exact trusted origin and a same-origin login URI.");
217
- const insecure = origin.protocol === "http:" && !!config.allowInsecureLocalhost && ["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname);
218
- if (origin.protocol !== "https:" && !insecure) throw new Error("HTTPS is required except for explicitly configured loopback development.");
219
- const prefix = config.prefix ?? "/auth/ghostlink";
220
- if (!/^\/[a-zA-Z0-9/_-]+$/.test(prefix) || prefix.endsWith("/")) throw new Error("Invalid authentication path prefix.");
221
- const store = config.storage;
222
- const now = config.now ?? Date.now;
223
- const challengeTtl = config.challengeTtlMs ?? 3e5;
224
- const sessionTtl = config.sessionTtlMs ?? 864e5;
225
- const idleTtl = config.idleTtlMs ?? 18e5;
226
- const skew = config.clockSkewMs ?? 3e4;
227
- for (const v of [challengeTtl, sessionTtl, idleTtl]) if (!Number.isSafeInteger(v) || v <= 0) throw new Error("Session and challenge durations must be positive integers.");
228
- if (challengeTtl > 3e5 || !Number.isSafeInteger(skew) || skew < 0 || skew > 3e4) throw new Error("Challenge duration or clock skew exceeds the profile limit.");
229
- const networks = config.networks ?? NETWORKS;
230
- if (!networks.length || networks.some((n) => !isNetwork(n))) throw new Error("Configure supported Kaspa networks.");
231
- const browserName = insecure ? "ghostlink-browser" : "__Host-ghostlink-browser";
232
- const sessionName = insecure ? "ghostlink-session" : "__Host-ghostlink-session";
233
- const browserTtl = Math.max(6048e5, sessionTtl);
234
- function cookie(name, value, maxAge) {
235
- return `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${Math.floor(maxAge / 1e3)}${insecure ? "" : "; Secure"}`;
236
- }
237
- function response(data, status = 200, setCookies = []) {
238
- const headers = new Headers({ "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Vary": "Cookie, Origin" });
239
- for (const c of setCookies) headers.append("Set-Cookie", c);
240
- return new Response(JSON.stringify(data), { status, headers });
241
- }
242
- function checkOrigin(request) {
243
- if (new URL(request.url).origin !== origin.origin || request.headers.get("sec-fetch-site") === "cross-site") throw new GhostlinkError2("INVALID_REQUEST", "Untrusted request origin.");
244
- const supplied = request.headers.get("origin");
245
- if (supplied !== null && supplied !== origin.origin || request.method !== "GET" && supplied !== origin.origin) throw new GhostlinkError2("INVALID_REQUEST", "Untrusted request origin.");
246
- }
247
- async function browserFor(request) {
248
- const value = cookies(request)[browserName];
249
- return hexToken(value) ? store.getBrowser(hash(value), now()) : null;
250
- }
251
- async function getSession(request) {
252
- const b = await browserFor(request);
253
- const value = cookies(request)[sessionName];
254
- if (!b || !hexToken(value)) return null;
255
- return store.getSession(hash(value), b.hash, now(), idleTtl);
256
- }
257
- async function handle(request, context = {}) {
258
- try {
259
- checkOrigin(request);
260
- const path = new URL(request.url).pathname;
261
- if (!path.startsWith(`${prefix}/`)) return response({ error: "Not found." }, 404);
262
- const endpoint = path.slice(prefix.length);
263
- if (!["/session", "/challenge", "/verify", "/logout"].includes(endpoint)) return response({ error: "Not found." }, 404);
264
- if (endpoint === "/session" && request.method !== "GET" || endpoint !== "/session" && request.method !== "POST") return response({ error: "Method not allowed." }, 405);
265
- const time = now();
266
- if (!await store.consumeRateLimit(`peer:${hash(context.ip ?? "shared")}`, time, 6e4, 180)) return response({ code: "SERVER_ERROR", error: "Too many requests. Wait a minute and try again." }, 429);
267
- await store.prune(time);
268
- let browser = await browserFor(request);
269
- if (endpoint === "/session") {
270
- const setCookies = [];
271
- if (!browser) {
272
- const value2 = token();
273
- browser = { hash: hash(value2), csrf: token(), expiresAt: time + browserTtl };
274
- await store.putBrowser(browser);
275
- setCookies.push(cookie(browserName, value2, browserTtl));
276
- }
277
- const session2 = await getSession(request);
278
- return response({ session: session2, csrfToken: browser.csrf }, 200, setCookies);
279
- }
280
- const csrf = request.headers.get("x-ghostlink-csrf") ?? "";
281
- if (!browser || !hexToken(csrf) || !equal(csrf, browser.csrf)) return response({ code: "UNAUTHENTICATED", error: "Reload this application before signing in." }, 403);
282
- if (!await store.consumeRateLimit(`browser:${browser.hash}`, time, 6e4, 30)) return response({ code: "SERVER_ERROR", error: "Too many requests. Wait a minute and try again." }, 429);
283
- const body = await boundedJson(request);
284
- if (endpoint === "/logout") {
285
- await store.revokeBrowser(browser.hash);
286
- return response({ ok: true }, 200, [cookie(sessionName, "", 0)]);
287
- }
288
- if (endpoint === "/challenge") {
289
- if (!isNetwork(body.network) || !networks.includes(body.network) || typeof body.address !== "string") throw new GhostlinkError2("INVALID_REQUEST", "Unsupported account or network.");
290
- const a = validateKaspaAddress(body.address, body.network);
291
- const expiresAt = new Date(time + challengeTtl).toISOString();
292
- const message = serializeLoginMessage({ domain: origin.host, address: a.address, network: body.network, uri: uri.href, nonce: token(), issuedAt: new Date(time).toISOString(), expiresAt });
293
- const record = { id: token(), profile: PROFILE, message, address: a.address, network: body.network, expiresAt, issuedAt: time, browserHash: browser.hash };
294
- await store.putChallenge(record);
295
- const { browserHash: _browser, issuedAt: _issued, ...challenge2 } = record;
296
- return response(challenge2);
297
- }
298
- if (!hexToken(body.challengeId) || typeof body.message !== "string" || body.message.length > 2e3 || typeof body.signature !== "string" || !/^[a-f0-9]{128}$/.test(body.signature) || body.publicKey !== void 0 && (typeof body.publicKey !== "string" || !/^(?:[a-fA-F0-9]{64}|0[23][a-fA-F0-9]{64})$/.test(body.publicKey))) throw new GhostlinkError2("INVALID_REQUEST", "Invalid verification request.");
299
- const challenge = await store.getChallenge(body.challengeId, browser.hash);
300
- if (!challenge || Date.parse(challenge.expiresAt) <= time || challenge.issuedAt > time + skew) throw new GhostlinkError2("EXPIRED", "The challenge expired or was already used. Generate a new message.");
301
- if (body.message !== challenge.message || !networks.includes(challenge.network)) throw new GhostlinkError2("INVALID_SIGNATURE", "The signed message does not match this login request.");
302
- if (!verifyKaspaSignature({ address: challenge.address, network: challenge.network, message: challenge.message, signature: body.signature, publicKey: body.publicKey })) throw new GhostlinkError2("INVALID_SIGNATURE", "The signature does not match the signing address and message.");
303
- const verifiedTime = now();
304
- const value = token();
305
- const session = { accountId: validateKaspaAddress(challenge.address, challenge.network).accountId, address: challenge.address, network: challenge.network, chainId: chainId(challenge.network), issuedAt: new Date(verifiedTime).toISOString(), expiresAt: new Date(verifiedTime + sessionTtl).toISOString(), idleExpiresAt: new Date(verifiedTime + Math.min(idleTtl, sessionTtl)).toISOString() };
306
- const committed = await store.commitLogin(challenge.id, browser.hash, verifiedTime, { hash: hash(value), browserHash: browser.hash, lastSeen: verifiedTime, session, receipt: { profile: PROFILE, message: challenge.message, signature: body.signature, publicKey: body.publicKey } });
307
- if (!committed) throw new GhostlinkError2("EXPIRED", "The challenge expired or was already used. Generate a new message.");
308
- return response(session, 200, [cookie(sessionName, value, sessionTtl)]);
309
- } catch (error) {
310
- if (error instanceof GhostlinkError2) return response({ code: error.code, error: error.message }, error.code === "INVALID_REQUEST" ? 400 : 401);
311
- return response({ code: "SERVER_ERROR", error: "The authentication service could not complete this request." }, 500);
312
- }
313
- }
314
- return {
315
- /** Handle session/challenge/verify/logout Web requests under prefix. Pass trusted peer metadata for rate limits; returns HTTP failures as Responses. */
316
- handle,
317
- /** Read identity from request cookies, returning null if missing/expired. Refreshes idle expiry. Does not enforce application authorization, origin checks, or CSRF for your own routes. */
318
- getSession,
319
- /** Validated public origin used for audience and Host checks. */
320
- origin: origin.origin,
321
- /** Authentication route prefix; mount these routes on the same origin as the browser app. */
322
- prefix
323
- };
324
- }
325
-
326
60
  // src/node.ts
327
61
  function createNodeHandler(server) {
328
62
  return async (req, res) => {
@@ -366,7 +100,9 @@ export {
366
100
  assertStorageConformance,
367
101
  createGhostlinkServer,
368
102
  createNodeHandler,
103
+ createPostgresStorage,
369
104
  createSqliteStorage,
105
+ migratePostgresStorage,
370
106
  validateKaspaAddress,
371
107
  verifyKaspaSignature
372
108
  };
@@ -0,0 +1,26 @@
1
+ import { GhostlinkStorage } from './index.js';
2
+ import '@ghostdagger/ghostlink-core';
3
+
4
+ /** Structural subset shared by pg and @neondatabase/serverless Pool clients. */
5
+ interface PostgresConnection {
6
+ query(text: string, values?: unknown[]): Promise<{
7
+ rows: Record<string, unknown>[];
8
+ }>;
9
+ release(destroy?: boolean): void;
10
+ }
11
+ /** Supply a writable primary pool. Read replicas and HTTP-only query functions are not supported. */
12
+ interface PostgresPool {
13
+ connect(): Promise<PostgresConnection>;
14
+ }
15
+ /** Isolate each application/environment in its own schema or database. */
16
+ interface PostgresStorageOptions {
17
+ /** Owned schema, default ghostlink. Lowercase SQL identifier, at most 63 characters. */
18
+ schema?: string;
19
+ }
20
+ /** Apply the versioned schema once during deployment, using a migration role. Safe to call concurrently. The caller owns the pool and must await pool.end() when finished. */
21
+ declare function migratePostgresStorage(pool: PostgresPool, options?: PostgresStorageOptions): Promise<void>;
22
+ /** Create a Postgres/Neon adapter after migratePostgresStorage. No I/O or pool ownership: share a bounded pool, and await pool.end() at shutdown. All security operations use the writable primary. */
23
+ declare function createPostgresStorage(pool: PostgresPool, options?: PostgresStorageOptions): GhostlinkStorage;
24
+
25
+ export { createPostgresStorage, migratePostgresStorage };
26
+ export type { PostgresConnection, PostgresPool, PostgresStorageOptions };
@@ -0,0 +1,8 @@
1
+ import {
2
+ createPostgresStorage,
3
+ migratePostgresStorage
4
+ } from "./chunk-44GVNLDI.js";
5
+ export {
6
+ createPostgresStorage,
7
+ migratePostgresStorage
8
+ };
@@ -0,0 +1,46 @@
1
+ import { Network, AuthSession } from '@ghostdagger/ghostlink-core';
2
+ import { GhostlinkStorage } from './index.js';
3
+
4
+ /** Trusted authentication policy. Origin/network configuration must agree with the browser client. */
5
+ interface GhostlinkServerConfig {
6
+ /** Exact public HTTP(S) origin, including port when present; no path or trailing slash. */
7
+ origin: string;
8
+ /** Absolute same-origin URI included in login messages; no credentials or fragment. */
9
+ loginUri: string;
10
+ /** Persistence adapter. Use createSqliteStorage or createPostgresStorage; its creator owns database/pool shutdown. */
11
+ storage: GhostlinkStorage;
12
+ /** Nonempty allowed network list. Defaults to mainnet, testnet-10, and testnet-11. */
13
+ networks?: readonly Network[];
14
+ /** Authentication route prefix without a trailing slash. Defaults to /auth/ghostlink. */
15
+ prefix?: string;
16
+ /** Permit HTTP only for localhost/loopback development. Defaults to false; public origins require HTTPS. */
17
+ allowInsecureLocalhost?: boolean;
18
+ /** Challenge lifetime in milliseconds. Defaults to 300_000 (5 minutes); must be positive and at most 300_000. */
19
+ challengeTtlMs?: number;
20
+ /** Absolute session lifetime in milliseconds. Defaults to 86_400_000 (24 hours); must be a positive safe integer. */
21
+ sessionTtlMs?: number;
22
+ /** Idle session lifetime in milliseconds. Defaults to 1_800_000 (30 minutes); successful getSession calls refresh it, capped by absolute expiry. */
23
+ idleTtlMs?: number;
24
+ /** Future-issued challenge tolerance in milliseconds. Defaults to 30_000; allowed range is 0–30_000. */
25
+ clockSkewMs?: number;
26
+ /** Clock returning Unix milliseconds. Defaults to Date.now; override for deterministic tests. */
27
+ now?: () => number;
28
+ }
29
+ /** Request metadata supplied by a trusted server adapter. */
30
+ interface RequestContext {
31
+ ip?: string;
32
+ }
33
+ /** Create Node authentication handlers with cookie sessions, CSRF checks, and signature verification. Validates policy immediately; does not start an HTTP listener or own storage shutdown. */
34
+ declare function createGhostlinkServer(config: GhostlinkServerConfig): {
35
+ /** Handle session/challenge/verify/logout Web requests under prefix. Pass trusted peer metadata for rate limits; returns HTTP failures as Responses. */
36
+ handle: (request: Request, context?: RequestContext) => Promise<Response>;
37
+ /** Read identity from request cookies, returning null if missing/expired. Refreshes idle expiry. Does not enforce application authorization, origin checks, or CSRF for your own routes. */
38
+ getSession: (request: Request) => Promise<AuthSession | null>;
39
+ /** Validated public origin used for audience and Host checks. */
40
+ origin: string;
41
+ /** Authentication route prefix; mount these routes on the same origin as the browser app. */
42
+ prefix: string;
43
+ };
44
+
45
+ export { createGhostlinkServer };
46
+ export type { GhostlinkServerConfig, RequestContext };
package/dist/server.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ createGhostlinkServer
3
+ } from "./chunk-DAQY4RJN.js";
4
+ export {
5
+ createGhostlinkServer
6
+ };
@@ -0,0 +1,7 @@
1
+ import { GhostlinkStorage } from './index.js';
2
+ import '@ghostdagger/ghostlink-core';
3
+
4
+ /** Open a Node 24 SQLite store, creating parent directories and schema as needed. Use :memory: for isolated tests; otherwise persist this file. The caller must close the store on shutdown. */
5
+ declare function createSqliteStorage(filename: string): GhostlinkStorage;
6
+
7
+ export { createSqliteStorage };
package/dist/sqlite.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ createSqliteStorage
3
+ } from "./chunk-XMINHYKA.js";
4
+ export {
5
+ createSqliteStorage
6
+ };
@@ -0,0 +1,48 @@
1
+ import { AuthChallenge, AuthSession } from '@ghostdagger/ghostlink-core';
2
+
3
+ interface BrowserRecord {
4
+ hash: string;
5
+ csrf: string;
6
+ expiresAt: number;
7
+ }
8
+ interface ChallengeRecord extends AuthChallenge {
9
+ browserHash: string;
10
+ issuedAt: number;
11
+ }
12
+ interface SessionRecord {
13
+ hash: string;
14
+ browserHash: string;
15
+ session: AuthSession;
16
+ lastSeen: number;
17
+ receipt: {
18
+ profile: string;
19
+ message: string;
20
+ signature: string;
21
+ publicKey?: string;
22
+ };
23
+ }
24
+ /** All times are Unix milliseconds. commitLogin MUST atomically consume the challenge and create the session. Operations must coordinate across independent server instances; subsequent reads must observe completed revocations. Fail closed on storage errors. */
25
+ interface GhostlinkStorage {
26
+ /** Look up an unexpired browser record by its hashed cookie token. */
27
+ getBrowser(hash: string, now: number): Promise<BrowserRecord | null>;
28
+ /** Persist the browser binding and CSRF token. */
29
+ putBrowser(browser: BrowserRecord): Promise<void>;
30
+ /** Store the new challenge, replacing outstanding challenges for the same browser. */
31
+ putChallenge(challenge: ChallengeRecord): Promise<void>;
32
+ /** Look up a challenge only within its bound browser. commitLogin must still enforce expiry. */
33
+ getChallenge(id: string, browserHash: string): Promise<ChallengeRecord | null>;
34
+ /** Atomically consume one unexpired challenge and replace the browser's session. Return false if already consumed, expired, or browser binding is invalid. */
35
+ commitLogin(challengeId: string, browserHash: string, now: number, session: SessionRecord): Promise<boolean>;
36
+ /** Return null for expired/wrong-browser sessions; otherwise refresh lastSeen and idleExpiresAt, capped by absolute expiry. All time arguments are milliseconds. */
37
+ getSession(hash: string, browserHash: string, now: number, idleMs: number): Promise<AuthSession | null>;
38
+ /** Revoke all sessions and outstanding challenges for this browser. */
39
+ revokeBrowser(browserHash: string): Promise<void>;
40
+ /** Atomically consume a request in the given millisecond window; false means the maximum was exceeded. */
41
+ consumeRateLimit(key: string, now: number, windowMs: number, maximum: number): Promise<boolean>;
42
+ /** Remove expired records. now is Unix milliseconds. */
43
+ prune(now: number): Promise<void>;
44
+ /** Optional synchronous shutdown. The storage creator owns calling this when no requests remain. */
45
+ close?(): void;
46
+ }
47
+
48
+ export type { BrowserRecord as B, ChallengeRecord as C, GhostlinkStorage as G, SessionRecord as S };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ghostdagger/ghostlink-server",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.1.0-beta.2",
4
4
  "type": "module",
5
5
  "description": "Server verification and revocable sessions for Ghostlink",
6
6
  "main": "./dist/index.js",
@@ -9,6 +9,18 @@
9
9
  ".": {
10
10
  "types": "./dist/index.d.ts",
11
11
  "import": "./dist/index.js"
12
+ },
13
+ "./server": {
14
+ "types": "./dist/server.d.ts",
15
+ "import": "./dist/server.js"
16
+ },
17
+ "./postgres": {
18
+ "types": "./dist/postgres.d.ts",
19
+ "import": "./dist/postgres.js"
20
+ },
21
+ "./sqlite": {
22
+ "types": "./dist/sqlite.d.ts",
23
+ "import": "./dist/sqlite.js"
12
24
  }
13
25
  },
14
26
  "files": [
@@ -22,7 +34,7 @@
22
34
  "node": ">=24 <25"
23
35
  },
24
36
  "dependencies": {
25
- "@ghostdagger/ghostlink-core": "0.1.0-beta.1"
37
+ "@ghostdagger/ghostlink-core": "0.1.0-beta.2"
26
38
  },
27
39
  "license": "MIT",
28
40
  "repository": {
@@ -40,7 +52,7 @@
40
52
  "tag": "candidate"
41
53
  },
42
54
  "scripts": {
43
- "build": "tsup src/index.ts --format esm --dts --clean",
55
+ "build": "tsup src/index.ts src/server.ts src/postgres.ts src/sqlite.ts --format esm --dts --clean",
44
56
  "typecheck": "tsc -p tsconfig.json"
45
57
  }
46
58
  }