taler-typescript-core

Wallet core logic and WebUIs for various components
Log | Files | Refs | Submodules | README | LICENSE

commit 9c684ecde01f11b9d1721c1c31b63e202b9d8ba1
parent 80d2f5eeaf33ae443cb6d2c584e0df699c2bdb55
Author: Florian Dold <dold@taler.net>
Date:   Tue, 24 Nov 2026 13:55:41 +0100

taler-util: preserve service origins and payment URI fields

Bind service prefixes to the declared host and require colons in prefix
segments to be percent-encoded. Reject empty required IDs and preserve
NFC flags and mailbox schemes when serializing links.

Diffstat:
Mpackages/taler-util/src/payto.test.ts | 37+++++++++++++++++++++++++++++++++++++
Mpackages/taler-util/src/payto.ts | 102+++++++++++++++++++++++++++++++------------------------------------------------
Dpackages/taler-util/src/taleruri-roundtrip.test.ts | 101-------------------------------------------------------------------------------
Mpackages/taler-util/src/taleruri.test.ts | 203+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpackages/taler-util/src/taleruri.ts | 420+++++++++++++++++++++++++++----------------------------------------------------
5 files changed, 425 insertions(+), 438 deletions(-)

diff --git a/packages/taler-util/src/payto.test.ts b/packages/taler-util/src/payto.test.ts @@ -67,6 +67,43 @@ test("basic x-taler-bank payto string", (t) => { assert.strictEqual(result.account, "accountName"); }); +test("service directories retain their authority, port, casing and empty segments", () => { + assert.strictEqual( + Paytos.parseHostPortPath2("[::1]:8080", "//Store//Catalog%3a2026/", "http"), + "http://[::1]:8080///Store//Catalog%3a2026/", + ); + for (const invalid of [ + "", + "mail.example:bad", + "mail.example:65536", + "user@mail.example", + ]) { + assert.strictEqual( + Paytos.parseHostPortPath2(invalid, "Store"), + undefined, + invalid, + ); + } +}); + +test("bank payto parsing and construction agree on encoded service prefix colons", () => { + const uri = "payto://x-taler-bank/bank.example:8443/Bank%3A2026/alice"; + const parsed = Result.unpack(Paytos.fromString(uri)); + assert.strictEqual(parsed.targetType, PaytoType.TalerBank); + assert.strictEqual(parsed.url, "https://bank.example:8443/Bank%3A2026/"); + assert.strictEqual(Paytos.toFullString(parsed), uri); + assert.strictEqual(Paytos.fromString(uri.replace("%3A", ":")).tag, "error"); + const constructed = Paytos.createTalerBank( + "https://bank.example:8443/Bank:2026/" as HostPortPath, + "alice", + ); + assert.strictEqual(Paytos.toFullString(constructed), uri); + assert.strictEqual( + Paytos.toNormalizedString(constructed), + Paytos.toNormalizedString(parsed), + ); +}); + test("parsing payto and stringify again on normalized strings are unchanged", (t) => { const payto1 = "payto://iban/DE89370400440532013000?reciever-name=John%20Doe"; assert.strictEqual( diff --git a/packages/taler-util/src/payto.ts b/packages/taler-util/src/payto.ts @@ -32,7 +32,7 @@ import { import { TalerErrorCode } from "./taler-error-codes.js"; import { AmountString } from "./types-taler-common.js"; import { TransferSubject } from "./types-taler-prepared-transfer.js"; -import { URLSearchParams } from "./url.js"; +import { URL, URLSearchParams } from "./url.js"; const logger = new Logger("payto.ts"); @@ -285,73 +285,55 @@ export namespace Paytos { }); } } - /** - * Check hostname is a valid string with form $host:$port/$path like - * domain.com:22/some/path - * - * Return the canonical form. - * - * FIXME: new need a function that only takes una string: host+port+path and - * parse it without using URL to prevent parsing unnecessary components and - * better error reporting - * https://bugs.gnunet.org/view.php?id=10467 - * - * @param hostname - * @param path - * @param scheme - * @returns - */ + /** Build an HTTP(S) service URL from an authority and an encoded path. */ export function parseHostPortPath2( - hostname: string, - path: string | undefined, + authority: string, + path = "", scheme: "http" | "https" = "https", ): HostPortPath | undefined { - // maybe it should check that it doesn't contain search or hash? + // The authority contains only the host and optional port. A colon in a + // prefix segment must be percent-encoded, including in the first segment. + if (!authority || /[\s/@?#\\]/u.test(authority) || path.includes(":")) { + return undefined; + } try { - // https://url.spec.whatwg.org/#concept-basic-url-parser - if (path === undefined) { - path = ""; - } - if (!path.endsWith("/")) { - path = path + "/"; - } - const url = new URL(path, `${scheme}://${hostname.toLowerCase()}`); - url.search = ""; - url.password = ""; - url.username = ""; - url.hash = ""; + const url = new URL(`${scheme}://${authority}/`); + const pathname = "/" + path; + url.pathname = pathname.endsWith("/") ? pathname : pathname + "/"; return url.href as HostPortPath; } catch { return undefined; } } - function withoutScheme(h: HostPortPath): HostPortPath { + /** The first segment is the authority. Each following segment is a directory. */ + export function parseServiceBaseUrl( + [authority, ...prefix]: string[], + scheme: "http" | "https" = "https", + ): HostPortPath | undefined { + const path = prefix.length ? prefix.join("/") + "/" : ""; + return parseHostPortPath2(authority, path, scheme); + } + + function withoutScheme(h: HostPortPath): string { + const hostAndPath = h.replace(/^https?:\/\//, ""); + const slash = hostAndPath.indexOf("/"); + if (slash < 0) return hostAndPath; return ( - h.startsWith("http://") - ? h.substring(7) - : h.startsWith("https://") - ? h.substring(8) - : h - ) as HostPortPath; + hostAndPath.slice(0, slash) + + hostAndPath.slice(slash).replaceAll(":", "%3A") + ); } - /** - * Same as `parseHostPortPath2` but only takes one string. - * This should be the definitive signature. - * https://bugs.gnunet.org/view.php?id=10467 - * - * @param hostnameAndPath - * @returns - */ + /** Parse a host with an optional port and service prefix. */ export function parseHostPortPath( hostnameAndPath: string, + scheme: "http" | "https" = "https", ): HostPortPath | undefined { - const slashIdx = hostnameAndPath.indexOf("/"); - const host = - slashIdx < 0 ? hostnameAndPath : hostnameAndPath.slice(0, slashIdx); - const path = slashIdx < 0 ? "" : hostnameAndPath.slice(slashIdx + 1); - return parseHostPortPath2(host, path); + const slash = hostnameAndPath.indexOf("/"); + const host = slash < 0 ? hostnameAndPath : hostnameAndPath.slice(0, slash); + const path = slash < 0 ? "" : hostnameAndPath.slice(slash + 1); + return parseHostPortPath2(host, path, scheme); } /** @@ -517,7 +499,7 @@ export namespace Paytos { // segments. Both forms are built from the raw segments so that going // through a URL parser (which would lowercase or resolve) cannot change // H_PAYTO. - const segments = rawSegments ?? [host, account]; + const segments = rawSegments ?? [...host.split("/"), account]; const normalizedPath = `${segments[0].toLowerCase()}/${segments .slice(1) .join("/")}`; @@ -769,7 +751,7 @@ export namespace Paytos { }); } - const host = parseHostPortPath2(cs[0], cs.slice(1, -1).join("/")); + const host = parseServiceBaseUrl(cs.slice(0, -1)); if (!opts.ignoreComponentError && !host) { return Result.errorWithDetail(PaytoParseError.INVALID_TARGET_PATH, { pos: 0, @@ -801,7 +783,7 @@ export namespace Paytos { targetType, }); } - const exchange = parseHostPortPath2(cs[0], cs.slice(1, -1).join("/")); + const exchange = parseServiceBaseUrl(cs.slice(0, -1)); if (!opts.ignoreComponentError && !exchange) { return Result.errorWithDetail(PaytoParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -834,11 +816,7 @@ export namespace Paytos { targetType, }); } - const exchange = parseHostPortPath2( - cs[0], - cs.slice(1, -1).join("/"), - "http", - ); + const exchange = parseServiceBaseUrl(cs.slice(0, -1), "http"); if (!opts.ignoreComponentError && !exchange) { return Result.errorWithDetail(PaytoParseError.INVALID_TARGET_PATH, { pos: 0, @@ -888,7 +866,7 @@ export namespace Paytos { targetType, }); } - const host = parseHostPortPath2(cs[0], cs.slice(1, -1).join("/")); + const host = parseServiceBaseUrl(cs.slice(0, -1)); if (!opts.ignoreComponentError && !host) { return Result.errorWithDetail(PaytoParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -1032,7 +1010,7 @@ export namespace Paytos { const hostStr = (fields.bankHost || "") .trim() .replace(/^https?:\/\//, ""); - const host = parseHostPortPath2(hostStr, "") || (hostStr as HostPortPath); + const host = parseHostPortPath(hostStr) || (hostStr as HostPortPath); const acc = (fields.accountName || "").trim(); return toFullString(createTalerBank(host, acc, search)); } diff --git a/packages/taler-util/src/taleruri-roundtrip.test.ts b/packages/taler-util/src/taleruri-roundtrip.test.ts @@ -1,101 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2026 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -import { test } from "node:test"; -import assert from "node:assert"; -import { TalerUris, TalerUriAction } from "./taleruri.js"; -import { Result } from "./result.js"; - -const payUri = (orderId: string, sessionId = "sess") => ({ - type: TalerUriAction.Pay as const, - merchantBaseUrl: "https://m.example.com/" as any, - orderId, - sessionId, -}); - -test("pay URI: a component with structural characters round-trips", (t) => { - for (const orderId of ["a/b", "a?c=evil", "a#b", "a&b", "plain-01", "a b"]) { - const s = TalerUris.stringify(payUri(orderId)); - const r = TalerUris.parse(s); - assert.strictEqual( - r.tag, - "ok", - `parse failed for orderId ${orderId}: ${s}`, - ); - const v = Result.unpack(r) as any; - assert.strictEqual(v.orderId, orderId, `orderId not preserved: ${s}`); - // the merchant host must survive intact - assert.strictEqual(v.merchantBaseUrl, "https://m.example.com/", s); - } -}); - -test("pay URI: a dot-segment component cannot be represented", (t) => { - // "." and ".." are resolved away by the URL parser, even percent-encoded, - // so they cannot be a path segment and must be rejected rather than - // silently erasing the host. - assert.throws(() => TalerUris.stringify(payUri(".."))); - assert.throws(() => TalerUris.stringify(payUri("."))); -}); - -test("withdrawal-transfer-result URI round-trips", (t) => { - const parsed = TalerUris.parse( - "taler://withdrawal-transfer-result?ref=abc&status=success", - ); - assert.strictEqual(parsed.tag, "ok"); - const v = Result.unpack(parsed) as any; - assert.strictEqual(v.ref, "abc"); - assert.strictEqual(v.status, "success"); - - const s = TalerUris.stringify(v); - const reparsed = TalerUris.parse(s); - assert.strictEqual(reparsed.tag, "ok", `not re-parseable: ${s}`); - assert.deepStrictEqual(Result.unpack(reparsed), v); -}); - -test("withdrawal-transfer-result URI requires a ref", (t) => { - const r = TalerUris.parse( - "taler://withdrawal-transfer-result?status=success", - ); - assert.strictEqual(r.tag, "error"); -}); - -test("pay URI: control characters cannot erase the merchant host", (t) => { - // The WHATWG URL parser strips tab, LF and CR before parsing, so a - // component of ".." followed by one of them is not caught by the dot-segment - // guard and is resolved away together with the preceding path segment. - for (const orderId of ["..\t", "..\n", "..\r", "a\tb", "x\ny"]) { - const s = TalerUris.stringify(payUri(orderId)); - const r = TalerUris.parse(s); - assert.strictEqual(r.tag, "ok", `parse failed: ${JSON.stringify(s)}`); - const v = Result.unpack(r) as any; - assert.strictEqual(v.merchantBaseUrl, "https://m.example.com/", s); - assert.strictEqual(v.orderId, orderId, `orderId not preserved: ${s}`); - } -}); - -test("pay URI: an instance sub-path survives a hostile order id", (t) => { - const s = TalerUris.stringify({ - type: TalerUriAction.Pay, - merchantBaseUrl: "https://shop.example.com/instances/alice/" as any, - orderId: "..\t", - sessionId: "sess", - }); - const v = Result.unpack(TalerUris.parse(s)) as any; - assert.strictEqual( - v.merchantBaseUrl, - "https://shop.example.com/instances/alice/", - ); -}); diff --git a/packages/taler-util/src/taleruri.test.ts b/packages/taler-util/src/taleruri.test.ts @@ -1,6 +1,7 @@ /* This file is part of GNU Taler (C) 2019 GNUnet e.V. + (C) 2026 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -24,6 +25,7 @@ import { TalerErrorCode } from "./taler-error-codes.js"; import { canonicalizeMerchantInstanceUrl, TalerUriAction, + TalerUriParseError, TalerUris, } from "./taleruri.js"; import { @@ -196,6 +198,102 @@ const VALID_MAILBOX_KEY = "1".repeat(52) as EddsaPublicKeyString; } }); + const payUri = (orderId: string, sessionId = "sess") => ({ + type: TalerUriAction.Pay as const, + merchantBaseUrl: "https://m.example.com/" as HostPortPath, + orderId, + sessionId, + }); + + test("service prefix colons must be escaped and identifier colons remain literal", () => { + for (const prefix of ["Catalog:2026", "Shop/Catalog:2026"]) { + const uri = `taler://pay/shop.example:8443/${prefix}/Order:42/`; + const parsed = TalerUris.parse(uri); + assert.strictEqual(parsed.tag, "error"); + assert.strictEqual(parsed.error, TalerUriParseError.INVALID_TARGET_PATH); + assert.ok("pos" in parsed.detail); + assert.strictEqual(parsed.detail.pos, 0); + } + + const expected = "taler+http://pay/[::1]:8080/Catalog%3A2026//EN/Order:42/"; + const parsed = TalerUris.parseRestrictedOrThrow( + expected, + TalerUriAction.Pay, + ); + assert.strictEqual( + parsed.merchantBaseUrl, + "http://[::1]:8080/Catalog%3A2026//EN/", + ); + assert.strictEqual(parsed.orderId, "Order:42"); + assert.strictEqual(TalerUris.stringify(parsed), expected); + assert.strictEqual( + TalerUris.stringify({ + ...parsed, + merchantBaseUrl: "http://[::1]:8080/Catalog:2026//EN/" as HostPortPath, + }), + expected, + ); + }); + + test("pay URI: a component with structural characters round-trips", (t) => { + for (const orderId of [ + "a/b", + "a?c=evil", + "a#b", + "a&b", + "plain-01", + "a b", + ]) { + const s = TalerUris.stringify(payUri(orderId)); + const r = TalerUris.parse(s); + assert.strictEqual( + r.tag, + "ok", + `parse failed for orderId ${orderId}: ${s}`, + ); + const v = Result.unpack(r) as any; + assert.strictEqual(v.orderId, orderId, `orderId not preserved: ${s}`); + // the merchant host must survive intact + assert.strictEqual(v.merchantBaseUrl, "https://m.example.com/", s); + } + }); + + test("pay URI: a dot-segment component cannot be represented", (t) => { + // "." and ".." are resolved away by the URL parser, even percent-encoded, + // so they cannot be a path segment and must be rejected rather than + // silently erasing the host. + assert.throws(() => TalerUris.stringify(payUri(".."))); + assert.throws(() => TalerUris.stringify(payUri("."))); + }); + + test("pay URI: control characters cannot erase the merchant host", (t) => { + // The WHATWG URL parser strips tab, LF and CR before parsing, so a + // component of ".." followed by one of them is not caught by the dot-segment + // guard and is resolved away together with the preceding path segment. + for (const orderId of ["..\t", "..\n", "..\r", "a\tb", "x\ny"]) { + const s = TalerUris.stringify(payUri(orderId)); + const r = TalerUris.parse(s); + assert.strictEqual(r.tag, "ok", `parse failed: ${JSON.stringify(s)}`); + const v = Result.unpack(r) as any; + assert.strictEqual(v.merchantBaseUrl, "https://m.example.com/", s); + assert.strictEqual(v.orderId, orderId, `orderId not preserved: ${s}`); + } + }); + + test("pay URI: an instance sub-path survives a hostile order id", (t) => { + const s = TalerUris.stringify({ + type: TalerUriAction.Pay, + merchantBaseUrl: "https://shop.example.com/instances/alice/" as any, + orderId: "..\t", + sessionId: "sess", + }); + const v = Result.unpack(TalerUris.parse(s)) as any; + assert.strictEqual( + v.merchantBaseUrl, + "https://shop.example.com/instances/alice/", + ); + }); + test("taler pay URI (stringify)", (t) => { const url1 = TalerUris.stringify({ type: TalerUriAction.Pay, @@ -503,6 +601,24 @@ const VALID_MAILBOX_KEY = "1".repeat(52) as EddsaPublicKeyString; assert.deepStrictEqual(r1.templateId, "FEGHYJY48FEGU6WETYIOIDEDE2QW3OCZVY"); }); + test("payment and template links preserve true, false and absent NFC flags", () => { + for (const [action, path] of [ + [TalerUriAction.Pay, "Order-42/"], + [TalerUriAction.PayTemplate, "Lunch"], + ] as const) { + for (const [query, nfc] of [ + ["?nfc=1", true], + ["?nfc=0", false], + ["", undefined], + ] as const) { + const uri = `taler://${action}/shop.example/${path}${query}`; + const parsed = TalerUris.parseRestrictedOrThrow(uri, action); + assert.strictEqual(parsed.nfc, nfc); + assert.strictEqual(TalerUris.stringify(parsed), uri); + } + } + }); + test("taler pay template URI (stringify)", (t) => { const url1 = TalerUris.stringify({ type: TalerUriAction.PayTemplate, @@ -762,6 +878,34 @@ const VALID_MAILBOX_KEY = "1".repeat(52) as EddsaPublicKeyString; /** * Add contact */ + test("contact links keep the mailbox scheme and separate the identity from its service prefix", () => { + const key = "0".repeat(52); + for (const [prefix, scheme] of [ + ["taler", "https"], + ["taler+http", "http"], + ] as const) { + for (const path of ["/", "/MyMailbox/"]) { + const uri = `${prefix}://add-contact/email/bob/mail.example:8000${path}${key}`; + const contact = TalerUris.parseRestrictedOrThrow( + uri, + TalerUriAction.AddContact, + ); + assert.strictEqual( + contact.mailboxBaseUri, + `${scheme}://mail.example:8000${path}`, + ); + assert.strictEqual(TalerUris.stringify(contact), uri); + assert.strictEqual( + TalerUris.stringify({ + ...contact, + mailboxBaseUri: contact.mailboxBaseUri.slice(0, -1), + }), + uri, + ); + } + } + }); + test("taler add contact URI (stringify)", (t) => { const url = TalerUris.stringify({ type: TalerUriAction.AddContact, @@ -808,6 +952,28 @@ const VALID_MAILBOX_KEY = "1".repeat(52) as EddsaPublicKeyString; }); } +test("withdrawal-transfer-result URI round-trips", (t) => { + const parsed = TalerUris.parse( + "taler://withdrawal-transfer-result?ref=abc&status=success", + ); + assert.strictEqual(parsed.tag, "ok"); + const v = Result.unpack(parsed) as any; + assert.strictEqual(v.ref, "abc"); + assert.strictEqual(v.status, "success"); + + const s = TalerUris.stringify(v); + const reparsed = TalerUris.parse(s); + assert.strictEqual(reparsed.tag, "ok", `not re-parseable: ${s}`); + assert.deepStrictEqual(Result.unpack(reparsed), v); +}); + +test("withdrawal-transfer-result URI requires a ref", (t) => { + const r = TalerUris.parse( + "taler://withdrawal-transfer-result?status=success", + ); + assert.strictEqual(r.tag, "error"); +}); + test("parseAddContact keeps the mailbox sub-path", () => { const r = Result.orUndefined( TalerUris.parseRestricted( @@ -820,6 +986,43 @@ test("parseAddContact keeps the mailbox sub-path", () => { assert.deepStrictEqual(r.mailboxBaseUri, "https://mailbox.example.com/mb/"); }); +test("parsing and stringifying require identifiers but allow an empty payment session", () => { + const merchantBaseUrl = "https://shop.example/" as HostPortPath; + for (const [uri, value] of [ + [ + "taler://pay/shop.example//", + { type: TalerUriAction.Pay, merchantBaseUrl, orderId: "" }, + ], + [ + "taler://refund/shop.example//", + { type: TalerUriAction.Refund, merchantBaseUrl, orderId: "" }, + ], + [ + "taler://withdraw/bank.example/", + { + type: TalerUriAction.Withdraw, + bankIntegrationApiBaseUrl: "https://bank.example/" as HostPortPath, + withdrawalOperationId: "", + }, + ], + [ + "taler://pay-template/shop.example/", + { type: TalerUriAction.PayTemplate, merchantBaseUrl, templateId: "" }, + ], + ] as const) { + assert.deepStrictEqual(TalerUris.parse(uri), { + tag: "error", + error: TalerUriParseError.INVALID_TARGET_PATH, + detail: { uriType: value.type, pos: 1 }, + }); + assert.throws(() => TalerUris.stringify(value), /required.*identifier/i); + } + const uri = "taler://pay/shop.example/Order-42/"; + const payment = TalerUris.parseRestrictedOrThrow(uri, TalerUriAction.Pay); + assert.strictEqual(payment.sessionId, undefined); + assert.strictEqual(TalerUris.stringify(payment), uri); +}); + test("URI parsing rejects malformed financial capabilities and template fields", () => { for (const uri of [ "taler://pay-push/exchange.example/not-a-private-key", diff --git a/packages/taler-util/src/taleruri.ts b/packages/taler-util/src/taleruri.ts @@ -156,7 +156,7 @@ export enum TalerUriParseError { */ INVALID_PARAMETER, /** - * The taler action is unsupported. + * The URI is valid and denotes a different action than requested. */ UNEXPECTED_ACTION, } @@ -225,22 +225,26 @@ export namespace TalerUris { "withdrawal-transfer-result": true, }; - function asHost(s: HostPortPath): string { - const b = new URL(s); - return `${b.host}${b.pathname}`; + function servicePrefix(baseUrl: string): string { + const url = new URL(baseUrl); + const path = url.pathname.replaceAll(":", "%3A"); + return url.host + (path.endsWith("/") ? path : path + "/"); } function getTalerParamList(p: URI): [string, string][] { const result: [string, string][] = []; + function addFlag(name: string, value: boolean | undefined): void { + if (value !== undefined) result.push([name, value ? "1" : "0"]); + } + switch (p.type) { case TalerUriAction.Withdraw: { - if (p.externalConfirmation) { - result.push(["external-confirmation", "1"]); - } + addFlag("external-confirmation", p.externalConfirmation); return result; } case TalerUriAction.Pay: { + addFlag("nfc", p.nfc); if (p.claimToken) { result.push(["c", p.claimToken]); } @@ -281,12 +285,9 @@ export namespace TalerUris { if (p.summary) { result.push(["summary", p.summary]); } - if (p.editableAmount) { - result.push(["editable_amount", "1"]); - } - if (p.editableSummary) { - result.push(["editable_summary", "1"]); - } + addFlag("editable_amount", p.editableAmount); + addFlag("editable_summary", p.editableSummary); + addFlag("nfc", p.nfc); return result; } case TalerUriAction.DevExperiment: { @@ -330,42 +331,39 @@ export namespace TalerUris { case TalerUriAction.Restore: case TalerUriAction.DevExperiment: case TalerUriAction.WithdrawalTransferResult: - case TalerUriAction.AddContact: return TALER_PREFIX; + case TalerUriAction.AddContact: + return p.mailboxBaseUri.startsWith("http://") + ? TALER_HTTP_PREFIX + : TALER_PREFIX; default: assertUnreachable(p); } } function getTalerPath(p: URI): string { - /** - * After the host we should not add a / since the href - * already adds one - */ switch (p.type) { case TalerUriAction.Withdraw: - return `/${asHost(p.bankIntegrationApiBaseUrl)}${encodeUriSegment( + return `/${servicePrefix(p.bankIntegrationApiBaseUrl)}${encodeRequiredUriSegment( p.withdrawalOperationId, )}`; case TalerUriAction.Pay: // The session ID is the last path component of the URI and thus // cannot be omitted; an empty component means "no session". - return `/${asHost(p.merchantBaseUrl)}${encodeUriSegment( + return `/${servicePrefix(p.merchantBaseUrl)}${encodeRequiredUriSegment( p.orderId, )}/${encodeUriSegment(p.sessionId ?? "")}`; case TalerUriAction.Refund: // refund should end with a / - return `/${asHost(p.merchantBaseUrl)}${encodeUriSegment(p.orderId)}/`; + return `/${servicePrefix(p.merchantBaseUrl)}${encodeRequiredUriSegment(p.orderId)}/`; case TalerUriAction.PayTemplate: - return `/${asHost(p.merchantBaseUrl)}${encodeUriSegment(p.templateId)}`; + return `/${servicePrefix(p.merchantBaseUrl)}${encodeRequiredUriSegment(p.templateId)}`; case TalerUriAction.PayPush: - return `/${asHost(p.exchangeBaseUrl)}${encodeUriSegment(p.contractPriv)}`; case TalerUriAction.PayPull: - return `/${asHost(p.exchangeBaseUrl)}${encodeUriSegment(p.contractPriv)}`; + return `/${servicePrefix(p.exchangeBaseUrl)}${encodeUriSegment(p.contractPriv)}`; case TalerUriAction.AddExchange: - return `/${asHost(p.exchangeBaseUrl)}`; case TalerUriAction.WithdrawExchange: - return `/${asHost(p.exchangeBaseUrl)}`; + return `/${servicePrefix(p.exchangeBaseUrl)}`; case TalerUriAction.Restore: return `/${encodeUriSegment(p.walletRootPriv)}/${p.providers .map((d) => encodeURIComponent(d)) @@ -378,7 +376,7 @@ export namespace TalerUris { case TalerUriAction.AddContact: return `/${encodeUriSegment(p.aliasType)}/${encodeUriSegment( p.alias, - )}/${asHost(p.mailboxBaseUri as HostPortPath)}/${encodeUriSegment( + )}/${servicePrefix(p.mailboxBaseUri)}${encodeUriSegment( p.mailboxIdentity, )}`; default: @@ -402,67 +400,24 @@ export namespace TalerUris { ignoreComponentError?: boolean; } + /** + * pos identifies an action-specific field. A service URL and its prefix + * occupy one position regardless of the number of path segments. + */ export type InvalidTargetPathDetail = + | { uriType: TalerUriAction.Restore } + | { uriType: TalerUriAction.AddExchange; pos: 0 } | { - uriType: TalerUriAction.Restore; - } - | { - uriType: TalerUriAction.Pay; - } - | { - uriType: TalerUriAction.Withdraw; - } - | { - uriType: TalerUriAction.Refund; - pos: 0; - } - | { - uriType: TalerUriAction.Refund; - pos: 1; - } - | { - uriType: TalerUriAction.PayPull; - pos: 0; - } - | { - uriType: TalerUriAction.PayPull; - pos: 1; - } - | { - uriType: TalerUriAction.PayPush; - pos: 0; - } - | { - uriType: TalerUriAction.PayPush; - pos: 1; - } - | { - uriType: TalerUriAction.PayTemplate; - pos: 0; - } - | { - uriType: TalerUriAction.PayTemplate; - pos: 1; - } - | { - uriType: TalerUriAction.WithdrawExchange; - pos: 0; - } - | { - uriType: TalerUriAction.WithdrawExchange; - pos: 1; - } - | { - uriType: TalerUriAction.AddExchange; - pos: 0; - } - | { - uriType: TalerUriAction.AddContact; - pos: 0; - } - | { - uriType: TalerUriAction.AddContact; - pos: 1; + uriType: + | TalerUriAction.Pay + | TalerUriAction.Withdraw + | TalerUriAction.Refund + | TalerUriAction.PayPull + | TalerUriAction.PayPush + | TalerUriAction.PayTemplate + | TalerUriAction.WithdrawExchange + | TalerUriAction.AddContact; + pos: 0 | 1; }; export type ParseResult<T extends TalerUri = TalerUri> = @@ -489,12 +444,9 @@ export namespace TalerUris { */ export function parse(s: string, opts: PaytoParseOptions = {}): ParseResult { // check prefix - let isHttp = false; const prefixCheckStr = s.toLowerCase(); - if ( - !prefixCheckStr.startsWith(TALER_PREFIX) && - !(isHttp = prefixCheckStr.startsWith(TALER_HTTP_PREFIX)) - ) { + const isHttp = prefixCheckStr.startsWith(TALER_HTTP_PREFIX); + if (!isHttp && !prefixCheckStr.startsWith(TALER_PREFIX)) { return Result.error(TalerUriParseError.WRONG_PREFIX); } const scheme = isHttp ? ("http" as const) : ("https" as const); @@ -544,32 +496,31 @@ export namespace TalerUris { } // get URI components - const cs = targetPath.split("/"); + const segments = targetPath.split("/"); switch (uriType) { case TalerUriAction.Pay: - return parsePay(scheme, uriType, cs, params, opts); + return parsePay(scheme, uriType, segments, params, opts); case TalerUriAction.Withdraw: - return parseWithdraw(scheme, uriType, cs, params, opts); + return parseWithdraw(scheme, uriType, segments, params, opts); case TalerUriAction.Refund: - return parseRefund(scheme, uriType, cs, params, opts); + return parseRefund(scheme, uriType, segments, opts); case TalerUriAction.PayPull: - return parsePayPull(scheme, uriType, cs, params, opts); case TalerUriAction.PayPush: - return parsePayPush(scheme, uriType, cs, params, opts); + return parsePeerPayment(scheme, uriType, segments, opts); case TalerUriAction.PayTemplate: - return parsePayTemplate(scheme, uriType, cs, params, opts); + return parsePayTemplate(scheme, uriType, segments, params, opts); case TalerUriAction.Restore: - return parseRestore(scheme, uriType, cs, params, opts); + return parseRestore(scheme, uriType, segments); case TalerUriAction.DevExperiment: - return parseDevExperiment(scheme, uriType, cs, params, opts); + return parseDevExperiment(uriType, segments, params); case TalerUriAction.WithdrawExchange: - return parseWithdrawExchange(scheme, uriType, cs, params, opts); + return parseWithdrawExchange(scheme, uriType, segments, params, opts); case TalerUriAction.AddExchange: - return parseAddExchange(scheme, uriType, cs, params, opts); + return parseAddExchange(scheme, uriType, segments, opts); case TalerUriAction.WithdrawalTransferResult: - return parseWithdrawalTransferResult(scheme, uriType, cs, params); + return parseWithdrawalTransferResult(uriType, params); case TalerUriAction.AddContact: - return parseAddContact(scheme, uriType, cs, params); + return parseAddContact(scheme, uriType, segments, params); default: { assertUnreachable(uriType); } @@ -630,23 +581,19 @@ export namespace TalerUris { function parseWithdraw( scheme: "http" | "https", uriType: TalerUriAction.Withdraw, - cs: string[], + segments: string[], params: Record<string, string>, opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { // check number of segments - if (cs.length < 2) { + if (segments.length < 2) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } // get bank host - const bank = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1, -1).join("/"), - scheme, - ); + const bank = Paytos.parseServiceBaseUrl(segments.slice(0, -1), scheme); if (!opts.ignoreComponentError && !bank) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -656,7 +603,13 @@ function parseWithdraw( } // get operation id - const operationId = decodeUriSegment(cs[cs.length - 1]); + const operationId = decodeUriSegment(segments[segments.length - 1]); + if (!opts.ignoreComponentError && !operationId) { + return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { + pos: 1 as const, + uriType, + }); + } // get external confirmation const externalConfirmation = !params["external-confirmation"] ? undefined @@ -664,7 +617,7 @@ function parseWithdraw( return Result.of<TalerUri>({ type: TalerUriAction.Withdraw, - bankIntegrationApiBaseUrl: bank ?? (cs[0] as HostPortPath), + bankIntegrationApiBaseUrl: bank ?? (segments[0] as HostPortPath), withdrawalOperationId: operationId, externalConfirmation, }); @@ -673,23 +626,19 @@ function parseWithdraw( function parsePay( scheme: "http" | "https", uriType: TalerUriAction.Pay, - cs: string[], + segments: string[], params: Record<string, string>, opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { // check number of segments - if (cs.length < 3) { + if (segments.length < 3) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } // get merchant host - const merchant = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1, -2).join("/"), - scheme, - ); + const merchant = Paytos.parseServiceBaseUrl(segments.slice(0, -2), scheme); if (!opts.ignoreComponentError && !merchant) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -699,47 +648,44 @@ function parsePay( } // get order - const orderId = decodeUriSegment(cs[cs.length - 2]); + const orderId = decodeUriSegment(segments[segments.length - 2]); + if (!opts.ignoreComponentError && !orderId) { + return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { + pos: 1 as const, + uriType, + }); + } // get session; the merchant emits an empty last component for orders // that are not bound to a session, which is not a session ID - const sessionId = decodeUriSegment(cs[cs.length - 1]) || undefined; - - let nfc: boolean | undefined; - if ("nfc" in params) { - nfc = params["nfc"] === "1"; - } + const sessionId = + decodeUriSegment(segments[segments.length - 1]) || undefined; return Result.of<TalerUri>({ type: TalerUriAction.Pay, - merchantBaseUrl: merchant ?? (cs[0] as HostPortPath), + merchantBaseUrl: merchant ?? (segments[0] as HostPortPath), orderId, sessionId, claimToken: params["c"], noncePriv: params["n"], - nfc, + nfc: parseFlag(params["nfc"]), }); } -function parsePayPush( +function parsePeerPayment( scheme: "http" | "https", - uriType: TalerUriAction.PayPush, - cs: string[], - _params: Record<string, string>, + uriType: TalerUriAction.PayPush | TalerUriAction.PayPull, + segments: string[], opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { // check number of segments - if (cs.length < 2) { + if (segments.length < 2) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } // get exchange host - const exchange = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1, -1).join("/"), - scheme, - ); + const exchange = Paytos.parseServiceBaseUrl(segments.slice(0, -1), scheme); if (!opts.ignoreComponentError && !exchange) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -749,7 +695,7 @@ function parsePayPush( } // get contract priv - const contractPriv = decodeUriSegment(cs[cs.length - 1]); + const contractPriv = decodeUriSegment(segments[segments.length - 1]); if ( !opts.ignoreComponentError && @@ -762,54 +708,8 @@ function parsePayPush( } return Result.of({ - type: TalerUriAction.PayPush, - exchangeBaseUrl: exchange ?? (cs[0] as HostPortPath), - contractPriv: contractPriv as EddsaPrivateKeyString, - }); -} - -function parsePayPull( - scheme: "http" | "https", - uriType: TalerUriAction.PayPull, - cs: string[], - _params: Record<string, string>, - opts: TalerUris.PaytoParseOptions = {}, -): TalerUris.ParseResult { - // check number of segments - if (cs.length < 2) { - return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { - uriType, - }); - } - - // get exchange host - const exchange = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1, -1).join("/"), - scheme, - ); - if (!opts.ignoreComponentError && !exchange) { - return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { - pos: 0 as const, - uriType, - error: exchange, - }); - } - // get contract priv - const contractPriv = decodeUriSegment(cs[cs.length - 1]); - if ( - !opts.ignoreComponentError && - (!contractPriv || !isFixedSizeCrock(contractPriv, 32)) - ) { - return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { - pos: 1 as const, - uriType, - }); - } - - return Result.of({ - type: TalerUriAction.PayPull, - exchangeBaseUrl: exchange ?? (cs[0] as HostPortPath), + type: uriType, + exchangeBaseUrl: exchange ?? (segments[0] as HostPortPath), contractPriv: contractPriv as EddsaPrivateKeyString, }); } @@ -817,17 +717,16 @@ function parsePayPull( function parseRefund( scheme: "http" | "https", uriType: TalerUriAction.Refund, - cs: string[], - _params: Record<string, string>, + segments: string[], opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { // check number of segments - if (cs.length < 3) { + if (segments.length < 3) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } - if (cs[cs.length - 1]) { + if (segments[segments.length - 1]) { // last must be empty return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 1 as const, @@ -836,11 +735,7 @@ function parseRefund( } // get merchant host - const merchant = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1, -2).join("/"), - scheme, - ); + const merchant = Paytos.parseServiceBaseUrl(segments.slice(0, -2), scheme); if (!opts.ignoreComponentError && !merchant) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -850,10 +745,16 @@ function parseRefund( } // get order id - const orderId = decodeUriSegment(cs[cs.length - 2]); + const orderId = decodeUriSegment(segments[segments.length - 2]); + if (!opts.ignoreComponentError && !orderId) { + return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { + pos: 1 as const, + uriType, + }); + } return Result.of({ type: TalerUriAction.Refund, - merchantBaseUrl: merchant ?? (cs[0] as HostPortPath), + merchantBaseUrl: merchant ?? (segments[0] as HostPortPath), orderId, }); } @@ -861,23 +762,19 @@ function parseRefund( function parsePayTemplate( scheme: "http" | "https", uriType: TalerUriAction.PayTemplate, - cs: string[], + segments: string[], params: Record<string, string>, opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { // check number of segments - if (cs.length < 2) { + if (segments.length < 2) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } // get merchant host - const merchant = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1, -1).join("/"), - scheme, - ); + const merchant = Paytos.parseServiceBaseUrl(segments.slice(0, -1), scheme); if (!opts.ignoreComponentError && !merchant) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -885,7 +782,7 @@ function parsePayTemplate( error: merchant, }); } - const templateId = decodeUriSegment(cs[cs.length - 1]); + const templateId = decodeUriSegment(segments[segments.length - 1]); if (!opts.ignoreComponentError && !templateId) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 1 as const, @@ -905,53 +802,39 @@ function parsePayTemplate( amount = amountParam; } - let nfc: boolean | undefined; - if ("nfc" in params) { - nfc = params["nfc"] === "1"; - } - return Result.of({ type: TalerUriAction.PayTemplate, - merchantBaseUrl: merchant ?? (cs[0] as HostPortPath), + merchantBaseUrl: merchant ?? (segments[0] as HostPortPath), templateId, fulfillmentUrl: params["fulfillment_url"], sessionId: params["session_id"], amount, - editableAmount: truthyArg(params["editable_amount"]), - editableSummary: truthyArg(params["editable_summary"]), + editableAmount: parseFlag(params["editable_amount"]), + editableSummary: parseFlag(params["editable_summary"]), summary: params["summary"], - nfc, + nfc: parseFlag(params["nfc"]), }); } -function truthyArg(x: string | undefined): boolean | undefined { - if (x == null) { - return undefined; - } - if (x === "1") { - return true; - } - return false; +function parseFlag(value: string | undefined): boolean | undefined { + return value === undefined ? undefined : value === "1"; } function parseRestore( scheme: "http" | "https", uriType: TalerUriAction.Restore, - cs: string[], - _params: Record<string, string>, - _opts: TalerUris.PaytoParseOptions = {}, + segments: string[], ): TalerUris.ParseResult { // check number of segments - if (cs.length !== 2) { + if (segments.length !== 2) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } - const walletPriv = decodeUriSegment(cs[0]); // FIXME: validate private key + const walletPriv = decodeUriSegment(segments[0]); // FIXME: validate private key const providers: Array<HostPortPath> = []; - // const providers = new Array<HostPortPath>(); - for (const name of cs[1].split(",")) { + for (const name of segments[1].split(",")) { let url: string; try { url = decodeURIComponent(name); @@ -977,7 +860,12 @@ function parseRestore( const hostname = slashIdx < 0 ? withoutScheme : withoutScheme.slice(0, slashIdx); const path = slashIdx < 0 ? "" : withoutScheme.slice(slashIdx + 1); - const host = Paytos.parseHostPortPath2(hostname, path, thisScheme); + // A restore provider is a whole URL inside an encoded URI component. + const host = Paytos.parseHostPortPath2( + hostname, + path.replaceAll(":", "%3A"), + thisScheme, + ); if (host === undefined) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { uriType: TalerUriAction.Restore as const, @@ -989,25 +877,23 @@ function parseRestore( return Result.of({ type: TalerUriAction.Restore, providers, - walletRootPriv: walletPriv ?? (cs[0] as HostPortPath), + walletRootPriv: walletPriv, }); } function parseDevExperiment( - _scheme: "http" | "https", uriType: TalerUriAction.DevExperiment, - cs: string[], + segments: string[], params: Record<string, string>, - _opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { // check number of segments - if (cs.length !== 1) { + if (segments.length !== 1) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } - const devExperimentId = decodeUriSegment(cs[0]); + const devExperimentId = decodeUriSegment(segments[0]); return Result.of({ type: TalerUriAction.DevExperiment, @@ -1019,20 +905,12 @@ function parseDevExperiment( function parseWithdrawExchange( scheme: "http" | "https", uriType: TalerUriAction.WithdrawExchange, - cs: string[], + segments: string[], params: Record<string, string>, opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { - // check number of segments - if (cs.length < 1) { - return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { - uriType, - }); - } - - // FIXME: https://bugs.gnunet.org/view.php?id=10466 - // if (cs[cs.length-1]) { - if (cs.length > 1 && cs[cs.length - 1]) { + // Accept a bare host as well as the canonical trailing slash. + if (segments.length > 1 && segments[segments.length - 1]) { // last must be empty return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 1 as const, @@ -1041,11 +919,7 @@ function parseWithdrawExchange( } // get exchange host - const exchange = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1, -1).join("/"), - scheme, - ); + const exchange = Paytos.parseHostPortPath(segments.join("/"), scheme); if (!opts.ignoreComponentError && !exchange) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -1072,17 +946,14 @@ function parseWithdrawExchange( return Result.of({ type: TalerUriAction.WithdrawExchange, - exchangeBaseUrl: exchange ?? (cs[0] as HostPortPath), + exchangeBaseUrl: exchange ?? (segments[0] as HostPortPath), amount, }); } function parseWithdrawalTransferResult( - _scheme: "http" | "https", uriType: TalerUriAction.WithdrawalTransferResult, - _cs: string[], params: Record<string, string>, - _opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { const ref = params["ref"]; if (!ref) { @@ -1105,23 +976,18 @@ function parseWithdrawalTransferResult( function parseAddExchange( scheme: "http" | "https", uriType: TalerUriAction.AddExchange, - cs: string[], - params: Record<string, string>, + segments: string[], opts: TalerUris.PaytoParseOptions = {}, ): TalerUris.ParseResult { // check number of segments - if (cs.length === 1) { + if (segments.length === 1) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } // get exchange host - const exchange = Paytos.parseHostPortPath2( - cs[0], - cs.slice(1).join("/"), - scheme, - ); + const exchange = Paytos.parseHostPortPath(segments.join("/"), scheme); if (!opts.ignoreComponentError && !exchange) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 0 as const, @@ -1132,29 +998,28 @@ function parseAddExchange( return Result.of({ type: TalerUriAction.AddExchange, - exchangeBaseUrl: exchange ?? (cs[0] as HostPortPath), + exchangeBaseUrl: exchange ?? (segments[0] as HostPortPath), }); } function parseAddContact( scheme: "http" | "https", uriType: TalerUriAction.AddContact, - cs: string[], + segments: string[], params: Record<string, string>, ): TalerUris.ParseResult { // check number of segments - if (cs.length < 4) { + if (segments.length < 4) { return Result.errorWithDetail(TalerUriParseError.COMPONENTS_LENGTH, { uriType, }); } - const aliasType = decodeUriSegment(cs[0]); - const alias = decodeUriSegment(cs[1]); + const aliasType = decodeUriSegment(segments[0]); + const alias = decodeUriSegment(segments[1]); - const mailboxBaseUri = Paytos.parseHostPortPath2( - cs[2], - cs.slice(3, cs.length - 1).join("/"), + const mailboxBaseUri = Paytos.parseServiceBaseUrl( + segments.slice(2, -1), scheme, ); if (!mailboxBaseUri) { @@ -1164,7 +1029,7 @@ function parseAddContact( error: mailboxBaseUri, }); } - const mailboxIdentity = decodeUriSegment(cs[cs.length - 1]); + const mailboxIdentity = decodeUriSegment(segments[segments.length - 1]); if (!mailboxIdentity || !isFixedSizeCrock(mailboxIdentity, 32)) { return Result.errorWithDetail(TalerUriParseError.INVALID_TARGET_PATH, { pos: 1 as const, @@ -1322,6 +1187,11 @@ function encodeUriSegment(s: string): string { ); } +function encodeRequiredUriSegment(value: string): string { + if (!value) throw Error("a required Taler URI identifier is empty"); + return encodeUriSegment(value); +} + /** * Decode a single taler:// URI path segment. Falls back to the raw value for * input that is not valid percent-encoding, so parsing never throws on it.