@ohauthcat/react-native 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.js ADDED
@@ -0,0 +1,67 @@
1
+ import { OhAuthCatError } from "./errors.js";
2
+ const URI_RE = /^([a-zA-Z][a-zA-Z0-9+.-]*):(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/;
3
+ export function parseUri(s) {
4
+ const m = URI_RE.exec(s);
5
+ if (!m)
6
+ return null;
7
+ const authority = m[2] ?? "";
8
+ const hostPort = authority.slice(authority.lastIndexOf("@") + 1);
9
+ const pm = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(hostPort);
10
+ return {
11
+ scheme: (m[1] ?? "").toLowerCase(),
12
+ host: (pm?.[1] ?? "").toLowerCase(),
13
+ port: pm?.[2] ?? "",
14
+ path: m[3] ?? "",
15
+ query: m[4] ?? "",
16
+ fragment: m[5] ?? null,
17
+ };
18
+ }
19
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
20
+ function invalid(msg) {
21
+ return OhAuthCatError.client("invalid_configuration", msg);
22
+ }
23
+ export function resolveConfig(o) {
24
+ const origin = parseUri(o.loginOrigin);
25
+ if (!origin ||
26
+ origin.host === "" ||
27
+ !(origin.scheme === "https" ||
28
+ (origin.scheme === "http" && LOOPBACK.has(origin.host)))) {
29
+ throw invalid("loginOrigin must be an https URL");
30
+ }
31
+ const clientId = o.clientId.trim();
32
+ if (clientId === "")
33
+ throw invalid("clientId is required");
34
+ const r = parseUri(o.redirectUri);
35
+ if (!r || r.fragment !== null) {
36
+ throw invalid("redirectUri must be absolute and carry no fragment");
37
+ }
38
+ if (r.scheme === "http" && !LOOPBACK.has(r.host)) {
39
+ throw invalid("redirectUri must not be plain http");
40
+ }
41
+ const mode = o.mode ?? { kind: "user_management" };
42
+ if (mode.kind === "oauth" && mode.environmentId.trim() === "") {
43
+ throw invalid("environmentId is required in oauth mode");
44
+ }
45
+ const base = o.loginOrigin.replace(/\/+$/, "");
46
+ const issuer = mode.kind === "oauth" ? `${base}/oauth/${mode.environmentId}` : base;
47
+ return {
48
+ origin: base,
49
+ clientId,
50
+ redirectUri: o.redirectUri,
51
+ mode,
52
+ scopes: o.scopes ?? ["openid", "profile", "email"],
53
+ issuer,
54
+ authorizationEndpoint: mode.kind === "oauth"
55
+ ? `${issuer}/authorize`
56
+ : `${base}/user_management/authorize`,
57
+ tokenEndpoint: mode.kind === "oauth"
58
+ ? `${issuer}/token`
59
+ : `${base}/user_management/token`,
60
+ revocationEndpoint: mode.kind === "oauth"
61
+ ? `${issuer}/revoke`
62
+ : `${base}/user_management/revoke`,
63
+ endSessionEndpoint: mode.kind === "oauth"
64
+ ? `${issuer}/logout`
65
+ : `${base}/user_management/logout`,
66
+ };
67
+ }
@@ -0,0 +1,8 @@
1
+ export declare function utf8(s: string): Uint8Array;
2
+ export declare function utf8Decode(b: Uint8Array): string;
3
+ export declare function base64UrlEncode(b: Uint8Array): string;
4
+ /** Decodes base64url (padding and the standard alphabet tolerated); null if invalid. */
5
+ export declare function base64UrlDecode(input: string): Uint8Array | null;
6
+ /** SHA-256 (FIPS 180-4). */
7
+ export declare function sha256(msg: Uint8Array): Uint8Array;
8
+ export declare function constantTimeEqual(a: string, b: string): boolean;
@@ -0,0 +1,148 @@
1
+ // Pure-TS encoding and hashing, so the flows run on any JS engine
2
+ // (Hermes has no WebCrypto subtle digest).
3
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
4
+ export function utf8(s) {
5
+ const out = [];
6
+ for (const ch of s) {
7
+ const c = ch.codePointAt(0) ?? 0;
8
+ if (c < 0x80)
9
+ out.push(c);
10
+ else if (c < 0x800)
11
+ out.push(0xc0 | (c >> 6), 0x80 | (c & 63));
12
+ else if (c < 0x10000)
13
+ out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
14
+ else
15
+ out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));
16
+ }
17
+ return Uint8Array.from(out);
18
+ }
19
+ export function utf8Decode(b) {
20
+ let s = "";
21
+ for (let i = 0; i < b.length;) {
22
+ const c = b[i] ?? 0;
23
+ let cp;
24
+ let n;
25
+ if (c < 0x80)
26
+ [cp, n] = [c, 1];
27
+ else if (c >> 5 === 6)
28
+ [cp, n] = [c & 31, 2];
29
+ else if (c >> 4 === 14)
30
+ [cp, n] = [c & 15, 3];
31
+ else
32
+ [cp, n] = [c & 7, 4];
33
+ for (let j = 1; j < n; j++)
34
+ cp = (cp << 6) | ((b[i + j] ?? 0) & 63);
35
+ s += String.fromCodePoint(cp);
36
+ i += n;
37
+ }
38
+ return s;
39
+ }
40
+ export function base64UrlEncode(b) {
41
+ let s = "";
42
+ for (let i = 0; i < b.length; i += 3) {
43
+ const n = ((b[i] ?? 0) << 16) | ((b[i + 1] ?? 0) << 8) | (b[i + 2] ?? 0);
44
+ const chars = [18, 12, 6, 0].map((sh) => ALPHABET[(n >> sh) & 63] ?? "");
45
+ s += chars.slice(0, Math.min(4, b.length - i + 1)).join("");
46
+ }
47
+ return s;
48
+ }
49
+ /** Decodes base64url (padding and the standard alphabet tolerated); null if invalid. */
50
+ export function base64UrlDecode(input) {
51
+ const s = input.replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
52
+ if (s.length % 4 === 1)
53
+ return null;
54
+ const out = [];
55
+ let buf = 0;
56
+ let bits = 0;
57
+ for (const ch of s) {
58
+ const v = ALPHABET.indexOf(ch);
59
+ if (v < 0)
60
+ return null;
61
+ buf = (buf << 6) | v;
62
+ bits += 6;
63
+ if (bits >= 8) {
64
+ bits -= 8;
65
+ out.push((buf >> bits) & 0xff);
66
+ }
67
+ }
68
+ return Uint8Array.from(out);
69
+ }
70
+ const K = [
71
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
72
+ 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
73
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
74
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
75
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
76
+ 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
77
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
78
+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
79
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
80
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
81
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
82
+ ];
83
+ /** SHA-256 (FIPS 180-4). */
84
+ export function sha256(msg) {
85
+ const len = msg.length;
86
+ const padded = new Uint8Array(((len + 9 + 63) >> 6) << 6);
87
+ padded.set(msg);
88
+ padded[len] = 0x80;
89
+ const bitLen = len * 8;
90
+ const view = new DataView(padded.buffer);
91
+ view.setUint32(padded.length - 8, Math.floor(bitLen / 0x100000000));
92
+ view.setUint32(padded.length - 4, bitLen >>> 0);
93
+ const h = [
94
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,
95
+ 0x1f83d9ab, 0x5be0cd19,
96
+ ];
97
+ const w = new Array(64).fill(0);
98
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
99
+ for (let off = 0; off < padded.length; off += 64) {
100
+ for (let i = 0; i < 16; i++)
101
+ w[i] = view.getUint32(off + i * 4);
102
+ for (let i = 16; i < 64; i++) {
103
+ const a = w[i - 15] ?? 0;
104
+ const b = w[i - 2] ?? 0;
105
+ const s0 = rotr(a, 7) ^ rotr(a, 18) ^ (a >>> 3);
106
+ const s1 = rotr(b, 17) ^ rotr(b, 19) ^ (b >>> 10);
107
+ w[i] = ((w[i - 16] ?? 0) + s0 + (w[i - 7] ?? 0) + s1) >>> 0;
108
+ }
109
+ const at = (i) => h[i] ?? 0;
110
+ let a = at(0), b = at(1), c = at(2), d = at(3);
111
+ let e = at(4), f = at(5), g = at(6), hh = at(7);
112
+ for (let i = 0; i < 64; i++) {
113
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
114
+ const ch = (e & f) ^ (~e & g);
115
+ const t1 = (hh + S1 + ch + (K[i] ?? 0) + (w[i] ?? 0)) >>> 0;
116
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
117
+ const maj = (a & b) ^ (a & c) ^ (b & c);
118
+ const t2 = (S0 + maj) >>> 0;
119
+ hh = g;
120
+ g = f;
121
+ f = e;
122
+ e = (d + t1) >>> 0;
123
+ d = c;
124
+ c = b;
125
+ b = a;
126
+ a = (t1 + t2) >>> 0;
127
+ }
128
+ const add = [a, b, c, d, e, f, g, hh];
129
+ for (let i = 0; i < 8; i++)
130
+ h[i] = ((h[i] ?? 0) + (add[i] ?? 0)) >>> 0;
131
+ }
132
+ const out = new Uint8Array(32);
133
+ const ov = new DataView(out.buffer);
134
+ h.forEach((x, i) => {
135
+ ov.setUint32(i * 4, x);
136
+ });
137
+ return out;
138
+ }
139
+ export function constantTimeEqual(a, b) {
140
+ const x = utf8(a);
141
+ const y = utf8(b);
142
+ if (x.length !== y.length)
143
+ return false;
144
+ let diff = 0;
145
+ for (let i = 0; i < x.length; i++)
146
+ diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
147
+ return diff === 0;
148
+ }
@@ -0,0 +1,41 @@
1
+ /** Stable codes: the OhAuthCat error catalogue plus RFC 6749 OAuth codes. */
2
+ export declare const ErrorCodes: {
3
+ readonly invalidRequest: "invalid_request";
4
+ readonly invalidClient: "invalid_client";
5
+ readonly invalidGrant: "invalid_grant";
6
+ readonly unsupportedGrantType: "unsupported_grant_type";
7
+ readonly invalidScope: "invalid_scope";
8
+ readonly accessDenied: "access_denied";
9
+ readonly serverError: "server_error";
10
+ readonly loginRequired: "login_required";
11
+ readonly consentRequired: "consent_required";
12
+ readonly redirectUriNotAllowed: "redirect_uri_not_allowed";
13
+ readonly refreshTokenReused: "refresh_token_reused";
14
+ readonly userBlocked: "user_blocked";
15
+ readonly userCredentialsInvalid: "user_credentials_invalid";
16
+ readonly userCodeInvalid: "user_code_invalid";
17
+ readonly userFactorInvalid: "user_factor_invalid";
18
+ readonly mfaRequired: "mfa_required";
19
+ readonly signInBlocked: "sign_in_blocked";
20
+ readonly botChallengeFailed: "bot_challenge_failed";
21
+ readonly oauthThirdPartyDenied: "oauth_third_party_denied";
22
+ readonly organizationNotFound: "organization_not_found";
23
+ readonly rateLimited: "rate_limited";
24
+ };
25
+ /** SDK-side failure kinds (no server code involved). */
26
+ export type ClientErrorKind = "invalid_configuration" | "cancelled" | "redirect_mismatch" | "state_mismatch" | "issuer_mismatch" | "missing_code" | "invalid_id_token"
27
+ /** The sign-in asked for an organization and the token is for another one, or none. */
28
+ | "organization_mismatch" | "not_signed_in" | "network" | "invalid_response" | "storage" | "passkey_unavailable" | "native_module_missing";
29
+ /** Every error the SDK throws. `code` is a server code or a client kind. */
30
+ export declare class OhAuthCatError extends Error {
31
+ readonly name = "OhAuthCatError";
32
+ readonly code: string;
33
+ readonly status: number;
34
+ readonly server: boolean;
35
+ constructor(code: string, message: string, status?: number, server?: boolean);
36
+ static client(kind: ClientErrorKind, detail?: string): OhAuthCatError;
37
+ static fromServer(code: string, status: number): OhAuthCatError;
38
+ /** True when the session is gone and the user must sign in again. */
39
+ get requiresSignIn(): boolean;
40
+ }
41
+ export declare function isOhAuthCatError(e: unknown): e is OhAuthCatError;
package/dist/errors.js ADDED
@@ -0,0 +1,57 @@
1
+ /** Stable codes: the OhAuthCat error catalogue plus RFC 6749 OAuth codes. */
2
+ export const ErrorCodes = {
3
+ invalidRequest: "invalid_request",
4
+ invalidClient: "invalid_client",
5
+ invalidGrant: "invalid_grant",
6
+ unsupportedGrantType: "unsupported_grant_type",
7
+ invalidScope: "invalid_scope",
8
+ accessDenied: "access_denied",
9
+ serverError: "server_error",
10
+ loginRequired: "login_required",
11
+ consentRequired: "consent_required",
12
+ redirectUriNotAllowed: "redirect_uri_not_allowed",
13
+ refreshTokenReused: "refresh_token_reused",
14
+ userBlocked: "user_blocked",
15
+ userCredentialsInvalid: "user_credentials_invalid",
16
+ userCodeInvalid: "user_code_invalid",
17
+ userFactorInvalid: "user_factor_invalid",
18
+ mfaRequired: "mfa_required",
19
+ signInBlocked: "sign_in_blocked",
20
+ botChallengeFailed: "bot_challenge_failed",
21
+ oauthThirdPartyDenied: "oauth_third_party_denied",
22
+ organizationNotFound: "organization_not_found",
23
+ rateLimited: "rate_limited",
24
+ };
25
+ const SIGN_IN_AGAIN = new Set([
26
+ ErrorCodes.invalidGrant,
27
+ "pkce_verification_failed",
28
+ ErrorCodes.refreshTokenReused,
29
+ ErrorCodes.userBlocked,
30
+ ErrorCodes.loginRequired,
31
+ ]);
32
+ /** Every error the SDK throws. `code` is a server code or a client kind. */
33
+ export class OhAuthCatError extends Error {
34
+ name = "OhAuthCatError";
35
+ code;
36
+ status;
37
+ server;
38
+ constructor(code, message, status = 0, server = false) {
39
+ super(message);
40
+ this.code = code;
41
+ this.status = status;
42
+ this.server = server;
43
+ }
44
+ static client(kind, detail) {
45
+ return new OhAuthCatError(kind, detail ? `${kind}: ${detail}` : kind);
46
+ }
47
+ static fromServer(code, status) {
48
+ return new OhAuthCatError(code, `server error ${code} (${String(status)})`, status, true);
49
+ }
50
+ /** True when the session is gone and the user must sign in again. */
51
+ get requiresSignIn() {
52
+ return this.server && SIGN_IN_AGAIN.has(this.code);
53
+ }
54
+ }
55
+ export function isOhAuthCatError(e) {
56
+ return e instanceof OhAuthCatError;
57
+ }
package/dist/flow.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { ResolvedConfig } from "./config.js";
2
+ import { OhAuthCatError } from "./errors.js";
3
+ import type { FetchLike } from "./platform.js";
4
+ export declare function pkceChallenge(verifier: string): string;
5
+ export declare function formEncode(form: Record<string, string>): string;
6
+ export declare function parseQuery(q: string): Map<string, string>;
7
+ export interface AuthorizationRequest {
8
+ url: string;
9
+ state: string;
10
+ nonce: string;
11
+ verifier: string;
12
+ organizationId?: string;
13
+ }
14
+ export declare function buildAuthorizationRequest(c: ResolvedConfig, secrets: {
15
+ state: string;
16
+ nonce: string;
17
+ verifier: string;
18
+ }, opts?: {
19
+ organizationId?: string;
20
+ prompt?: string;
21
+ }): AuthorizationRequest;
22
+ /** Validates the browser callback and returns the code. */
23
+ export declare function codeFromCallback(c: ResolvedConfig, req: AuthorizationRequest, callback: string): string;
24
+ export interface TokenSet {
25
+ accessToken: string;
26
+ refreshToken: string | null;
27
+ idToken: string | null;
28
+ /** Epoch milliseconds when the access token expires. */
29
+ expiresAt: number;
30
+ }
31
+ export interface User {
32
+ id: string;
33
+ email: string | null;
34
+ emailVerified: boolean | null;
35
+ name: string | null;
36
+ organizationId: string | null;
37
+ role: string | null;
38
+ roles: string[];
39
+ permissions: string[];
40
+ sessionId: string | null;
41
+ }
42
+ export declare function serializeTokens(t: TokenSet): string;
43
+ export declare function deserializeTokens(s: string): TokenSet | null;
44
+ /**
45
+ * Decoded JWT claims. The ID token comes straight from the token endpoint
46
+ * over TLS, so its signature is not checked on the device (OIDC Core
47
+ * §3.1.3.7); iss, aud, exp and nonce are.
48
+ */
49
+ export declare function decodeJwt(jwt: string): Record<string, unknown>;
50
+ export declare function validateIdToken(claims: Record<string, unknown>, c: {
51
+ issuer: string;
52
+ clientId: string;
53
+ }, nonce: string | null, nowMs: number, leewaySec?: number): void;
54
+ export declare function userFromClaims(claims: Record<string, unknown>): User | null;
55
+ export declare function errorFromBody(status: number, body: string): OhAuthCatError;
56
+ export declare function postForm(fetchImpl: FetchLike, url: string, form: Record<string, string>): Promise<{
57
+ status: number;
58
+ body: string;
59
+ }>;
60
+ export declare function tokenRequest(fetchImpl: FetchLike, c: ResolvedConfig, form: Record<string, string>, nowMs: number, previousRefresh: string | null): Promise<TokenSet>;
package/dist/flow.js ADDED
@@ -0,0 +1,226 @@
1
+ import { parseUri } from "./config.js";
2
+ import { base64UrlDecode, base64UrlEncode, constantTimeEqual, sha256, utf8, utf8Decode, } from "./encoding.js";
3
+ import { OhAuthCatError } from "./errors.js";
4
+ export function pkceChallenge(verifier) {
5
+ return base64UrlEncode(sha256(utf8(verifier)));
6
+ }
7
+ const enc = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
8
+ export function formEncode(form) {
9
+ return Object.keys(form)
10
+ .sort()
11
+ .map((k) => `${enc(k)}=${enc(form[k] ?? "")}`)
12
+ .join("&");
13
+ }
14
+ export function parseQuery(q) {
15
+ const out = new Map();
16
+ if (q === "")
17
+ return out;
18
+ for (const pair of q.split("&")) {
19
+ const i = pair.indexOf("=");
20
+ const dec = (s) => decodeURIComponent(s.replace(/\+/g, " "));
21
+ const k = dec(i < 0 ? pair : pair.slice(0, i));
22
+ if (!out.has(k))
23
+ out.set(k, i < 0 ? "" : dec(pair.slice(i + 1)));
24
+ }
25
+ return out;
26
+ }
27
+ export function buildAuthorizationRequest(c, secrets, opts = {}) {
28
+ const q = {
29
+ response_type: "code",
30
+ client_id: c.clientId,
31
+ redirect_uri: c.redirectUri,
32
+ code_challenge: pkceChallenge(secrets.verifier),
33
+ code_challenge_method: "S256",
34
+ state: secrets.state,
35
+ nonce: secrets.nonce,
36
+ };
37
+ if (c.mode.kind === "oauth")
38
+ q["scope"] = c.scopes.join(" ");
39
+ const org = opts.organizationId?.trim();
40
+ if (org)
41
+ q["organization_id"] = org;
42
+ if (opts.prompt)
43
+ q["prompt"] = opts.prompt;
44
+ const req = {
45
+ url: `${c.authorizationEndpoint}?${formEncode(q)}`,
46
+ ...secrets,
47
+ };
48
+ if (org)
49
+ req.organizationId = org;
50
+ return req;
51
+ }
52
+ /** Validates the browser callback and returns the code. */
53
+ export function codeFromCallback(c, req, callback) {
54
+ const cb = parseUri(callback);
55
+ const want = parseUri(c.redirectUri);
56
+ if (!cb ||
57
+ !want ||
58
+ cb.scheme !== want.scheme ||
59
+ cb.host !== want.host ||
60
+ cb.port !== want.port ||
61
+ cb.path !== want.path) {
62
+ throw OhAuthCatError.client("redirect_mismatch");
63
+ }
64
+ let params;
65
+ try {
66
+ params = parseQuery(cb.query);
67
+ }
68
+ catch {
69
+ throw OhAuthCatError.client("redirect_mismatch");
70
+ }
71
+ const state = params.get("state");
72
+ if (state === undefined || !constantTimeEqual(state, req.state)) {
73
+ throw OhAuthCatError.client("state_mismatch");
74
+ }
75
+ const iss = params.get("iss");
76
+ if (iss !== undefined && iss !== c.issuer)
77
+ throw OhAuthCatError.client("issuer_mismatch");
78
+ const err = params.get("error");
79
+ if (err)
80
+ throw OhAuthCatError.fromServer(err, 0);
81
+ const code = params.get("code");
82
+ if (!code)
83
+ throw OhAuthCatError.client("missing_code");
84
+ return code;
85
+ }
86
+ function isRecord(v) {
87
+ return typeof v === "object" && v !== null && !Array.isArray(v);
88
+ }
89
+ function parseJson(s) {
90
+ try {
91
+ const v = JSON.parse(s);
92
+ return isRecord(v) ? v : null;
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ const str = (o, k) => {
99
+ const v = o[k];
100
+ return typeof v === "string" ? v : null;
101
+ };
102
+ const strs = (o, k) => {
103
+ const v = o[k];
104
+ if (Array.isArray(v))
105
+ return v.filter((x) => typeof x === "string");
106
+ if (typeof v === "string")
107
+ return v.split(" ").filter((x) => x !== "");
108
+ return [];
109
+ };
110
+ export function serializeTokens(t) {
111
+ return JSON.stringify(t);
112
+ }
113
+ export function deserializeTokens(s) {
114
+ const o = parseJson(s);
115
+ if (!o)
116
+ return null;
117
+ const accessToken = str(o, "accessToken");
118
+ const expiresAt = o["expiresAt"];
119
+ if (!accessToken || typeof expiresAt !== "number")
120
+ return null;
121
+ return {
122
+ accessToken,
123
+ refreshToken: str(o, "refreshToken"),
124
+ idToken: str(o, "idToken"),
125
+ expiresAt,
126
+ };
127
+ }
128
+ /**
129
+ * Decoded JWT claims. The ID token comes straight from the token endpoint
130
+ * over TLS, so its signature is not checked on the device (OIDC Core
131
+ * §3.1.3.7); iss, aud, exp and nonce are.
132
+ */
133
+ export function decodeJwt(jwt) {
134
+ const parts = jwt.split(".");
135
+ const payload = parts.length === 3 ? base64UrlDecode(parts[1] ?? "") : null;
136
+ const claims = payload ? parseJson(utf8Decode(payload)) : null;
137
+ if (!claims)
138
+ throw OhAuthCatError.client("invalid_id_token", "malformed");
139
+ return claims;
140
+ }
141
+ export function validateIdToken(claims, c, nonce, nowMs, leewaySec = 60) {
142
+ const fail = (why) => OhAuthCatError.client("invalid_id_token", why);
143
+ if (str(claims, "iss") !== c.issuer)
144
+ throw fail("iss");
145
+ const aud = strs(claims, "aud");
146
+ if (!aud.includes(c.clientId))
147
+ throw fail("aud");
148
+ if (aud.length > 1 && str(claims, "azp") !== c.clientId)
149
+ throw fail("azp");
150
+ const exp = claims["exp"];
151
+ if (typeof exp !== "number" || (exp + leewaySec) * 1000 <= nowMs)
152
+ throw fail("exp");
153
+ if (nonce !== null) {
154
+ const got = str(claims, "nonce");
155
+ if (got === null || !constantTimeEqual(got, nonce))
156
+ throw fail("nonce");
157
+ }
158
+ if (!str(claims, "sub"))
159
+ throw fail("sub");
160
+ }
161
+ export function userFromClaims(claims) {
162
+ const id = str(claims, "sub");
163
+ if (!id)
164
+ return null;
165
+ const ev = claims["email_verified"];
166
+ return {
167
+ id,
168
+ email: str(claims, "email"),
169
+ emailVerified: typeof ev === "boolean" ? ev : null,
170
+ name: str(claims, "name"),
171
+ organizationId: str(claims, "org_id"),
172
+ role: str(claims, "role"),
173
+ roles: strs(claims, "roles"),
174
+ permissions: strs(claims, "permissions"),
175
+ sessionId: str(claims, "sid"),
176
+ };
177
+ }
178
+ export function errorFromBody(status, body) {
179
+ const o = parseJson(body);
180
+ if (o) {
181
+ const flat = str(o, "error");
182
+ if (flat)
183
+ return OhAuthCatError.fromServer(flat, status);
184
+ const nested = o["error"];
185
+ if (isRecord(nested)) {
186
+ const code = str(nested, "code");
187
+ if (code)
188
+ return OhAuthCatError.fromServer(code, status);
189
+ }
190
+ }
191
+ return OhAuthCatError.fromServer(status >= 500 ? "server_error" : "invalid_request", status);
192
+ }
193
+ export async function postForm(fetchImpl, url, form) {
194
+ try {
195
+ const r = await fetchImpl(url, {
196
+ method: "POST",
197
+ headers: {
198
+ "Content-Type": "application/x-www-form-urlencoded",
199
+ Accept: "application/json",
200
+ },
201
+ body: formEncode(form),
202
+ });
203
+ return { status: r.status, body: await r.text() };
204
+ }
205
+ catch (e) {
206
+ throw OhAuthCatError.client("network", e instanceof Error ? e.message : "request failed");
207
+ }
208
+ }
209
+ export async function tokenRequest(fetchImpl, c, form, nowMs, previousRefresh) {
210
+ const { status, body } = await postForm(fetchImpl, c.tokenEndpoint, form);
211
+ if (status < 200 || status > 299)
212
+ throw errorFromBody(status, body);
213
+ const o = parseJson(body);
214
+ const access = o ? str(o, "access_token") : null;
215
+ if (!o || !access || str(o, "token_type")?.toLowerCase() !== "bearer") {
216
+ throw OhAuthCatError.client("invalid_response");
217
+ }
218
+ const exp = o["expires_in"];
219
+ const expiresIn = typeof exp === "number" ? exp : 600;
220
+ return {
221
+ accessToken: access,
222
+ refreshToken: str(o, "refresh_token") || previousRefresh,
223
+ idToken: str(o, "id_token") || null,
224
+ expiresAt: nowMs + expiresIn * 1000,
225
+ };
226
+ }
@@ -0,0 +1,9 @@
1
+ export { OhAuthCatClient, passkeyOptions } from "./client.js";
2
+ export type { PasskeyBackend, SignInOptions, SignOutOptions } from "./client.js";
3
+ export type { ClientOptions, IssuerMode } from "./config.js";
4
+ export { ErrorCodes, OhAuthCatError, isOhAuthCatError } from "./errors.js";
5
+ export type { ClientErrorKind } from "./errors.js";
6
+ export type { TokenSet, User } from "./flow.js";
7
+ export { nativePlatform, isNativeModule, fromNativeError } from "./platform.js";
8
+ export type { FetchLike, NativeModuleShape, PasskeyAuthenticator, Platform, SecureStore, } from "./platform.js";
9
+ export { base64UrlDecode } from "./encoding.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { OhAuthCatClient, passkeyOptions } from "./client.js";
2
+ export { ErrorCodes, OhAuthCatError, isOhAuthCatError } from "./errors.js";
3
+ export { nativePlatform, isNativeModule, fromNativeError } from "./platform.js";
4
+ export { base64UrlDecode } from "./encoding.js";