@fountispanel/connect-server 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ - npm package renamed to `@fountispanel/connect-server`. Nothing else changes; install and import it under the new name.
6
+ - `applyMapping` leaves out a `governorate` or `city` that is not a FOUNTIS location code (lower-case code such as `erbil`), also when the rule has no `values` table; FOUNTIS refuses such values with `422 invalid_attribute`, so one unmapped city no longer costs the user their token.
7
+ - `checkToken` reports a `governorate` or `city` that is not a FOUNTIS location code.
8
+
9
+ ## 1.0.0
10
+
11
+ First stable release of `@fountispanel/connect-server` (Node server helper).
12
+
13
+ - `createUserToken`: signs the ES256 user token for a logged-in, verified user, applying your approved attribute mapping.
14
+ - `createUnsignedToken`: unsigned tokens for sandbox use.
15
+ - `verifyWebhook`: checks the signature and timestamp of webhooks FOUNTIS sends you.
16
+ - `checkToken` and the `connect-server` command line tool for inspecting a token.
17
+ - Node 18 or later, ESM, one dependency (`jose`).
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ FOUNTIS Connect SDK License
2
+
3
+ Copyright (c) 2026 FOUNTIS. All rights reserved.
4
+
5
+ 1. Permission. You may download, install and use this software development kit
6
+ (the "SDK") only to integrate FOUNTIS Connect into your own app or website,
7
+ and only while you have a valid FOUNTIS Connect partner agreement with FOUNTIS.
8
+
9
+ 2. Restrictions. You may not sell, sublicense or redistribute the SDK on its own,
10
+ use it to build a competing product or service, or remove this notice. You may
11
+ ship the SDK inside your app or website as part of your integration.
12
+
13
+ 3. Ownership. FOUNTIS keeps all rights in the SDK not expressly granted here.
14
+
15
+ 4. End. These rights end when your partner agreement ends or when you breach this
16
+ license. You must then stop using the SDK in new releases of your app or website.
17
+
18
+ 5. No warranty. THE SDK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19
+ OR IMPLIED, INCLUDING FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
20
+
21
+ 6. Limitation of liability. TO THE EXTENT ALLOWED BY LAW, FOUNTIS IS NOT LIABLE FOR
22
+ ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE SDK OR ITS USE.
23
+
24
+ If your partner agreement sets different terms, the partner agreement prevails.
package/README.md CHANGED
@@ -1,3 +1,99 @@
1
- # Temporary Holding Version
1
+ # @fountispanel/connect-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server helper for FOUNTIS Connect partners (Node 18+, ESM). Three things:
4
+
5
+ 1. sign a **user token** for your logged-in, verified user;
6
+ 2. **verify webhooks** FOUNTIS sends you;
7
+ 3. **check** a token from the command line.
8
+
9
+ ```bash
10
+ npm i @fountispanel/connect-server
11
+ ```
12
+
13
+ ## 1. Sign a user token
14
+
15
+ Your app calls this from your own login-protected endpoint. The web/iOS SDK asks that endpoint for a token whenever it needs one.
16
+
17
+ ```js
18
+ import { createUserToken } from "@fountispanel/connect-server";
19
+
20
+ const token = await createUserToken({
21
+ appId: "app_…", // from the FOUNTIS partner console
22
+ partnerId: "ptn_…",
23
+ kid: "my-key-1", // matches the public JWK you gave FOUNTIS
24
+ signingKey: process.env.FOUNTIS_SIGNING_KEY, // PEM, PKCS#8, ES256 (P-256)
25
+ userSecret: process.env.FOUNTIS_USER_SECRET, // any long random string, keep it private and stable
26
+ mapping, // your approved attribute mapping (below)
27
+ user, // your user record; user.id is required
28
+ lang: "ku", // optional: en | ku | kmr | ar
29
+ });
30
+ ```
31
+
32
+ - `sub` = `base64url(HMAC-SHA256(userSecret, String(user.id)))`. FOUNTIS never sees your user id. Do not change `userSecret` later: it would make every user look new.
33
+ - Tokens last 1 hour by default (`ttlSeconds`, max 24 h). Create one per request; do not store them.
34
+ - Users under 18 are refused (`error.code === "not_adult"`): return no token for them.
35
+ - Only send users you have verified yourself. The token says `kyc: "verified"`.
36
+
37
+ ### Mapping
38
+
39
+ The mapping says which of your fields become FOUNTIS attributes. Only these attributes exist: `gender` (`female` | `male`), `birth_year`, `governorate`, `city`, `lang`. FOUNTIS approves your mapping in the console; use the same one here.
40
+
41
+ ```js
42
+ const mapping = {
43
+ version: 1,
44
+ attributes: {
45
+ gender: { field: "sex", values: { M: "male", F: "female" } },
46
+ birth_year: { field: "dob", transform: "year" }, // Date, ISO string or a year number
47
+ city: { field: "address.city_code", values: { ERB: "erbil", SUL: "sulaymaniyah" } },
48
+ },
49
+ };
50
+ ```
51
+
52
+ A value that is missing or not in `values` is left out; nothing is guessed. `governorate` and `city` must be FOUNTIS location codes (lower case, for example `erbil`; the full lists are in the protocol contract): a value that is not one is left out too, so one unmapped city never costs the user their token.
53
+
54
+ ### Sandbox without a key pair
55
+
56
+ With a `pk_test_` key, FOUNTIS also accepts an unsigned token:
57
+
58
+ ```js
59
+ import { createUnsignedToken } from "@fountispanel/connect-server";
60
+ const token = createUnsignedToken({ appId, partnerId, userSecret, mapping, user });
61
+ ```
62
+
63
+ ## 2. Verify webhooks
64
+
65
+ FOUNTIS signs every webhook: header `Fountis-Signature: t=<unix seconds>,v1=<hex>`, HMAC-SHA256 of `t + "." + rawBody`. Verify the **raw** body (before JSON parsing).
66
+
67
+ ```js
68
+ import { verifyWebhook } from "@fountispanel/connect-server";
69
+
70
+ http.createServer(async (req, res) => {
71
+ const chunks = [];
72
+ for await (const c of req) chunks.push(c);
73
+ const raw = Buffer.concat(chunks);
74
+ if (!verifyWebhook(raw, req.headers["fountis-signature"], process.env.FOUNTIS_WEBHOOK_SECRET)) {
75
+ res.writeHead(400).end();
76
+ return;
77
+ }
78
+ const event = JSON.parse(raw.toString());
79
+ // credit event.units to the user behind event.sub …
80
+ res.writeHead(200).end();
81
+ });
82
+ ```
83
+
84
+ `verifyWebhook` returns `true` only for a correct signature that is less than 5 minutes old (constant-time compare; several `v1=` values are accepted during secret rotation). To map `event.sub` back to your user, compute `subjectFor(userSecret, user.id)` for your users (or keep the sub next to the user row).
85
+
86
+ ## 3. Check a token
87
+
88
+ ```bash
89
+ npx @fountispanel/connect-server check <token>
90
+ npx @fountispanel/connect-server check <token> --jwk public-jwk.json # also verifies the signature
91
+ ```
92
+
93
+ Prints the decoded header and claims and lists problems: unexpected claims, wrong `aud`, a numeric `sub`, a lifetime over 24 h, a bad attribute value.
94
+
95
+ ## Test
96
+
97
+ ```bash
98
+ npm test
99
+ ```
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@fountispanel/connect-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "FOUNTIS Connect server helper: sign user tokens, verify webhooks, check tokens.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "type": "module",
7
+ "main": "src/index.js",
8
+ "exports": {
9
+ ".": "./src/index.js"
10
+ },
11
+ "bin": {
12
+ "connect-server": "src/cli.js"
13
+ },
14
+ "files": [
15
+ "src",
16
+ "README.md",
17
+ "CHANGELOG.md",
18
+ "LICENSE"
19
+ ],
20
+ "engines": {
21
+ "node": ">=18"
22
+ },
23
+ "scripts": {
24
+ "test": "node --test",
25
+ "prepublishOnly": "npm test"
26
+ },
27
+ "dependencies": {
28
+ "jose": "^5.9.6"
29
+ },
30
+ "author": "FOUNTIS",
31
+ "homepage": "https://github.com/darbaz/fountis-connect#readme",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/darbaz/fountis-connect.git",
35
+ "directory": "server/node"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/darbaz/fountis-connect/issues",
39
+ "email": "dev@fountis.org"
40
+ },
41
+ "keywords": [
42
+ "fountis",
43
+ "connect",
44
+ "survey",
45
+ "jwt",
46
+ "webhook",
47
+ "sdk"
48
+ ],
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }
package/src/cli.js ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { checkToken } from "./index.js";
4
+
5
+ const [cmd, token, ...rest] = process.argv.slice(2);
6
+ if (cmd !== "check" || !token) {
7
+ console.error("usage: npx @fountispanel/connect-server check <token> [--jwk public-jwk.json]");
8
+ process.exit(2);
9
+ }
10
+
11
+ const r = checkToken(token);
12
+ if (r.claims) {
13
+ const c = r.claims;
14
+ console.log(`alg ${r.header.alg}, kid ${r.header.kid ?? "-"}`);
15
+ console.log(`iss ${c.iss} aud ${c.aud} sub ${String(c.sub).slice(0, 8)}... mapping v${c.mapping_version}`);
16
+ console.log(`attrs ${JSON.stringify(c.attrs)}`);
17
+ if (Number.isInteger(c.exp)) console.log(`expires ${new Date(c.exp * 1000).toISOString()}`);
18
+ }
19
+
20
+ const jwkAt = rest.indexOf("--jwk");
21
+ if (jwkAt !== -1 && rest[jwkAt + 1]) {
22
+ try {
23
+ const { jwtVerify, importJWK } = await import("jose");
24
+ const jwk = JSON.parse(readFileSync(rest[jwkAt + 1], "utf8"));
25
+ await jwtVerify(token, await importJWK(jwk, "ES256"), { algorithms: ["ES256"] });
26
+ console.log("signature OK");
27
+ } catch (e) {
28
+ r.errors.push(`signature check failed: ${e.message}`);
29
+ r.ok = false;
30
+ }
31
+ }
32
+
33
+ for (const w of r.warnings ?? []) console.log(`note: ${w}`);
34
+ if (r.errors.length) {
35
+ for (const e of r.errors) console.error(`- ${e}`);
36
+ }
37
+ console.log(r.ok ? "token looks valid" : "token has problems");
38
+ process.exit(r.ok ? 0 : 1);
package/src/index.js ADDED
@@ -0,0 +1,203 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { SignJWT, importPKCS8 } from "jose";
3
+
4
+ /** Error with a stable `code`, so callers can branch without parsing messages. */
5
+ export class ConnectTokenError extends Error {
6
+ constructor(code, message) {
7
+ super(message || code);
8
+ this.code = code;
9
+ this.name = "ConnectTokenError";
10
+ }
11
+ }
12
+
13
+ const b64url = (buf) => Buffer.from(buf).toString("base64url");
14
+
15
+ /** sub = base64url(HMAC-SHA256(userSecret, String(user.id))). Stable per user, not reversible without the secret. */
16
+ export function subjectFor(userSecret, userId) {
17
+ if (!userSecret) throw new ConnectTokenError("missing_user_secret");
18
+ if (userId === undefined || userId === null || userId === "") throw new ConnectTokenError("missing_user_id");
19
+ return b64url(createHmac("sha256", userSecret).update(String(userId)).digest());
20
+ }
21
+
22
+ const getPath = (obj, path) => String(path).split(".").reduce((o, k) => (o == null ? undefined : o[k]), obj);
23
+
24
+ /**
25
+ * `governorate` and `city` are FOUNTIS location codes (lower case, e.g. "erbil"; the lists are in
26
+ * protocol/CONTRACT.md), never names, phone numbers or your own codes. This is the shape FOUNTIS
27
+ * accepts at the edge (up to 3 digits); the exact list is checked server-side.
28
+ */
29
+ const isLocationCode = (v) => typeof v === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(v) && (v.match(/\d/g) || []).length <= 3;
30
+
31
+ function toYear(v) {
32
+ if (typeof v === "number" && Number.isInteger(v) && v >= 1900 && v <= 2200) return v;
33
+ if (v instanceof Date && !Number.isNaN(v.getTime())) return v.getUTCFullYear();
34
+ if (typeof v === "string") {
35
+ if (/^\d{4}$/.test(v.trim())) return Number(v);
36
+ const d = new Date(v);
37
+ if (!Number.isNaN(d.getTime())) return d.getUTCFullYear();
38
+ }
39
+ return undefined;
40
+ }
41
+
42
+ /**
43
+ * Apply the partner's approved mapping spec to a user record. Returns the attrs claim.
44
+ * mapping = { version?, attributes: { gender: { field: "sex", values: { M: "male", F: "female" } },
45
+ * birth_year: { field: "dob", transform: "year" },
46
+ * city: { field: "city_code", values: { ... } } } }
47
+ * Attributes whose value is missing or not in `values` are left out (never guessed). So is a
48
+ * `governorate` / `city` that is not a FOUNTIS location code (see isLocationCode): one unmapped
49
+ * city must not make FOUNTIS refuse the whole token.
50
+ */
51
+ export function applyMapping(mapping, user) {
52
+ const out = {};
53
+ for (const [attr, rule] of Object.entries(mapping?.attributes ?? {})) {
54
+ let v = getPath(user, rule.field ?? attr);
55
+ if (v === undefined || v === null || v === "") continue;
56
+ if (rule.values) {
57
+ v = rule.values[String(v)];
58
+ if (v === undefined) continue;
59
+ }
60
+ if (rule.transform === "year") {
61
+ v = toYear(v);
62
+ if (v === undefined) continue;
63
+ } else if (rule.transform) {
64
+ throw new ConnectTokenError("bad_mapping", `unknown transform "${rule.transform}"`);
65
+ }
66
+ if ((attr === "governorate" || attr === "city") && !isLocationCode(v)) continue;
67
+ out[attr] = v;
68
+ }
69
+ return out;
70
+ }
71
+
72
+ function buildClaims({ appId, partnerId, userSecret, mapping, user, lang, ttlSeconds = 3600, now = Date.now() }) {
73
+ if (!appId || !partnerId) throw new ConnectTokenError("missing_ids", "appId and partnerId are required");
74
+ if (!user) throw new ConnectTokenError("missing_user");
75
+ const attrs = applyMapping(mapping, user);
76
+ if (lang) attrs.lang = lang;
77
+ const year = new Date(now).getUTCFullYear();
78
+ if (attrs.birth_year !== undefined && attrs.birth_year > year - 18)
79
+ throw new ConnectTokenError("not_adult", "FOUNTIS studies are for adults (18+)");
80
+ const iat = Math.floor(now / 1000);
81
+ const ttl = Math.min(Math.max(Math.floor(ttlSeconds), 60), 86400);
82
+ return {
83
+ iss: partnerId,
84
+ aud: `fountis-connect:${appId}`,
85
+ sub: subjectFor(userSecret, user.id),
86
+ kyc: "verified",
87
+ attrs,
88
+ mapping_version: mapping?.version ?? mapping?.mapping_version ?? 1,
89
+ iat,
90
+ exp: iat + ttl,
91
+ jti: b64url(randomBytes(16)),
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Sign a user token (JWS ES256) for the FOUNTIS Connect SDK.
97
+ * signingKey is the PEM (PKCS#8) private key whose public JWK you gave FOUNTIS.
98
+ * Only call this for users YOU have verified (kyc: "verified"), after your own login check.
99
+ */
100
+ export async function createUserToken({ signingKey, kid, ...rest }) {
101
+ if (!signingKey) throw new ConnectTokenError("missing_signing_key");
102
+ const claims = buildClaims(rest);
103
+ const key = await importPKCS8(signingKey, "ES256");
104
+ return new SignJWT(claims)
105
+ .setProtectedHeader({ alg: "ES256", typ: "JWT", kid: kid ?? rest.appId })
106
+ .sign(key);
107
+ }
108
+
109
+ /** Sandbox only: an unsigned token (alg "none"). The server accepts it just for pk_test_ keys. */
110
+ export function createUnsignedToken(opts) {
111
+ const claims = buildClaims(opts);
112
+ const head = b64url(JSON.stringify({ alg: "none", typ: "JWT" }));
113
+ return `${head}.${b64url(JSON.stringify(claims))}.`;
114
+ }
115
+
116
+ /* ------------------------------- webhooks ------------------------------- */
117
+
118
+ /** Header value for a webhook body: `t=<unix seconds>,v1=<hex hmac of "t.body">`. (FOUNTIS signs; exported for tests.) */
119
+ export function signWebhook(rawBody, secret, t = Math.floor(Date.now() / 1000)) {
120
+ const mac = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
121
+ return `t=${t},v1=${mac}`;
122
+ }
123
+
124
+ /**
125
+ * Verify a FOUNTIS webhook. Pass the RAW request body (string or Buffer), the
126
+ * `Fountis-Signature` header and your webhook secret. Returns true only for a
127
+ * fresh (within 5 minutes), correctly signed body.
128
+ */
129
+ export function verifyWebhook(rawBody, signatureHeader, secret, { toleranceSeconds = 300, now = Date.now() } = {}) {
130
+ try {
131
+ if (!signatureHeader || !secret) return false;
132
+ const parts = String(signatureHeader).split(",").map((p) => p.trim().split("="));
133
+ const t = Number(parts.find(([k]) => k === "t")?.[1]);
134
+ const sigs = parts.filter(([k]) => k === "v1").map(([, v]) => v);
135
+ if (!Number.isFinite(t) || sigs.length === 0) return false;
136
+ if (Math.abs(now / 1000 - t) > toleranceSeconds) return false;
137
+ const body = Buffer.isBuffer(rawBody) ? rawBody.toString("utf8") : String(rawBody);
138
+ const expected = createHmac("sha256", secret).update(`${t}.${body}`).digest();
139
+ return sigs.some((hex) => {
140
+ if (!/^[0-9a-f]{64}$/i.test(hex)) return false;
141
+ return timingSafeEqual(Buffer.from(hex, "hex"), expected);
142
+ });
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ /* ------------------------------ token check ------------------------------ */
149
+
150
+ const CLAIMS = ["iss", "aud", "sub", "kyc", "attrs", "mapping_version", "iat", "exp", "jti"];
151
+ const ATTRS = {
152
+ gender: (v) => ["female", "male"].includes(v),
153
+ birth_year: (v, year) => Number.isInteger(v) && v <= year - 18 && v >= 1900,
154
+ governorate: isLocationCode,
155
+ city: isLocationCode,
156
+ lang: (v) => ["en", "ku", "kmr", "ar"].includes(v),
157
+ };
158
+
159
+ /** Decode (no signature check) and validate the claim shape. Returns { ok, errors, header, claims }. */
160
+ export function checkToken(token, { now = Date.now() } = {}) {
161
+ const errors = [];
162
+ const warnings = [];
163
+ const parts = String(token || "").trim().split(".");
164
+ if (parts.length !== 3) return { ok: false, errors: ["not a compact JWS (needs 3 dot-separated parts)"] };
165
+ let header, claims;
166
+ try {
167
+ header = JSON.parse(Buffer.from(parts[0], "base64url").toString("utf8"));
168
+ claims = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
169
+ } catch {
170
+ return { ok: false, errors: ["header or payload is not base64url JSON"] };
171
+ }
172
+ if (header.alg === "none") warnings.push("alg is none: accepted for sandbox (pk_test_) keys only");
173
+ else if (header.alg !== "ES256") errors.push(`alg must be ES256 (got ${header.alg})`);
174
+ else if (!header.kid) errors.push("header.kid is missing");
175
+ for (const k of Object.keys(claims)) if (!CLAIMS.includes(k)) errors.push(`unexpected claim "${k}" (the claim set is closed)`);
176
+ for (const k of CLAIMS) if (claims[k] === undefined) errors.push(`missing claim "${k}"`);
177
+ const year = new Date(now).getUTCFullYear();
178
+ if (typeof claims.iss !== "string" || !claims.iss) errors.push("iss must be your partner id");
179
+ if (typeof claims.aud !== "string" || !claims.aud.startsWith("fountis-connect:app_")) errors.push('aud must be "fountis-connect:<app id>"');
180
+ if (typeof claims.sub !== "string" || !/^[A-Za-z0-9_-]{22,64}$/.test(claims.sub)) errors.push("sub must be 22-64 chars of A-Z a-z 0-9 _ -");
181
+ else if (/^\d+$/.test(claims.sub)) errors.push("sub must not be all digits (looks like a raw user id)");
182
+ if (claims.kyc !== "verified") errors.push('kyc must be "verified"');
183
+ if (!Number.isInteger(claims.mapping_version)) errors.push("mapping_version must be an integer");
184
+ if (!Number.isInteger(claims.iat) || !Number.isInteger(claims.exp)) errors.push("iat and exp must be integer seconds");
185
+ else {
186
+ if (claims.exp - claims.iat > 86400) errors.push("exp - iat is more than 24 hours");
187
+ if (claims.exp * 1000 < now) errors.push("token is expired");
188
+ }
189
+ if (typeof claims.jti !== "string" || !claims.jti) errors.push("jti must be a non-empty string");
190
+ if (!claims.attrs || typeof claims.attrs !== "object" || Array.isArray(claims.attrs)) errors.push("attrs must be an object");
191
+ else
192
+ for (const [k, v] of Object.entries(claims.attrs)) {
193
+ if (!(k in ATTRS)) errors.push(`attrs.${k} is not in the attribute vocabulary`);
194
+ else if (!ATTRS[k](v, year)) {
195
+ errors.push(
196
+ k === "governorate" || k === "city"
197
+ ? `attrs.${k} must be a FOUNTIS location code in lower case, e.g. "erbil" (names, phone numbers and your own codes are refused)`
198
+ : `attrs.${k} has an invalid value (${JSON.stringify(v)})`,
199
+ );
200
+ }
201
+ }
202
+ return { ok: errors.length === 0, errors, warnings, header, claims };
203
+ }