Skip to content

Commit 0528bc8

Browse files
committed
Merge release/3.22.0: 3.22.0 as published (sign-in label format, apiEndpoint read as new URL() reads it)
2 parents 1a94a6c + b519f68 commit 0528bc8

8 files changed

Lines changed: 218 additions & 32 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,11 @@
2525

2626
- **Development and test dependencies refreshed (`npm audit` 16 to 5 moderate, all development-only; 0 for what ships).** The repository overrides `ws` to `^8.23.0` (GHSA-37g9-w4hg-h9qr, reached through `socket.io-client` -> `engine.io-client`) and takes the non-breaking `npm audit fix` updates (typescript-eslint, mocha, terser, eslint-plugin-import-x). An override does not reach applications that install `@pryv/socket.io`: the add-on's README now tells Node.js applications to add the same `ws` override until `engine.io-client` allows a fixed `ws`.
2727

28-
## 3.22.0 - 2026-12-01
28+
## 3.22.0 - 2026-12-04
2929

3030
`pryv`, `@pryv/socket.io`, `@pryv/monitor`, `@pryv/delegation`, `@pryv/encryption` 3.22.0 (`@pryv/cmc` unchanged at
31-
3.26.0): the sign-in button label format can be set by the service.
31+
3.26.0): the sign-in button label format can be set by the service, and an apiEndpoint is read the way `new URL()`
32+
reads it (security).
3233

3334
### Added
3435

@@ -37,6 +38,28 @@
3738
language (e.g. "Sign in with Health Data Safe") in its `buttonSignInMessages.json`. Default `{LOGIN}: {serviceName}`:
3839
the label is unchanged for services that do not define it.
3940

41+
### Security
42+
43+
- **`pryv`: an `apiEndpoint` is read the way `new URL()` reads it, and an ambiguous one is refused.**
44+
`utils.extractTokenAndAPIEndpoint` (used by `new pryv.Connection(apiEndpoint)`) took everything up to the last `@`
45+
as the token, so an `@` in the path, query or fragment (`https://good.example/@other.example/`) made the library call
46+
another host than the one `new URL(apiEndpoint).host` names: an application that checks the host of an endpoint it
47+
received before opening a connection could be sent elsewhere, with the token text. The token is now the user part of
48+
the authority only; an endpoint with an `@` after the authority, more than one `@`, a backslash, white space or a
49+
control character throws `Invalid apiEndpoint: ambiguous URL`. The endpoint is now read against a strict grammar:
50+
`http` or `https` only, a token of URL user-part characters without `:` or `%` (a `user:password@` part is refused),
51+
an ASCII host name (a Unicode name is given in its `xn--` form), IPv4 or bracketed IPv6 address with an optional
52+
port, a path without query or fragment; and
53+
`new URL()` must parse it to the same host. A value that is not a string (a `URL` object), or a string with
54+
surrounding white space or a trailing newline, now throws instead of being accepted. `utils.buildAPIEndpoint` refuses
55+
a token outside that grammar and checks that what it builds reads back the same; `Service.buildAPIEndpoint` (and so
56+
`apiEndpointFor`, `login`, the MFA calls) refuses a username other than letters, digits and `-`, which could move the
57+
endpoint, and the password sent to it, to another host. `utils.decomposeAPIEndpoint` names no username when the part
58+
matching the template is not one (`https://tok@other.example/x.pryv.me/` is not on pryv.me). `@pryv/socket.io`
59+
percent-encodes the token in its query. Pryv endpoints never hold the refused forms, so valid endpoints parse as
60+
before (`connection.endpoint` keeps the host as written). Applications that validate an endpoint should compare
61+
`new URL(connection.endpoint).host`, the endpoint the library calls.
62+
4063
## 3.26.0 - 2026-12-01
4164

4265
`@pryv/cmc` 3.26.0 only (`pryv` and the other packages stay 3.21.0): revoke helpers wait for the outcome and throw on

