@ghostdagger/ghostlink-server 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +51 -2
- package/dist/chunk-44GVNLDI.js +138 -0
- package/dist/chunk-DAQY4RJN.js +203 -0
- package/dist/chunk-XMINHYKA.js +100 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +108 -0
- package/dist/postgres.d.ts +26 -0
- package/dist/postgres.js +8 -0
- package/dist/server.d.ts +46 -0
- package/dist/server.js +6 -0
- package/dist/sqlite.d.ts +7 -0
- package/dist/sqlite.js +6 -0
- package/dist/storage-BazI-SH0.d.ts +48 -0
- package/package.json +55 -3
- package/vendor/kaspa/LICENSE +15 -0
- package/vendor/kaspa/README.md +206 -0
- package/vendor/kaspa/kaspa.d.ts +8095 -0
- package/vendor/kaspa/kaspa.js +15629 -0
- package/vendor/kaspa/kaspa_bg.wasm +0 -0
- package/vendor/kaspa/kaspa_bg.wasm.d.ts +881 -0
- package/vendor/kaspa/package.json +20 -0
- package/vendor/provenance.json +15 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 GhostDagger contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ghostdagger/ghostlink-server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node 24 authentication verification, Web handlers, Node HTTP adapter and durable SQLite or Postgres/Neon sessions for Ghostlink.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { createGhostlinkServer, createSqliteStorage, createNodeHandler } from '@ghostdagger/ghostlink-server';
|
|
7
|
+
const storage = createSqliteStorage('./data/auth.sqlite');
|
|
8
|
+
const auth = createGhostlinkServer({
|
|
9
|
+
origin: 'https://app.example', loginUri: 'https://app.example/login',
|
|
10
|
+
networks: ['testnet-11'], storage,
|
|
11
|
+
});
|
|
12
|
+
// Web: await auth.handle(request, { ip: trustedPeerAddress });
|
|
13
|
+
// Node: createServer(createNodeHandler(auth)).listen(...);
|
|
14
|
+
// Protected route: await auth.getSession(request);
|
|
15
|
+
// Shutdown: storage.close();
|
|
16
|
+
```
|
|
17
|
+
|
|
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
|
+
|
|
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
|
+
|
|
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.
|
|
45
|
+
|
|
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.
|
|
47
|
+
|
|
48
|
+
The official rusty-kaspa v2.0.1 Node WASM artifact is packaged unmodified with its ISC license and `vendor/provenance.json` checksums. Do not replace it with a similarly named unofficial npm package. New storage adapters must satisfy `GhostlinkStorage` and `assertStorageConformance` against an empty isolated test store, particularly atomic challenge consumption and session revocation.
|
|
49
|
+
|
|
50
|
+
Pre-release. See the repository's security and live-wallet acceptance documentation before deployment.
|
|
51
|
+
|
|
52
|
+
Beta acceptance status: live protected-API and real testnet transaction checks are deferred. Transaction APIs remain enabled; automated fixtures do not constitute real-wallet certification. See the [compatibility record](https://github.com/ghostdagger-labs/ghostlink/blob/main/docs/testing/compatibility-v1.json).
|
|
@@ -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
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
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';
|
|
8
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
9
|
+
|
|
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. */
|
|
11
|
+
declare function validateKaspaAddress(value: string, network: Network): {
|
|
12
|
+
address: string;
|
|
13
|
+
accountId: string;
|
|
14
|
+
publicKey: string;
|
|
15
|
+
};
|
|
16
|
+
/** Verify a 64-byte lowercase hex Schnorr signature against the exact message and address. Returns false on invalid input. Does not check challenge expiry, origin, replay, or application authorization; use createGhostlinkServer for login. */
|
|
17
|
+
declare function verifyKaspaSignature(input: {
|
|
18
|
+
address: string;
|
|
19
|
+
network: Network;
|
|
20
|
+
message: string;
|
|
21
|
+
signature: string;
|
|
22
|
+
publicKey?: string;
|
|
23
|
+
}): boolean;
|
|
24
|
+
|
|
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>;
|
|
27
|
+
|
|
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. */
|
|
29
|
+
declare function createNodeHandler(server: ReturnType<typeof createGhostlinkServer>): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
30
|
+
|
|
31
|
+
export { GhostlinkStorage, assertStorageConformance, createGhostlinkServer, createNodeHandler, validateKaspaAddress, verifyKaspaSignature };
|