@phibac/sdk 0.0.0-stage → 0.1.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/dist/dpop.js ADDED
@@ -0,0 +1,105 @@
1
+ // DPoP (RFC 9449): a non-extractable P-256 key pair kept in IndexedDB, and
2
+ // the proof JWT that shows possession of it on every request.
3
+ import { openDB } from "idb";
4
+ import { DEFAULT_BASE_URL } from "./brand.js";
5
+ const DB_NAME = "pb";
6
+ const DB_VERSION = 1;
7
+ /**
8
+ * openPbDB opens the SDK's database. Callers close it when done: a
9
+ * connection is opened per operation so no handle outlives the page's
10
+ * use of it.
11
+ */
12
+ export function openPbDB() {
13
+ return openDB(DB_NAME, DB_VERSION, {
14
+ upgrade(db) {
15
+ if (!db.objectStoreNames.contains("keys"))
16
+ db.createObjectStore("keys");
17
+ if (!db.objectStoreNames.contains("tokens"))
18
+ db.createObjectStore("tokens");
19
+ },
20
+ });
21
+ }
22
+ // ---- base64url ----
23
+ export function b64url(bytes) {
24
+ const u = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
25
+ let bin = "";
26
+ for (const b of u)
27
+ bin += String.fromCharCode(b);
28
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
29
+ }
30
+ /** randomToken returns n random bytes, base64url without padding. */
31
+ export function randomToken(n = 32) {
32
+ return b64url(crypto.getRandomValues(new Uint8Array(n)));
33
+ }
34
+ export async function sha256(s) {
35
+ return b64url(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
36
+ }
37
+ const utf8 = (v) => b64url(new TextEncoder().encode(JSON.stringify(v)));
38
+ // ---- the key ----
39
+ const ALG = { name: "ECDSA", namedCurve: "P-256" };
40
+ /**
41
+ * getOrCreateKey returns this browser's DPoP key pair for the server at
42
+ * baseUrl (one key per server origin, shared by every app on it), creating
43
+ * and storing it on first use. The private key is generated with
44
+ * extractable false: it can sign but can never be read, so a stolen
45
+ * IndexedDB copy or XSS cannot take it off the device.
46
+ *
47
+ * Safe when several tabs call it at once: the "is there a key, else store
48
+ * mine" step is one readwrite transaction, which IndexedDB serialises, so
49
+ * every caller ends up with the first key stored.
50
+ */
51
+ export async function getOrCreateKey(baseUrl = DEFAULT_BASE_URL) {
52
+ const origin = new URL(baseUrl).origin;
53
+ const db = await openPbDB();
54
+ try {
55
+ const existing = await db.get("keys", origin);
56
+ if (existing)
57
+ return existing;
58
+ const fresh = (await crypto.subtle.generateKey(ALG, false, ["sign", "verify"]));
59
+ const tx = db.transaction("keys", "readwrite");
60
+ const raced = await tx.store.get(origin);
61
+ if (!raced)
62
+ await tx.store.put(fresh, origin);
63
+ await tx.done;
64
+ return raced ?? fresh;
65
+ }
66
+ finally {
67
+ db.close();
68
+ }
69
+ }
70
+ // The public JWK of a key, computed once per key object.
71
+ const publicJwks = new WeakMap();
72
+ function publicJwk(key) {
73
+ let p = publicJwks.get(key);
74
+ if (!p) {
75
+ // Public keys are always exportable, whatever the pair's extractable flag.
76
+ p = crypto.subtle.exportKey("jwk", key).then(({ kty, crv, x, y }) => ({ kty, crv, x, y }));
77
+ publicJwks.set(key, p);
78
+ }
79
+ return p;
80
+ }
81
+ // ---- the proof ----
82
+ /**
83
+ * createProof returns a DPoP proof (compact JWS, ES256) for one request:
84
+ * header {typ "dpop+jwt", alg "ES256", jwk}, claims htm (upper-case
85
+ * method), htu (url without query and fragment), iat (seconds, the device
86
+ * clock plus clockOffsetMs), a random jti and, when accessToken is given,
87
+ * ath (base64url SHA-256 of the token).
88
+ */
89
+ export async function createProof(keys, method, url, accessToken, clockOffsetMs = 0) {
90
+ const u = new URL(url);
91
+ const header = { typ: "dpop+jwt", alg: "ES256", jwk: await publicJwk(keys.publicKey) };
92
+ const claims = {
93
+ jti: randomToken(16),
94
+ htm: method.toUpperCase(),
95
+ htu: u.origin + u.pathname,
96
+ iat: Math.floor((Date.now() + clockOffsetMs) / 1000),
97
+ };
98
+ if (accessToken !== undefined)
99
+ claims.ath = await sha256(accessToken);
100
+ const input = `${utf8(header)}.${utf8(claims)}`;
101
+ // WebCrypto's ECDSA signature is already the raw r||s (64 bytes) JWS needs.
102
+ const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, keys.privateKey, new TextEncoder().encode(input));
103
+ return `${input}.${b64url(sig)}`;
104
+ }
105
+ //# sourceMappingURL=dpop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dpop.js","sourceRoot":"","sources":["../src/dpop.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8DAA8D;AAC9D,OAAO,EAAE,MAAM,EAAoC,MAAM,KAAK,CAAC;AAC/D,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAiB9C,MAAM,OAAO,GAAG,IAAI,CAAC;AACrB,MAAM,UAAU,GAAG,CAAC,CAAC;AAErB;;;;GAIG;AACH,MAAM,UAAU,QAAQ;IACtB,OAAO,MAAM,CAAO,OAAO,EAAE,UAAU,EAAE;QACvC,OAAO,CAAC,EAAE;YACR,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC;gBAAE,EAAE,CAAC,iBAAiB,CAAC,MAAM,CAAC,CAAC;YACxE,IAAI,CAAC,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBAAE,EAAE,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC;QAC9E,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,sBAAsB;AAEtB,MAAM,UAAU,MAAM,CAAC,KAA+B;IACpD,MAAM,CAAC,GAAG,KAAK,YAAY,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACtE,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,KAAK,MAAM,CAAC,IAAI,CAAC;QAAE,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IACjD,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G,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IACvB,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC;IACvF,MAAM,MAAM,GAAoC;QAC9C,GAAG,EAAE,WAAW,CAAC,EAAE,CAAC;QACpB,GAAG,EAAE,MAAM,CAAC,WAAW,EAAE;QACzB,GAAG,EAAE,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,QAAQ;QAC1B,GAAG,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,aAAa,CAAC,GAAG,IAAI,CAAC;KACrD,CAAC;IACF,IAAI,WAAW,KAAK,SAAS;QAAE,MAAM,CAAC,GAAG,GAAG,MAAM,MAAM,CAAC,WAAW,CAAC,CAAC;IACtE,MAAM,KAAK,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;IAChD,4EAA4E;IAC5E,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,IAAI,CAAC,UAAU,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3H,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;AACnC,CAAC"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * PbError is every error the SDK throws. code is a server error code (see
3
+ * the errors section of the agent docs) or one of the SDK's own: network,
4
+ * popup_blocked, sign_in_cancelled, access_denied. message says what went
5
+ * wrong, hint how to fix it, and extra holds every other field of the
6
+ * server's error body (for example reason, serverTime, consentUrl) plus
7
+ * retryAfter (seconds) on rate_limited.
8
+ */
9
+ export declare class PbError extends Error {
10
+ code: string;
11
+ hint: string;
12
+ extra: Record<string, unknown>;
13
+ constructor(code: string, message: string, hint?: string, extra?: Record<string, unknown>);
14
+ }
15
+ /** The hint for every "sign in again" situation. */
16
+ export declare const SIGN_IN_HINT = "Call connect() (or signIn()) again from a click or key handler so the user can sign in to pb.";
17
+ /**
18
+ * errorFromResponse turns a failed response into a PbError. The server's
19
+ * body is {"error": {"code", "message", "hint", ...extra}}; a body that is
20
+ * not of that form becomes code "internal" with the HTTP status in extra.
21
+ */
22
+ export declare function errorFromResponse(res: Response): Promise<PbError>;
package/dist/errors.js ADDED
@@ -0,0 +1,55 @@
1
+ import { BRAND } from "./brand.js";
2
+ /**
3
+ * PbError is every error the SDK throws. code is a server error code (see
4
+ * the errors section of the agent docs) or one of the SDK's own: network,
5
+ * popup_blocked, sign_in_cancelled, access_denied. message says what went
6
+ * wrong, hint how to fix it, and extra holds every other field of the
7
+ * server's error body (for example reason, serverTime, consentUrl) plus
8
+ * retryAfter (seconds) on rate_limited.
9
+ */
10
+ export class PbError extends Error {
11
+ code;
12
+ hint;
13
+ extra;
14
+ constructor(code, message, hint = "", extra = {}) {
15
+ super(message);
16
+ this.name = "PbError";
17
+ this.code = code;
18
+ this.hint = hint;
19
+ this.extra = extra;
20
+ }
21
+ }
22
+ /** The hint for every "sign in again" situation. */
23
+ export const SIGN_IN_HINT = `Call connect() (or signIn()) again from a click or key handler so the user can sign in to ${BRAND}.`;
24
+ /**
25
+ * errorFromResponse turns a failed response into a PbError. The server's
26
+ * body is {"error": {"code", "message", "hint", ...extra}}; a body that is
27
+ * not of that form becomes code "internal" with the HTTP status in extra.
28
+ */
29
+ export async function errorFromResponse(res) {
30
+ let body;
31
+ try {
32
+ body = await res.json();
33
+ }
34
+ catch {
35
+ body = undefined;
36
+ }
37
+ const extra = {};
38
+ let err;
39
+ const e = body?.error;
40
+ if (e && typeof e === "object" && typeof e.code === "string") {
41
+ const { code, message, hint, ...rest } = e;
42
+ Object.assign(extra, rest);
43
+ err = new PbError(code, typeof message === "string" ? message : "", typeof hint === "string" ? hint : "", extra);
44
+ }
45
+ else {
46
+ extra.status = res.status;
47
+ err = new PbError("internal", `${BRAND} answered with HTTP ${res.status} and no error details.`, "Retry later; if it keeps failing, check the server's base URL.", extra);
48
+ }
49
+ const retryAfter = Number(res.headers.get("Retry-After"));
50
+ if (res.status === 429 && res.headers.has("Retry-After") && Number.isFinite(retryAfter)) {
51
+ extra.retryAfter = retryAfter;
52
+ }
53
+ return err;
54
+ }
55
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAEnC;;;;;;;GAOG;AACH,MAAM,OAAO,OAAQ,SAAQ,KAAK;IAChC,IAAI,CAAS;IACb,IAAI,CAAS;IACb,KAAK,CAA0B;IAE/B,YAAY,IAAY,EAAE,OAAe,EAAE,IAAI,GAAG,EAAE,EAAE,KAAK,GAA4B,EAAE;QACvF,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAED,oDAAoD;AACpD,MAAM,CAAC,MAAM,YAAY,GAAG,6FAA6F,KAAK,GAAG,CAAC;AAElI;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,GAAa;IACnD,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC;QACH,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,IAAI,GAAG,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,KAAK,GAA4B,EAAE,CAAC;IAC1C,IAAI,GAAY,CAAC;IACjB,MAAM,CAAC,GAAI,IAAwC,EAAE,KAAK,CAAC;IAC3D,IAAI,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAQ,CAAwB,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QACrF,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,GAAG,CAA4B,CAAC;QACtE,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAC3B,GAAG,GAAG,IAAI,OAAO,CAAC,IAAc,EAAE,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC7H,CAAC;SAAM,CAAC;QACN,KAAK,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;QAC1B,GAAG,GAAG,IAAI,OAAO,CACf,UAAU,EACV,GAAG,KAAK,uBAAuB,GAAG,CAAC,MAAM,wBAAwB,EACjE,gEAAgE,EAChE,KAAK,CACN,CAAC;IACJ,CAAC;IACD,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC;IAC1D,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;QACxF,KAAK,CAAC,UAAU,GAAG,UAAU,CAAC;IAChC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { Net } from "./queue.js";
2
+ export declare class Files {
3
+ private readonly net;
4
+ constructor(net: Net);
5
+ /**
6
+ * upload stores blob as a file of a record in collection and resolves with
7
+ * its file ID (f_...), to be kept in a fileRef field. The bytes go
8
+ * straight to the signed upload URL with Content-Type and no
9
+ * Authorization or DPoP header.
10
+ */
11
+ upload(blob: Blob, opts: {
12
+ collection: string;
13
+ rkey?: string;
14
+ }): Promise<string>;
15
+ /** url resolves with a short-lived download URL for the file. */
16
+ url(fileId: string): Promise<string>;
17
+ /**
18
+ * delete removes the file at once and frees its storage. Only the app
19
+ * that owns the file's collection may delete it (forbidden otherwise); an
20
+ * unknown or already deleted file is not_found. Records whose fields name
21
+ * the file are not changed: clear those fields yourself. It works when the
22
+ * account is full or read-only. Not queued: offline it rejects.
23
+ */
24
+ delete(fileId: string): Promise<void>;
25
+ }
package/dist/files.js ADDED
@@ -0,0 +1,65 @@
1
+ // Files: upload a blob (request an upload URL, PUT the bytes to it, mark
2
+ // it complete), get a short-lived download URL, and delete a file. Uploads
3
+ // and deletes are never queued: offline, or on any failure, they reject
4
+ // with a PbError.
5
+ import { BRAND } from "./brand.js";
6
+ import { PbError, errorFromResponse } from "./errors.js";
7
+ const offline = () => new PbError("network", `Cannot upload a file to ${BRAND} while offline.`, "Upload again once the device is back online; uploads are not queued.");
8
+ const offlineDelete = () => new PbError("network", `Cannot delete a file on ${BRAND} while offline.`, "Delete it again once the device is back online; file deletes are not queued.");
9
+ export class Files {
10
+ net;
11
+ constructor(net) {
12
+ this.net = net;
13
+ }
14
+ /**
15
+ * upload stores blob as a file of a record in collection and resolves with
16
+ * its file ID (f_...), to be kept in a fileRef field. The bytes go
17
+ * straight to the signed upload URL with Content-Type and no
18
+ * Authorization or DPoP header.
19
+ */
20
+ async upload(blob, opts) {
21
+ if (!(blob instanceof Blob))
22
+ throw new PbError("invalid_request", "files.upload needs a Blob or File.", "Pass the file from an <input type=file> or a Blob.");
23
+ if (!this.net.deviceOnline)
24
+ throw offline();
25
+ const mime = blob.type || "application/octet-stream";
26
+ const body = { size: blob.size, mime, collection: opts.collection };
27
+ if (opts.rkey !== undefined)
28
+ body.rkey = opts.rkey;
29
+ const res = await this.net.request("POST", "/v1/files", body);
30
+ if (typeof res?.fileId !== "string" || typeof res.uploadUrl !== "string") {
31
+ throw new PbError("invalid_response", `${BRAND} returned no upload URL.`, "Check that baseUrl points at the server.");
32
+ }
33
+ let put;
34
+ try {
35
+ put = await fetch(res.uploadUrl, { method: "PUT", headers: { "Content-Type": mime }, body: blob });
36
+ }
37
+ catch {
38
+ throw new PbError("network", `The file upload to ${BRAND} failed.`, "Check the network connection, then upload again.");
39
+ }
40
+ if (!put.ok)
41
+ throw await errorFromResponse(put);
42
+ await this.net.request("POST", `/v1/files/${encodeURIComponent(res.fileId)}/complete`);
43
+ return res.fileId;
44
+ }
45
+ /** url resolves with a short-lived download URL for the file. */
46
+ async url(fileId) {
47
+ const res = await this.net.request("GET", `/v1/files/${encodeURIComponent(fileId)}`, undefined, { Accept: "application/json" });
48
+ if (typeof res?.url !== "string")
49
+ throw new PbError("invalid_response", `${BRAND} returned no download URL.`, "Check that baseUrl points at the server.");
50
+ return res.url;
51
+ }
52
+ /**
53
+ * delete removes the file at once and frees its storage. Only the app
54
+ * that owns the file's collection may delete it (forbidden otherwise); an
55
+ * unknown or already deleted file is not_found. Records whose fields name
56
+ * the file are not changed: clear those fields yourself. It works when the
57
+ * account is full or read-only. Not queued: offline it rejects.
58
+ */
59
+ async delete(fileId) {
60
+ if (!this.net.deviceOnline)
61
+ throw offlineDelete();
62
+ await this.net.request("DELETE", `/v1/files/${encodeURIComponent(fileId)}`);
63
+ }
64
+ }
65
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"files.js","sourceRoot":"","sources":["../src/files.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,2EAA2E;AAC3E,wEAAwE;AACxE,kBAAkB;AAClB,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAGzD,MAAM,OAAO,GAAG,GAA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http.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { Auth } from "./auth.js";
2
+ import { PbError } from "./errors.js";
3
+ /** What attempt needs from Auth: proofs, and the clock correction. */
4
+ export interface ProofSigner {
5
+ proof(method: string, url: string, accessToken?: string): Promise<string>;
6
+ setServerTime(serverTime: string): void;
7
+ }
8
+ /**
9
+ * REQUEST_TIMEOUT_MS bounds every API request (sending it and reading the
10
+ * whole response). A request that takes longer is abandoned and fails as
11
+ * PbError "network", which the queue and catch-up retry.
12
+ */
13
+ export declare const REQUEST_TIMEOUT_MS = 30000;
14
+ export type Outcome = {
15
+ ok: true;
16
+ res: Response;
17
+ } | {
18
+ ok: false;
19
+ err: PbError;
20
+ };
21
+ /**
22
+ * attempt sends one request with a new DPoP proof for exactly this method
23
+ * and URL, plus "Authorization: DPoP <token>" when accessToken is given and
24
+ * a JSON body when body is not undefined. A failed response comes back as
25
+ * a PbError; a network failure is thrown as PbError "network".
26
+ */
27
+ export declare function attempt(signer: ProofSigner, method: string, url: string, body?: unknown, accessToken?: string, extraHeaders?: Record<string, string>, signal?: AbortSignal): Promise<Outcome>;
28
+ /**
29
+ * readJSON returns the parsed JSON body of a successful response, or
30
+ * undefined for an empty body. A body that is not JSON (for example a proxy's
31
+ * HTML page) is PbError invalid_response, never a raw SyntaxError.
32
+ */
33
+ export declare function readJSON(res: Response): Promise<unknown>;
34
+ /**
35
+ * clockError returns the server's time when err rejected a DPoP proof
36
+ * because the device clock is wrong (reason dpop_iat), else undefined.
37
+ */
38
+ export declare function clockError(err: PbError): string | undefined;
39
+ export declare class Http {
40
+ private readonly auth;
41
+ private readonly base;
42
+ constructor(auth: Auth, baseUrl: string);
43
+ /**
44
+ * request calls path (e.g. "/v1/records") on the server and returns the
45
+ * parsed JSON response (undefined for an empty body). On 401 it retries
46
+ * exactly once: with the server's time when the proof's iat was refused
47
+ * (dpop_iat), otherwise after refreshing the access token. A second
48
+ * failure, and every other error, is thrown as a PbError. headers are
49
+ * added to the request (e.g. Accept). Each attempt times out after
50
+ * REQUEST_TIMEOUT_MS; signal cancels the request (both fail as network).
51
+ */
52
+ request<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>, signal?: AbortSignal): Promise<T>;
53
+ }
package/dist/http.js ADDED
@@ -0,0 +1,130 @@
1
+ import { BRAND } from "./brand.js";
2
+ import { PbError, errorFromResponse } from "./errors.js";
3
+ /**
4
+ * REQUEST_TIMEOUT_MS bounds every API request (sending it and reading the
5
+ * whole response). A request that takes longer is abandoned and fails as
6
+ * PbError "network", which the queue and catch-up retry.
7
+ */
8
+ export const REQUEST_TIMEOUT_MS = 30_000;
9
+ /**
10
+ * attempt sends one request with a new DPoP proof for exactly this method
11
+ * and URL, plus "Authorization: DPoP <token>" when accessToken is given and
12
+ * a JSON body when body is not undefined. A failed response comes back as
13
+ * a PbError; a network failure is thrown as PbError "network".
14
+ */
15
+ export async function attempt(signer, method, url, body, accessToken, extraHeaders = {}, signal) {
16
+ method = method.toUpperCase();
17
+ const headers = { ...extraHeaders, DPoP: await signer.proof(method, url, accessToken) };
18
+ if (accessToken !== undefined)
19
+ headers.Authorization = `DPoP ${accessToken}`;
20
+ const init = { method, headers };
21
+ if (body !== undefined) {
22
+ headers["Content-Type"] = "application/json";
23
+ init.body = JSON.stringify(body);
24
+ }
25
+ // One controller per request: aborted by the timeout or by the caller's signal.
26
+ const ac = new AbortController();
27
+ let timedOut = false;
28
+ const timer = setTimeout(() => {
29
+ timedOut = true;
30
+ ac.abort();
31
+ }, REQUEST_TIMEOUT_MS);
32
+ const cancel = () => ac.abort();
33
+ if (signal?.aborted)
34
+ ac.abort();
35
+ else
36
+ signal?.addEventListener("abort", cancel, { once: true });
37
+ init.signal = ac.signal;
38
+ let res;
39
+ try {
40
+ const sent = await fetch(url, init);
41
+ // Read the body inside the timeout too, then hand on a complete response.
42
+ const text = await sent.text();
43
+ res = new Response(text === "" && (sent.status === 204 || sent.status === 304) ? null : text, {
44
+ status: sent.status,
45
+ statusText: sent.statusText,
46
+ headers: sent.headers,
47
+ });
48
+ }
49
+ catch {
50
+ throw new PbError("network", timedOut
51
+ ? `${BRAND} at ${new URL(url).origin} did not answer within ${REQUEST_TIMEOUT_MS / 1000} seconds.`
52
+ : ac.signal.aborted
53
+ ? `The request to ${BRAND} was cancelled.`
54
+ : `Could not reach ${BRAND} at ${new URL(url).origin}.`, "Check the network connection and the base URL, then retry.");
55
+ }
56
+ finally {
57
+ clearTimeout(timer);
58
+ signal?.removeEventListener("abort", cancel);
59
+ }
60
+ if (res.ok)
61
+ return { ok: true, res };
62
+ return { ok: false, err: await errorFromResponse(res) };
63
+ }
64
+ /**
65
+ * readJSON returns the parsed JSON body of a successful response, or
66
+ * undefined for an empty body. A body that is not JSON (for example a proxy's
67
+ * HTML page) is PbError invalid_response, never a raw SyntaxError.
68
+ */
69
+ export async function readJSON(res) {
70
+ let text;
71
+ try {
72
+ text = await res.text();
73
+ }
74
+ catch {
75
+ throw new PbError("network", `The response from ${BRAND} was cut off.`, "Check the network connection, then retry.");
76
+ }
77
+ if (text === "")
78
+ return undefined;
79
+ try {
80
+ return JSON.parse(text);
81
+ }
82
+ catch {
83
+ throw new PbError("invalid_response", `${BRAND} answered with a body that is not JSON (HTTP ${res.status}).`, "Check that baseUrl points at the server and not at a proxy or web page.", { status: res.status });
84
+ }
85
+ }
86
+ /**
87
+ * clockError returns the server's time when err rejected a DPoP proof
88
+ * because the device clock is wrong (reason dpop_iat), else undefined.
89
+ */
90
+ export function clockError(err) {
91
+ const t = err.extra.serverTime;
92
+ if (err.code === "unauthorized" && err.extra.reason === "dpop_iat" && typeof t === "string" && !Number.isNaN(Date.parse(t))) {
93
+ return t;
94
+ }
95
+ return undefined;
96
+ }
97
+ export class Http {
98
+ auth;
99
+ base;
100
+ constructor(auth, baseUrl) {
101
+ this.auth = auth;
102
+ this.base = baseUrl.replace(/\/+$/, "");
103
+ }
104
+ /**
105
+ * request calls path (e.g. "/v1/records") on the server and returns the
106
+ * parsed JSON response (undefined for an empty body). On 401 it retries
107
+ * exactly once: with the server's time when the proof's iat was refused
108
+ * (dpop_iat), otherwise after refreshing the access token. A second
109
+ * failure, and every other error, is thrown as a PbError. headers are
110
+ * added to the request (e.g. Accept). Each attempt times out after
111
+ * REQUEST_TIMEOUT_MS; signal cancels the request (both fail as network).
112
+ */
113
+ async request(method, path, body, headers, signal) {
114
+ const url = this.base + path;
115
+ let token = await this.auth.accessToken();
116
+ let out = await attempt(this.auth, method, url, body, token, headers, signal);
117
+ if (!out.ok && out.err.code === "unauthorized") {
118
+ const serverTime = clockError(out.err);
119
+ if (serverTime)
120
+ this.auth.setServerTime(serverTime);
121
+ else
122
+ token = await this.auth.refresh(token);
123
+ out = await attempt(this.auth, method, url, body, token, headers, signal);
124
+ }
125
+ if (!out.ok)
126
+ throw out.err;
127
+ return (await readJSON(out.res));
128
+ }
129
+ }
130
+ //# sourceMappingURL=http.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAQzD;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAIzC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,MAAmB,EACnB,MAAc,EACd,GAAW,EACX,IAAc,EACd,WAAoB,EACpB,YAAY,GAA2B,EAAE,EACzC,MAAoB;IAEpB,MAAM,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;IAC9B,MAAM,OAAO,GAA2B,EAAE,GAAG,YAAY,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,CAAC;IAChH,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,CAAC,aAAa,GAAG,QAAQ,WAAW,EAAE,CA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CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;YAC/C,MAAM,UAAU,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YACvC,IAAI,UAAU;gBAAE,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;;gBAC/C,KAAK,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC5C,GAAG,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;QAC5E,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,EAAE;YAAE,MAAM,GAAG,CAAC,GAAG,CAAC;QAC3B,OAAO,CAAC,MAAM,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,CAAM,CAAC;IACxC,CAAC;CACF"}
@@ -0,0 +1,90 @@
1
+ import { PbError } from "./errors.js";
2
+ export { PbError };
3
+ export interface Backend {
4
+ collection<T>(name: string, opts?: {
5
+ versions?: number[];
6
+ schemaMajor?: number;
7
+ }): Collection<T>;
8
+ files: {
9
+ upload(blob: Blob, opts: {
10
+ collection: string;
11
+ rkey?: string;
12
+ }): Promise<string>;
13
+ url(fileId: string): Promise<string>;
14
+ delete(fileId: string): Promise<void>;
15
+ };
16
+ onConflict(cb: (e: {
17
+ op: QueuedOp;
18
+ error: PbError;
19
+ localData: unknown;
20
+ }) => void): () => void;
21
+ /**
22
+ * online: the device is online and the last request reached the server.
23
+ * pending: the number of queued writes. problem: set while something the
24
+ * user must fix stops the queue or the live connection (storage_full,
25
+ * trial_ended, app_suspended, account_closed, or consent_required for a
26
+ * subscribed collection the app may not read); undefined otherwise.
27
+ */
28
+ status(): {
29
+ online: boolean;
30
+ pending: number;
31
+ problem?: PbError;
32
+ };
33
+ signOut(): Promise<void>;
34
+ }
35
+ export interface PbRecord<T> {
36
+ id: string;
37
+ collection: string;
38
+ rkey: string;
39
+ data: T;
40
+ rev: number;
41
+ status: "pending" | "synced";
42
+ createdAt: string;
43
+ updatedAt: string;
44
+ }
45
+ export interface Collection<T> {
46
+ create(data: T): Promise<PbRecord<T>>;
47
+ update(rkey: string, patch: Partial<T>): Promise<PbRecord<T>>;
48
+ delete(rkey: string): Promise<void>;
49
+ get(rkey: string): Promise<PbRecord<T> | null>;
50
+ list(): Promise<PbRecord<T>[]>;
51
+ where(field: string, op: "==" | "!=" | "<" | "<=" | ">" | ">=" | "in", value: unknown): Query<T>;
52
+ orderBy(field: string, dir?: "asc" | "desc"): Query<T>;
53
+ subscribe(cb: (records: PbRecord<T>[]) => void): () => void;
54
+ requestAccess(): Promise<boolean>;
55
+ }
56
+ export interface Query<T> {
57
+ where: Collection<T>["where"];
58
+ orderBy: Collection<T>["orderBy"];
59
+ limit(n: number): Query<T>;
60
+ get(): Promise<PbRecord<T>[]>;
61
+ subscribe(cb: (records: PbRecord<T>[]) => void): () => void;
62
+ }
63
+ export interface QueuedOp {
64
+ opId: string;
65
+ kind: "create" | "update" | "delete";
66
+ collection: string;
67
+ rkey: string;
68
+ input: {
69
+ schemaMajor?: number;
70
+ baseRev?: number;
71
+ data?: unknown;
72
+ };
73
+ }
74
+ /**
75
+ * connect signs the user in if needed and returns their backend for the
76
+ * app. Call it from a click or key handler: when no sign-in is stored it
77
+ * opens the sign-in popup, which browsers allow only inside a user gesture.
78
+ *
79
+ * Whether a sign-in is stored is known only after an IndexedDB read, so a
80
+ * blank popup is opened first, synchronously, and then either sent to the
81
+ * sign-in page or closed again. Outside a gesture (navigator.userActivation
82
+ * says so) no popup is opened: a stored sign-in still works, and a missing
83
+ * one rejects with popup_blocked. No network request is needed when a
84
+ * sign-in is stored, so connect() works offline.
85
+ */
86
+ export declare function connect(opts: {
87
+ app: string;
88
+ baseUrl?: string;
89
+ schemaMajors?: Record<string, number>;
90
+ }): Promise<Backend>;