‎components/pryv-socket.io/src/SocketIO.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ class SocketIO extends EventEmitter {
5858

5959
this.connection.username()
6060
.then(username => {
61-
const socketEndpoint = this.connection.endpoint + username + '?auth=' + this.connection.token;
61+
const socketEndpoint = this.connection.endpoint + username + '?auth=' + encodeURIComponent(this.connection.token);
6262
// Cap reconnects so a server-side outage can't drive a runaway loop.
6363
// socket.io-client default is reconnectionAttempts: Infinity, max delay 5s.
6464
// With these settings, a stuck client gives up after ~10 attempts spread

‎components/pryv/src/OAuth2Client.js‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -285,11 +285,9 @@ class OAuth2Client {
285285
if (!apiEndpoint) {
286286
throw new Error('OAuth2Client: token response is missing the Pryv "apiEndpoint" extension');
287287
}
288-
// Validate the endpoint the Connection will actually send the token to, not
289-
// the raw apiEndpoint string: Connection splits token/endpoint on the LAST
290-
// `@` (utils regex), so a crafted `http://tok@127.0.0.1/x@evil/` parses as
291-
// loopback here but posts the token to `evil` there. Assert on the extracted
292-
// endpoint to close that parser-divergence gap.
288+
// Validate the endpoint the Connection will actually send the token to (the
289+
// extracted one, which refuses an endpoint other parsers could read with
290+
// another host), not the raw apiEndpoint string.
293291
const { endpoint } = utils.extractTokenAndAPIEndpoint(String(apiEndpoint));
294292
assertSecureApiEndpoint(endpoint);
295293
// DPoP flow → a SignedConnection bound to the same key the token was

‎components/pryv/src/Service.js‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,12 @@ class Service {
168168
* @returns {APIEndpoint} The constructed API endpoint URL
169169
*/
170170
static buildAPIEndpoint (serviceInfo, username, token) {
171+
// A username is letters, digits and `-`: anything else (a `/`, `@`, `.`
172+
// or `:`) would move the endpoint, and the password or token sent to it,
173+
// to another host or path.
174+
if (typeof username !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9-]*$/.test(username)) {
175+
throw new PryvError('Invalid username: it cannot be placed in an apiEndpoint');
176+
}
171177
const endpoint = serviceInfo.api.replace('{username}', username);
172178
return utils.buildAPIEndpoint({ endpoint, token });
173179
}

‎components/pryv/src/index.d.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1952,7 +1952,9 @@ declare module 'pryv' {
19521952

19531953
export const utils: {
19541954
isBrowser(): boolean;
1955+
/** @throws Error when the endpoint is not an http(s) URL with a token, host and path of their own grammar, or is ambiguous. */
19551956
extractTokenAndAPIEndpoint(apiEndpoint: string): TokenAndAPIEndpoint;
1957+
/** @throws Error when the token or the endpoint cannot be placed in an apiEndpoint unambiguously. */
19561958
buildAPIEndpoint(tokenAndAPI: TokenAndAPIEndpoint): string;
19571959
decomposeAPIEndpoint(apiEndpoint: string, serviceInfoApi: string): DecomposedAPIEndpoint;
19581960
browserIsMobileOrTablet(navigator?: string | Navigator): boolean;

‎components/pryv/src/utils.js‎

Lines changed: 74 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,21 @@
22
* @license
33
* [BSD-3-Clause](https://github.com/pryv/lib-js/blob/master/LICENSE)
44
*/
5-
const regexAPIandToken = /(.+):\/\/(.+)@(.+)/gm;
65
const regexSchemaAndPath = /(.+):\/\/(.+)/gm;
6+
// http(s), `://`, then the authority (up to the first `/`, `?` or `#`) and
7+
// the rest. Read the way `new URL()` reads the same string (checked below).
8+
const regexSchemeAuthorityRest = /^(https?):\/\/([^/?#]*)(.*)$/is;
9+
// A token: letters, digits and the URL user-part characters that need no
10+
// encoding and end nothing (no `:`, `@`, `/`, `?`, `#`, `%`, backslash).
11+
const regexToken = /^[A-Za-z0-9._~!$&'()*+,;=-]+$/;
12+
// A host: a name (ASCII; `_` as container names use) or an IPv4 address, or
13+
// an IPv6 address in brackets, with an optional port.
14+
const regexHost = /^(?:\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9_](?:[A-Za-z0-9_.-]*[A-Za-z0-9_])?\.?)(?::[0-9]{1,5})?$/;
15+
// A path: `/` and the characters a URL path holds without ending or
16+
// changing it (no `@`, `?`, `#`, backslash, white space).
17+
const regexPath = /^(?:\/[A-Za-z0-9._~!$&'()*+,;=:%/-]*)?$/;
18+
// A username placed in an endpoint (Pryv usernames: letters, digits, `-`).
19+
const regexUsername = /^[A-Za-z0-9][A-Za-z0-9-]*$/;
720
const buildSearchParams = require('./lib/buildSearchParams');
821

922
/**
@@ -74,34 +87,55 @@ const utils = module.exports = {
7487
},
7588

7689
/**
77-
* From a APIEndpoint URL, return an object (TokenAndAPI) with two properties
90+
* From a APIEndpoint URL, return an object (TokenAndAPI) with two properties.
91+
* The endpoint is read the way `new URL()` reads it: `http` or `https`, the
92+
* token as the authority's user part, a host, an optional port and a path.
7893
* @memberof pryv.utils
7994
* @param {APIEndpoint} apiEndpoint
8095
* @returns {TokenAndEndpoint}
96+
* @throws {Error} `Cannot find endpoint, invalid URL format` when it is not such a URL;
97+
* `Invalid apiEndpoint: ambiguous URL` when other URL parsers could read another host
98+
* or token in it (an `@` after the authority, more than one `@`, a query or fragment,
99+
* a backslash, white space, characters outside those of a token, host or path).
81100
*/
82101
extractTokenAndAPIEndpoint: function (apiEndpoint) {
83-
regexAPIandToken.lastIndex = 0;
84-
const res = regexAPIandToken.exec(apiEndpoint);
85-
86-
if (res !== null) { // has token
87-
// add a trailing '/' to end point if missing
88-
if (!res[3].endsWith('/')) {
89-
res[3] += '/';
90-
}
91-
return { endpoint: res[1] + '://' + res[3], token: res[2] };
102+
if (typeof apiEndpoint !== 'string') {
103+
throw new Error('Cannot find endpoint, invalid URL format');
92104
}
93-
// else check if valid url
94-
regexSchemaAndPath.lastIndex = 0;
95-
const res2 = regexSchemaAndPath.exec(apiEndpoint);
96-
if (res2 === null) {
105+
const res = regexSchemeAuthorityRest.exec(apiEndpoint);
106+
if (res === null || res[2] === '') {
97107
throw new Error('Cannot find endpoint, invalid URL format');
98108
}
109+
const [, scheme, authority, rest] = res;
110+
const ambiguous = () => new Error('Invalid apiEndpoint: ambiguous URL');
111+
// Everything is checked against a positive grammar, so `new URL()` and any
112+
// other parser find the same token and host: an endpoint that could be
113+
// read with another host would send the token, and the calls, to a host
114+
// other than the one a caller checked.
115+
const at = authority.indexOf('@');
116+
if (at !== authority.lastIndexOf('@')) throw ambiguous();
117+
const token = at === -1 ? null : authority.slice(0, at);
118+
const host = at === -1 ? authority : authority.slice(at + 1);
119+
if (token === '' || host === '') {
120+
throw new Error('Cannot find endpoint, invalid URL format');
121+
}
122+
if ((token !== null && !regexToken.test(token)) || !regexHost.test(host) || !regexPath.test(rest)) {
123+
throw ambiguous();
124+
}
125+
let endpoint = scheme + '://' + host + rest;
126+
// The same host as `new URL()` finds, which must parse it.
127+
let parsed;
128+
try {
129+
parsed = new URL(apiEndpoint);
130+
} catch (_e) {
131+
throw ambiguous();
132+
}
133+
if (parsed.host === '' || parsed.host !== new URL(endpoint).host) throw ambiguous();
99134
// add a trailing '/' to end point if missing
100-
if (!res2[2].endsWith('/')) {
101-
res2[2] += '/';
135+
if (!endpoint.endsWith('/')) {
136+
endpoint += '/';
102137
}
103-
104-
return { endpoint: res2[1] + '://' + res2[2], token: null };
138+
return { endpoint, token };
105139
},
106140

107141
/**
@@ -111,6 +145,20 @@ const utils = module.exports = {
111145
* @returns {APIEndpoint}
112146
*/
113147
buildAPIEndpoint: function (tokenAndAPI) {
148+
if (tokenAndAPI.token && !regexToken.test(tokenAndAPI.token)) {
149+
throw new Error('Invalid token: it cannot be placed in an apiEndpoint');
150+
}
151+
const built = utils._buildAPIEndpoint(tokenAndAPI);
152+
// What is built reads back as the same endpoint and token.
153+
const back = utils.extractTokenAndAPIEndpoint(built);
154+
if ((back.token ?? null) !== (tokenAndAPI.token ? String(tokenAndAPI.token) : null)) {
155+
throw new Error('Invalid apiEndpoint: ambiguous URL');
156+
}
157+
return built;
158+
},
159+
160+
/** @private `buildAPIEndpoint` without its checks. */
161+
_buildAPIEndpoint: function (tokenAndAPI) {
114162
if (!tokenAndAPI.token) {
115163
let res = tokenAndAPI.endpoint + '';
116164
if (!tokenAndAPI.endpoint.endsWith('/')) {
@@ -178,6 +226,13 @@ const utils = module.exports = {
178226
return { token, username: null, host };
179227
}
180228
const username = endpoint.slice(tplPrefix.length, endpoint.length - tplSuffix.length);
229+
// A "username" holding a dot, a slash or a port is another host or path
230+
// that happens to start and end like the template: not this platform's.
231+
if (!regexUsername.test(username)) {
232+
let host = '';
233+
try { host = new URL(endpoint).host; } catch (_e) {}
234+
return { token, username: null, host };
235+
}
181236
// Disambiguate by where {username} sits in the template:
182237
// - subdomain → prefix ends with `://` (username right after scheme)
183238
// - path-style → prefix has more after `://` (host already in prefix)

‎components/pryv/test/OAuth2Client.test.js‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -275,14 +275,13 @@ describe('[OAUTH-LIB] OAuth2Client', function () {
275275
});
276276

277277
it('[OAL-B11] refuses a loopback-spoofing apiEndpoint whose real endpoint is a remote http host', async function () {
278-
// Connection splits token/endpoint on the LAST `@`, so this parses as
279-
// token `tok@127.0.0.1/x`, endpoint `http://evil.example/` — the token
280-
// would go to evil.example in cleartext. The guard must validate the
281-
// extracted endpoint, not the loopback-looking raw string.
278+
// An `@` after the authority once moved the host a Connection called
279+
// (token `tok@127.0.0.1/x`, endpoint `http://evil.example/`); such an
280+
// endpoint is now refused as ambiguous before any check of its scheme.
282281
const storage = memoryStorage();
283282
const client = await primedClient(storage);
284283
fetchMock.tokenResponse = jsonResponse(tokenBody({ apiEndpoint: 'http://tok@127.0.0.1/x@evil.example/' }));
285-
await expect(client.handleCallback('?code=CODE&state=S')).to.be.rejectedWith(/insecure|https/);
284+
await expect(client.handleCallback('?code=CODE&state=S')).to.be.rejectedWith(/ambiguous/);
286285
});
287286
});
288287

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/**
2+
* @license
3+
* [BSD-3-Clause](https://github.com/pryv/lib-js/blob/master/LICENSE)
4+
*/
5+
/* global describe, it, expect, pryv */
6+
7+
// An apiEndpoint is read the way `new URL()` reads it: a check of
8+
// `new URL(apiEndpoint).host` and the host `pryv.Connection` calls agree, or
9+
// the endpoint is refused.
10+
describe('[UTLP] apiEndpoint parsing', function () {
11+
const extract = (e) => pryv.utils.extractTokenAndAPIEndpoint(e);
12+
13+
it('[UTLP1] the token is the user part of the authority, the rest is kept', function () {
14+
expect(extract('https://tok@alice.example.test/')).to.eql({ endpoint: 'https://alice.example.test/', token: 'tok' });
15+
expect(extract('https://tok@example.test/alice/')).to.eql({ endpoint: 'https://example.test/alice/', token: 'tok' });
16+
expect(extract('https://tok@example.test:8443/alice')).to.eql({ endpoint: 'https://example.test:8443/alice/', token: 'tok' });
17+
expect(extract('http://tok@127.0.0.1:3000')).to.eql({ endpoint: 'http://127.0.0.1:3000/', token: 'tok' });
18+
expect(extract('https://alice.example.test')).to.eql({ endpoint: 'https://alice.example.test/', token: null });
19+
});
20+
21+
it('[UTLP2] an `@` after the authority is refused (it would move the host)', function () {
22+
for (const e of [
23+
'https://good.example.test/@evil.test/',
24+
'https://tok@good.example.test/p@evil.test/',
25+
'https://tok@good.example.test/x?y=@evil.test/',
26+
'https://tok@good.example.test/#@evil.test/',
27+
'https://good.example.test/?a=b@evil.test',
28+
'https://good.example.test?a@evil.test/',
29+
'https://good.example.test#a@evil.test/'
30+
]) {
31+
expect(() => extract(e), e).to.throw(/ambiguous/);
32+
// What a caller checks with new URL(): never the host a Connection would call.
33+
expect(new URL(e).host).to.equal('good.example.test');
34+
}
35+
});
36+
37+
it('[UTLP3] more than one `@`, a backslash, white space or a control character is refused', function () {
38+
for (const e of [
39+
'https://a@b@evil.test/',
40+
'https://tok@good.example.test\\@evil.test/',
41+
'https://tok@good.example.test\\evil.test/',
42+
'https://tok@good.example.test/ x',
43+
'https://tok@good.example.test/\tx',
44+
'https://tok@good.example.test/\u0000'
45+
]) {
46+
expect(() => extract(e), JSON.stringify(e)).to.throw(/ambiguous/);
47+
}
48+
});
49+
50+
it('[UTLP4] not a URL, no host, empty token: refused', function () {
51+
for (const e of ['blip', 'https://', 'https://@host.test/', 'https://tok@/', '//tok@host.test/', null, undefined, 42]) {
52+
expect(() => extract(e), String(e)).to.throw();
53+
}
54+
});
55+
56+
it('[UTLP5] what is accepted calls the host new URL() names', function () {
57+
for (const e of ['https://tok@alice.example.test/', 'https://tok@example.test:8443/alice/', 'http://tok@[::1]:3000/', 'https://ALICE.example.test/']) {
58+
const { endpoint } = extract(e);
59+
expect(new URL(endpoint).host, e).to.equal(new URL(e).host);
60+
expect(new pryv.Connection(e).endpoint).to.equal(endpoint);
61+
}
62+
});
63+
64+
it('[UTLP6] buildAPIEndpoint refuses a token that would change the URL', function () {
65+
for (const token of ['a@evil.test', 'a/b', 'a?b', 'a#b', 'a:b', 'a b', 'a\\b']) {
66+
expect(() => pryv.utils.buildAPIEndpoint({ token, endpoint: 'https://example.test/' }), token).to.throw(/Invalid token/);
67+
}
68+
const built = pryv.utils.buildAPIEndpoint({ token: 'ck1abc', endpoint: 'https://example.test/alice/' });
69+
expect(built).to.equal('https://ck1abc@example.test/alice/');
70+
expect(extract(built)).to.eql({ endpoint: 'https://example.test/alice/', token: 'ck1abc' });
71+
});
72+
73+
it('[UTLP7] only http(s) with a token, host, port and path of their own grammar; new URL() must agree', function () {
74+
for (const e of [
75+
'https://tok@host:99999/', 'https://good.test%40evil.test/', 'https://tok@good.test%2Fx/', 'https://[::1/',
76+
'https://[tok@::1]/', 'https://u:p@h.test/', 'https://good.test?x/', 'https://good.test#x', 'https://tok%40x@h.test/',
77+
'https://tok@good.test/a?b', 'https://tok@g\uff0food.test/', 'https://tok@good.test/<x>/', 'https://tok@good.test/a|b/'
78+
]) {
79+
expect(() => extract(e), e).to.throw(/ambiguous/);
80+
}
81+
for (const e of ['javascript://x.test/', 'data://x.test/', 'ws://tok@x.test/', 'file:///etc/']) {
82+
expect(() => extract(e), e).to.throw(/invalid URL format/);
83+
}
84+
expect(extract('https://tok@[::1]:3000/')).to.eql({ endpoint: 'https://[::1]:3000/', token: 'tok' });
85+
expect(extract('http://tok@pryv_core:3000/u/')).to.eql({ endpoint: 'http://pryv_core:3000/u/', token: 'tok' });
86+
expect(extract('HTTPS://tok@A.test/a/').token).to.equal('tok');
87+
});
88+
89+
it('[UTLP8] decomposeAPIEndpoint names no username for another host that ends like the template', function () {
90+
const tpl = 'https://{username}.pryv.me/';
91+
expect(pryv.utils.decomposeAPIEndpoint('https://tok@evil.test/x.pryv.me/', tpl)).to.eql({ token: 'tok', username: null, host: 'evil.test' });
92+
expect(pryv.utils.decomposeAPIEndpoint('https://tok@alice.pryv.me/', tpl)).to.eql({ token: 'tok', username: 'alice', host: 'pryv.me' });
93+
expect(pryv.utils.decomposeAPIEndpoint('https://tok@h.test/alice/', 'https://h.test/{username}/')).to.eql({ token: 'tok', username: 'alice', host: 'h.test' });
94+
});
95+
96+
it('[UTLP9] Service.buildAPIEndpoint refuses a username that would move the endpoint', function () {
97+
const info = { api: 'https://{username}.pryv.me/' };
98+
for (const username of ['evil.test/', 'a@evil.test', 'a.b', 'a:1', 'a b', '', null]) {
99+
expect(() => pryv.Service.buildAPIEndpoint(info, username, 'tok'), String(username)).to.throw(/Invalid username/);
100+
}
101+
expect(pryv.Service.buildAPIEndpoint(info, 'alice-1', 'tok')).to.equal('https://tok@alice-1.pryv.me/');
102+
});
103+
});

0 commit comments

Comments
 (0)