@atribu/node 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +21 -0
  3. package/README.md +423 -0
  4. package/dist/admin/index.cjs +326 -0
  5. package/dist/admin/index.cjs.map +1 -0
  6. package/dist/admin/index.d.cts +46 -0
  7. package/dist/admin/index.d.ts +46 -0
  8. package/dist/admin/index.js +323 -0
  9. package/dist/admin/index.js.map +1 -0
  10. package/dist/api.d-BXINTQo6.d.cts +3547 -0
  11. package/dist/api.d-BXINTQo6.d.ts +3547 -0
  12. package/dist/errors-D3ApBz8J.d.cts +86 -0
  13. package/dist/errors-D3ApBz8J.d.ts +86 -0
  14. package/dist/index.cjs +549 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.cts +198 -0
  17. package/dist/index.d.ts +198 -0
  18. package/dist/index.js +536 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/next/index.cjs +153 -0
  21. package/dist/next/index.cjs.map +1 -0
  22. package/dist/next/index.d.cts +43 -0
  23. package/dist/next/index.d.ts +43 -0
  24. package/dist/next/index.js +151 -0
  25. package/dist/next/index.js.map +1 -0
  26. package/dist/oauth/index.cjs +299 -0
  27. package/dist/oauth/index.cjs.map +1 -0
  28. package/dist/oauth/index.d.cts +117 -0
  29. package/dist/oauth/index.d.ts +117 -0
  30. package/dist/oauth/index.js +291 -0
  31. package/dist/oauth/index.js.map +1 -0
  32. package/dist/test/index.cjs +443 -0
  33. package/dist/test/index.cjs.map +1 -0
  34. package/dist/test/index.d.cts +321 -0
  35. package/dist/test/index.d.ts +321 -0
  36. package/dist/test/index.js +437 -0
  37. package/dist/test/index.js.map +1 -0
  38. package/dist/types-Dc6tIN_V.d.cts +101 -0
  39. package/dist/types-Dc6tIN_V.d.ts +101 -0
  40. package/dist/webhooks/index.cjs +97 -0
  41. package/dist/webhooks/index.cjs.map +1 -0
  42. package/dist/webhooks/index.d.cts +35 -0
  43. package/dist/webhooks/index.d.ts +35 -0
  44. package/dist/webhooks/index.js +94 -0
  45. package/dist/webhooks/index.js.map +1 -0
  46. package/package.json +101 -0
@@ -0,0 +1,299 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var AtribuError = class extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = new.target.name;
8
+ }
9
+ };
10
+ var AtribuConfigError = class extends AtribuError {
11
+ };
12
+ var AtribuTransportError = class extends AtribuError {
13
+ cause;
14
+ constructor(message, cause) {
15
+ super(message);
16
+ this.cause = cause;
17
+ }
18
+ };
19
+ var AtribuOauthError = class extends AtribuError {
20
+ code;
21
+ status;
22
+ description;
23
+ constructor(args) {
24
+ super(`[oauth/${args.code}] ${args.description ?? args.code}`);
25
+ this.code = args.code;
26
+ this.status = args.status;
27
+ this.description = args.description;
28
+ }
29
+ };
30
+
31
+ // src/oauth/authorize-url.ts
32
+ var DEFAULT_BASE_URL = "https://www.atribu.app";
33
+ function buildAuthorizeUrl(input) {
34
+ for (const key of ["clientId", "redirectUri", "provider", "state", "idTokenHint"]) {
35
+ if (!input[key]) throw new AtribuConfigError(`buildAuthorizeUrl: ${key} is required`);
36
+ }
37
+ if (input.codeChallenge && !input.codeChallengeMethod) {
38
+ throw new AtribuConfigError("codeChallengeMethod is required when codeChallenge is set");
39
+ }
40
+ const baseUrl = (input.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
41
+ const scope = Array.isArray(input.scope) ? input.scope.join(" ") : input.scope;
42
+ const url = new URL("/oauth/authorize", baseUrl);
43
+ url.searchParams.set("response_type", "code");
44
+ url.searchParams.set("client_id", input.clientId);
45
+ url.searchParams.set("redirect_uri", input.redirectUri);
46
+ url.searchParams.set("provider", input.provider);
47
+ url.searchParams.set("scope", scope);
48
+ url.searchParams.set("state", input.state);
49
+ url.searchParams.set("id_token_hint", input.idTokenHint);
50
+ if (input.codeChallenge && input.codeChallengeMethod) {
51
+ url.searchParams.set("code_challenge", input.codeChallenge);
52
+ url.searchParams.set("code_challenge_method", input.codeChallengeMethod);
53
+ }
54
+ if (input.extras) {
55
+ for (const [k, v] of Object.entries(input.extras)) url.searchParams.set(k, v);
56
+ }
57
+ return url.toString();
58
+ }
59
+
60
+ // src/version.ts
61
+ var SDK_VERSION = "0.1.0";
62
+
63
+ // src/runtime.ts
64
+ function detectRuntime() {
65
+ if (typeof Deno !== "undefined") return "deno";
66
+ if (typeof Bun !== "undefined") return "bun";
67
+ if (typeof EdgeRuntime !== "undefined") return "edge";
68
+ if (typeof process !== "undefined" && typeof process.versions?.node === "string") {
69
+ return "node";
70
+ }
71
+ if (typeof window !== "undefined" && typeof document !== "undefined") return "browser";
72
+ return "unknown";
73
+ }
74
+ function runtimeTag() {
75
+ const rt = detectRuntime();
76
+ if (rt === "node") {
77
+ const v = process.versions?.node;
78
+ return v ? `node/${v}` : "node";
79
+ }
80
+ return rt;
81
+ }
82
+
83
+ // src/oauth/exchange.ts
84
+ var DEFAULT_BASE_URL2 = "https://www.atribu.app";
85
+ async function exchangeCode(input) {
86
+ for (const key of ["clientId", "clientSecret", "code", "redirectUri"]) {
87
+ if (!input[key]) throw new AtribuConfigError(`exchangeCode: ${key} is required`);
88
+ }
89
+ const fetchImpl = input.fetch ?? globalThis.fetch;
90
+ if (typeof fetchImpl !== "function") {
91
+ throw new AtribuConfigError("globalThis.fetch is not available; pass a `fetch` impl");
92
+ }
93
+ const baseUrl = (input.baseUrl ?? DEFAULT_BASE_URL2).replace(/\/+$/, "");
94
+ const url = `${baseUrl}/oauth/token`;
95
+ const authMethod = input.authMethod ?? "basic";
96
+ const form = {
97
+ grant_type: "authorization_code",
98
+ code: input.code,
99
+ redirect_uri: input.redirectUri
100
+ };
101
+ if (input.codeVerifier) form.code_verifier = input.codeVerifier;
102
+ const headers = {
103
+ Accept: "application/json",
104
+ "Content-Type": "application/x-www-form-urlencoded",
105
+ "User-Agent": `@atribu/node/${SDK_VERSION} (${runtimeTag()})`
106
+ };
107
+ if (authMethod === "basic") {
108
+ headers.Authorization = `Basic ${base64(`${input.clientId}:${input.clientSecret}`)}`;
109
+ } else {
110
+ form.client_id = input.clientId;
111
+ form.client_secret = input.clientSecret;
112
+ }
113
+ const controller = new AbortController();
114
+ const timeout = setTimeout(() => controller.abort(), input.timeoutMs ?? 3e4);
115
+ const signal = input.signal ?? controller.signal;
116
+ let res;
117
+ try {
118
+ res = await fetchImpl(url, {
119
+ method: "POST",
120
+ headers,
121
+ body: new URLSearchParams(form).toString(),
122
+ signal
123
+ });
124
+ } catch (err) {
125
+ clearTimeout(timeout);
126
+ throw new AtribuTransportError(
127
+ err instanceof Error ? err.message : "fetch failed",
128
+ err
129
+ );
130
+ }
131
+ clearTimeout(timeout);
132
+ const text = await res.text();
133
+ const parsed = text ? safeJson(text) : null;
134
+ if (!res.ok) {
135
+ const body2 = parsed ?? {};
136
+ throw new AtribuOauthError({
137
+ code: typeof body2.error === "string" ? body2.error : "server_error",
138
+ description: typeof body2.error_description === "string" ? body2.error_description : null,
139
+ status: res.status
140
+ });
141
+ }
142
+ const body = parsed;
143
+ return {
144
+ accessToken: body.access_token,
145
+ tokenType: "bearer",
146
+ scope: typeof body.scope === "string" ? body.scope.split(/\s+/).filter(Boolean) : [],
147
+ connectionId: body.connection_id ?? null,
148
+ profileId: body.profile_id,
149
+ workspaceId: body.workspace_id
150
+ };
151
+ }
152
+ function base64(input) {
153
+ if (typeof btoa === "function") return btoa(input);
154
+ return Buffer.from(input, "utf8").toString("base64");
155
+ }
156
+ function safeJson(text) {
157
+ try {
158
+ return JSON.parse(text);
159
+ } catch {
160
+ return text;
161
+ }
162
+ }
163
+
164
+ // src/oauth/revoke.ts
165
+ var DEFAULT_BASE_URL3 = "https://www.atribu.app";
166
+ async function revokeToken(input) {
167
+ for (const key of ["clientId", "clientSecret", "token"]) {
168
+ if (!input[key]) throw new AtribuConfigError(`revokeToken: ${key} is required`);
169
+ }
170
+ const fetchImpl = input.fetch ?? globalThis.fetch;
171
+ if (typeof fetchImpl !== "function") {
172
+ throw new AtribuConfigError("globalThis.fetch is not available; pass a `fetch` impl");
173
+ }
174
+ const baseUrl = (input.baseUrl ?? DEFAULT_BASE_URL3).replace(/\/+$/, "");
175
+ const url = `${baseUrl}/oauth/revoke`;
176
+ const authMethod = input.authMethod ?? "basic";
177
+ const form = {
178
+ token: input.token,
179
+ token_type_hint: "access_token"
180
+ };
181
+ const headers = {
182
+ Accept: "application/json",
183
+ "Content-Type": "application/x-www-form-urlencoded",
184
+ "User-Agent": `@atribu/node/${SDK_VERSION} (${runtimeTag()})`
185
+ };
186
+ if (authMethod === "basic") {
187
+ headers.Authorization = `Basic ${base642(`${input.clientId}:${input.clientSecret}`)}`;
188
+ } else {
189
+ form.client_id = input.clientId;
190
+ form.client_secret = input.clientSecret;
191
+ }
192
+ const controller = new AbortController();
193
+ const timeout = setTimeout(() => controller.abort(), input.timeoutMs ?? 3e4);
194
+ const signal = input.signal ?? controller.signal;
195
+ let res;
196
+ try {
197
+ res = await fetchImpl(url, {
198
+ method: "POST",
199
+ headers,
200
+ body: new URLSearchParams(form).toString(),
201
+ signal
202
+ });
203
+ } catch (err) {
204
+ clearTimeout(timeout);
205
+ throw new AtribuTransportError(
206
+ err instanceof Error ? err.message : "fetch failed",
207
+ err
208
+ );
209
+ }
210
+ clearTimeout(timeout);
211
+ if (res.ok) return;
212
+ const text = await res.text();
213
+ let body = {};
214
+ try {
215
+ body = text ? JSON.parse(text) : {};
216
+ } catch {
217
+ body = {};
218
+ }
219
+ throw new AtribuOauthError({
220
+ code: typeof body.error === "string" ? body.error : "server_error",
221
+ description: typeof body.error_description === "string" ? body.error_description : null,
222
+ status: res.status
223
+ });
224
+ }
225
+ function base642(input) {
226
+ if (typeof btoa === "function") return btoa(input);
227
+ return Buffer.from(input, "utf8").toString("base64");
228
+ }
229
+
230
+ // src/oauth/id-token-hint.ts
231
+ var cachedJose = null;
232
+ var joseLoadAttempted = false;
233
+ async function loadJose() {
234
+ if (cachedJose) return cachedJose;
235
+ if (joseLoadAttempted && !cachedJose) {
236
+ throw new AtribuConfigError(
237
+ "signIdTokenHint requires the `jose` peer dependency. Run `npm install jose`."
238
+ );
239
+ }
240
+ joseLoadAttempted = true;
241
+ try {
242
+ const mod = await import('jose');
243
+ cachedJose = mod;
244
+ return mod;
245
+ } catch (err) {
246
+ const message = err instanceof Error ? err.message : "import failed";
247
+ throw new AtribuConfigError(
248
+ `signIdTokenHint requires the \`jose\` peer dependency. Install with \`npm install jose\`. (${message})`
249
+ );
250
+ }
251
+ }
252
+ async function signIdTokenHint(input) {
253
+ if (!input.jwtSigningSecret) {
254
+ throw new AtribuConfigError("signIdTokenHint: jwtSigningSecret is required");
255
+ }
256
+ if (!input.subject) throw new AtribuConfigError("signIdTokenHint: subject is required");
257
+ if (!input.email) throw new AtribuConfigError("signIdTokenHint: email is required");
258
+ const jose = await loadJose();
259
+ const claims = { email: input.email, ...input.extraClaims ?? {} };
260
+ const jwt = new jose.SignJWT(claims).setProtectedHeader({ alg: "HS256", typ: "JWT" }).setIssuedAt().setSubject(input.subject).setAudience(input.audience ?? "atribu").setExpirationTime(input.expiresIn ?? "5m");
261
+ if (input.issuer) jwt.setIssuer(input.issuer);
262
+ return jwt.sign(new TextEncoder().encode(input.jwtSigningSecret));
263
+ }
264
+
265
+ // src/oauth/pkce.ts
266
+ var VERIFIER_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
267
+ function generateCodeVerifier(length = 64) {
268
+ if (length < 43 || length > 128) {
269
+ throw new Error("PKCE verifier length must be 43\u2013128");
270
+ }
271
+ const bytes = new Uint8Array(length);
272
+ crypto.getRandomValues(bytes);
273
+ let out = "";
274
+ for (let i = 0; i < length; i++) {
275
+ out += VERIFIER_CHARS[bytes[i] % VERIFIER_CHARS.length];
276
+ }
277
+ return out;
278
+ }
279
+ async function computeCodeChallenge(verifier) {
280
+ const data = new TextEncoder().encode(verifier);
281
+ const digest = await crypto.subtle.digest("SHA-256", data);
282
+ return base64UrlEncode(new Uint8Array(digest));
283
+ }
284
+ function base64UrlEncode(bytes) {
285
+ let bin = "";
286
+ for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
287
+ const b64 = typeof btoa === "function" ? btoa(bin) : Buffer.from(bytes).toString("base64");
288
+ return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
289
+ }
290
+
291
+ exports.AtribuOauthError = AtribuOauthError;
292
+ exports.buildAuthorizeUrl = buildAuthorizeUrl;
293
+ exports.computeCodeChallenge = computeCodeChallenge;
294
+ exports.exchangeCode = exchangeCode;
295
+ exports.generateCodeVerifier = generateCodeVerifier;
296
+ exports.revokeToken = revokeToken;
297
+ exports.signIdTokenHint = signIdTokenHint;
298
+ //# sourceMappingURL=index.cjs.map
299
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors.ts","../../src/oauth/authorize-url.ts","../../src/version.ts","../../src/runtime.ts","../../src/oauth/exchange.ts","../../src/oauth/revoke.ts","../../src/oauth/id-token-hint.ts","../../src/oauth/pkce.ts"],"names":["DEFAULT_BASE_URL","body","base64"],"mappings":";;;AAiCO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAAA,EACzB;AACF,CAAA;AAEO,IAAM,iBAAA,GAAN,cAAgC,WAAA,CAAY;AAAC,CAAA;AAE7C,IAAM,oBAAA,GAAN,cAAmC,WAAA,CAAY;AAAA,EAC3C,KAAA;AAAA,EACT,WAAA,CAAY,SAAiB,KAAA,EAAgB;AAC3C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,KAAA,GAAQ,KAAA;AAAA,EACf;AACF,CAAA;AAsD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A,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,MAAA,EAAQ,CAAA,EAAA,EAAK;AAC/B,IAAA,GAAA,IAAO,cAAA,CAAe,KAAA,CAAM,CAAC,CAAA,GAAK,eAAe,MAAM,CAAA;AAAA,EACzD;AACA,EAAA,OAAO,GAAA;AACT;AAEA,eAAsB,qBAAqB,QAAA,EAAmC;AAC5E,EAAA,MAAM,IAAA,GAAO,IAAI,WAAA,EAAY,CAAE,OAAO,QAAQ,CAAA;AAC9C,EAAA,MAAM,SAAS,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,WAAW,IAAI,CAAA;AACzD,EAAA,OAAO,eAAA,CAAgB,IAAI,UAAA,CAAW,MAAM,CAAC,CAAA;AAC/C;AAEA,SAAS,gBAAgB,KAAA,EAA2B;AAClD,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,MAAA,EAAQ,CAAA,EAAA,EAAK,GAAA,IAAO,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAE,CAAA;AAC3E,EAAA,MAAM,GAAA,GACJ,OAAO,IAAA,KAAS,UAAA,GACZ,IAAA,CAAK,GAAG,CAAA,GACR,MAAA,CAAO,IAAA,CAAK,KAAK,CAAA,CAAE,QAAA,CAAS,QAAQ,CAAA;AAC1C,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AACtE","file":"index.cjs","sourcesContent":["/**\n * Atribu error class hierarchy.\n *\n * Why typed errors: consumers need to branch on auth-failure vs rate-limit vs\n * server-error vs validation-error to decide whether to retry, refresh\n * credentials, or surface to the user. A single `Error` with a status code\n * forces every consumer to write the same `if (err.status === 401)` ladder.\n *\n * Why no automatic retries: the SDK derives a `retry` hint from status +\n * Retry-After + error code, but consumers' queue/job systems decide whether\n * to act on it. Auto-retry inside the SDK hides backpressure signals and\n * makes error budgets opaque.\n */\n\nimport type { RetryHint } from \"./retry\";\n\nexport type ApiErrorCode =\n | \"unauthorized\"\n | \"forbidden\"\n | \"insufficient_scope\"\n | \"not_found\"\n | \"invalid_parameter\"\n | \"invalid_request\"\n | \"validation_error\"\n | \"invalid_content\"\n | \"invalid_date_range\"\n | \"rate_limit_exceeded\"\n | \"connection_not_ready\"\n | \"provider_error\"\n | \"service_unavailable\"\n | \"internal_error\"\n | string;\n\nexport class AtribuError extends Error {\n constructor(message: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\nexport class AtribuConfigError extends AtribuError {}\n\nexport class AtribuTransportError extends AtribuError {\n readonly cause: unknown;\n constructor(message: string, cause: unknown) {\n super(message);\n this.cause = cause;\n }\n}\n\nexport interface ApiErrorBody {\n code: ApiErrorCode;\n message: string;\n status: number;\n request_id?: string;\n}\n\nexport class AtribuApiError extends AtribuError {\n readonly code: ApiErrorCode;\n readonly status: number;\n readonly requestId: string | null;\n readonly retry: RetryHint;\n readonly responseBody: unknown;\n\n constructor(args: {\n code: ApiErrorCode;\n message: string;\n status: number;\n requestId: string | null;\n retry: RetryHint;\n responseBody: unknown;\n }) {\n super(`[${args.code}] ${args.message}`);\n this.code = args.code;\n this.status = args.status;\n this.requestId = args.requestId;\n this.retry = args.retry;\n this.responseBody = args.responseBody;\n }\n\n isRetryable(): boolean {\n return this.retry.action === \"retry\" || this.retry.action === \"retry_after\";\n }\n isAuthFailure(): boolean {\n return this.status === 401 || this.code === \"unauthorized\";\n }\n isRateLimit(): boolean {\n return this.status === 429 || this.code === \"rate_limit_exceeded\";\n }\n}\n\nexport type OauthErrorCode =\n | \"invalid_request\"\n | \"invalid_client\"\n | \"invalid_grant\"\n | \"unauthorized_client\"\n | \"unsupported_grant_type\"\n | \"invalid_scope\"\n | \"server_error\"\n | \"unsupported_token_type\"\n | string;\n\nexport class AtribuOauthError extends AtribuError {\n readonly code: OauthErrorCode;\n readonly status: number;\n readonly description: string | null;\n\n constructor(args: { code: OauthErrorCode; description: string | null; status: number }) {\n super(`[oauth/${args.code}] ${args.description ?? args.code}`);\n this.code = args.code;\n this.status = args.status;\n this.description = args.description;\n }\n}\n\nexport type WebhookErrorCode =\n | \"missing_signature\"\n | \"malformed_header\"\n | \"expired_timestamp\"\n | \"invalid_signature\";\n\nexport class AtribuWebhookError extends AtribuError {\n readonly code: WebhookErrorCode;\n constructor(code: WebhookErrorCode, message: string) {\n super(message);\n this.code = code;\n }\n}\n","import { AtribuConfigError } from \"../errors\";\n\nexport type OauthProvider = \"whatsapp\" | \"instagram\";\nexport type OauthScope = \"whatsapp\" | \"instagram\";\n\nexport interface BuildAuthorizeUrlInput {\n baseUrl?: string;\n clientId: string;\n redirectUri: string;\n provider: OauthProvider;\n scope: OauthScope | OauthScope[];\n state: string;\n /** Pre-signed `id_token_hint` JWT — use `signIdTokenHint` to mint. */\n idTokenHint: string;\n /** PKCE challenge (base64url of SHA-256). */\n codeChallenge?: string;\n codeChallengeMethod?: \"S256\" | \"plain\";\n /** Forwards extra query params unchanged. */\n extras?: Record<string, string>;\n}\n\nconst DEFAULT_BASE_URL = \"https://www.atribu.app\";\n\n/**\n * Build the `/oauth/authorize` URL the user should be redirected to.\n *\n * Pure function — returns a string. No network calls, no crypto. The only\n * runtime check is required-arg validation.\n */\nexport function buildAuthorizeUrl(input: BuildAuthorizeUrlInput): string {\n for (const key of [\"clientId\", \"redirectUri\", \"provider\", \"state\", \"idTokenHint\"] as const) {\n if (!input[key]) throw new AtribuConfigError(`buildAuthorizeUrl: ${key} is required`);\n }\n if (input.codeChallenge && !input.codeChallengeMethod) {\n throw new AtribuConfigError(\"codeChallengeMethod is required when codeChallenge is set\");\n }\n const baseUrl = (input.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const scope = Array.isArray(input.scope) ? input.scope.join(\" \") : input.scope;\n\n const url = new URL(\"/oauth/authorize\", baseUrl);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", input.clientId);\n url.searchParams.set(\"redirect_uri\", input.redirectUri);\n url.searchParams.set(\"provider\", input.provider);\n url.searchParams.set(\"scope\", scope);\n url.searchParams.set(\"state\", input.state);\n url.searchParams.set(\"id_token_hint\", input.idTokenHint);\n if (input.codeChallenge && input.codeChallengeMethod) {\n url.searchParams.set(\"code_challenge\", input.codeChallenge);\n url.searchParams.set(\"code_challenge_method\", input.codeChallengeMethod);\n }\n if (input.extras) {\n for (const [k, v] of Object.entries(input.extras)) url.searchParams.set(k, v);\n }\n return url.toString();\n}\n","export const SDK_VERSION = \"0.1.0\";\n","export type Runtime = \"node\" | \"bun\" | \"deno\" | \"edge\" | \"browser\" | \"unknown\";\n\ndeclare const Deno: unknown;\ndeclare const Bun: unknown;\ndeclare const EdgeRuntime: unknown;\n\nexport function detectRuntime(): Runtime {\n if (typeof Deno !== \"undefined\") return \"deno\";\n if (typeof Bun !== \"undefined\") return \"bun\";\n if (typeof EdgeRuntime !== \"undefined\") return \"edge\";\n if (\n typeof process !== \"undefined\" &&\n typeof (process as { versions?: { node?: string } }).versions?.node === \"string\"\n ) {\n return \"node\";\n }\n if (typeof window !== \"undefined\" && typeof document !== \"undefined\") return \"browser\";\n return \"unknown\";\n}\n\nexport function runtimeTag(): string {\n const rt = detectRuntime();\n if (rt === \"node\") {\n const v = (process as { versions?: { node?: string } }).versions?.node;\n return v ? `node/${v}` : \"node\";\n }\n return rt;\n}\n","/**\n * Exchange an authorization code for an Atribu access token.\n *\n * Calls `POST /oauth/token` with form-urlencoded body (RFC 6749 default).\n * Tries `client_secret_basic` (Authorization header) by default; consumers\n * can opt into `client_secret_post` via `authMethod: \"body\"`.\n */\n\nimport {\n AtribuConfigError,\n AtribuOauthError,\n AtribuTransportError,\n} from \"../errors\";\nimport { SDK_VERSION } from \"../version\";\nimport { runtimeTag } from \"../runtime\";\n\nexport interface ExchangeCodeInput {\n baseUrl?: string;\n clientId: string;\n clientSecret: string;\n code: string;\n redirectUri: string;\n codeVerifier?: string;\n /** \"basic\" (default) sends Authorization: Basic; \"body\" puts creds in form body. */\n authMethod?: \"basic\" | \"body\";\n fetch?: typeof fetch;\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface ExchangeCodeResult {\n accessToken: string;\n tokenType: \"bearer\";\n scope: string[];\n connectionId: string | null;\n profileId: string;\n workspaceId: string;\n}\n\nconst DEFAULT_BASE_URL = \"https://www.atribu.app\";\n\nexport async function exchangeCode(input: ExchangeCodeInput): Promise<ExchangeCodeResult> {\n for (const key of [\"clientId\", \"clientSecret\", \"code\", \"redirectUri\"] as const) {\n if (!input[key]) throw new AtribuConfigError(`exchangeCode: ${key} is required`);\n }\n const fetchImpl = input.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new AtribuConfigError(\"globalThis.fetch is not available; pass a `fetch` impl\");\n }\n const baseUrl = (input.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const url = `${baseUrl}/oauth/token`;\n const authMethod = input.authMethod ?? \"basic\";\n\n const form: Record<string, string> = {\n grant_type: \"authorization_code\",\n code: input.code,\n redirect_uri: input.redirectUri,\n };\n if (input.codeVerifier) form.code_verifier = input.codeVerifier;\n\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": `@atribu/node/${SDK_VERSION} (${runtimeTag()})`,\n };\n\n if (authMethod === \"basic\") {\n headers.Authorization = `Basic ${base64(`${input.clientId}:${input.clientSecret}`)}`;\n } else {\n form.client_id = input.clientId;\n form.client_secret = input.clientSecret;\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), input.timeoutMs ?? 30_000);\n const signal = input.signal ?? controller.signal;\n\n let res: Response;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body: new URLSearchParams(form).toString(),\n signal,\n });\n } catch (err) {\n clearTimeout(timeout);\n throw new AtribuTransportError(\n err instanceof Error ? err.message : \"fetch failed\",\n err,\n );\n }\n clearTimeout(timeout);\n\n const text = await res.text();\n const parsed = text ? safeJson(text) : null;\n\n if (!res.ok) {\n const body = (parsed ?? {}) as { error?: unknown; error_description?: unknown };\n throw new AtribuOauthError({\n code: typeof body.error === \"string\" ? body.error : \"server_error\",\n description: typeof body.error_description === \"string\" ? body.error_description : null,\n status: res.status,\n });\n }\n const body = parsed as {\n access_token: string;\n token_type: string;\n scope?: string;\n connection_id?: string;\n profile_id: string;\n workspace_id: string;\n };\n return {\n accessToken: body.access_token,\n tokenType: \"bearer\",\n scope: typeof body.scope === \"string\" ? body.scope.split(/\\s+/).filter(Boolean) : [],\n connectionId: body.connection_id ?? null,\n profileId: body.profile_id,\n workspaceId: body.workspace_id,\n };\n}\n\nfunction base64(input: string): string {\n if (typeof btoa === \"function\") return btoa(input);\n return Buffer.from(input, \"utf8\").toString(\"base64\");\n}\n\nfunction safeJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n","/**\n * Revoke an Atribu access token via RFC 7009.\n *\n * Always returns void on success — the server returns 200 regardless of\n * whether the token existed (RFC §2.2; no enumeration). Authentication\n * errors (bad client credentials) still throw AtribuOauthError.\n */\n\nimport {\n AtribuConfigError,\n AtribuOauthError,\n AtribuTransportError,\n} from \"../errors\";\nimport { SDK_VERSION } from \"../version\";\nimport { runtimeTag } from \"../runtime\";\n\nexport interface RevokeTokenInput {\n baseUrl?: string;\n clientId: string;\n clientSecret: string;\n token: string;\n authMethod?: \"basic\" | \"body\";\n fetch?: typeof fetch;\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nconst DEFAULT_BASE_URL = \"https://www.atribu.app\";\n\nexport async function revokeToken(input: RevokeTokenInput): Promise<void> {\n for (const key of [\"clientId\", \"clientSecret\", \"token\"] as const) {\n if (!input[key]) throw new AtribuConfigError(`revokeToken: ${key} is required`);\n }\n const fetchImpl = input.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new AtribuConfigError(\"globalThis.fetch is not available; pass a `fetch` impl\");\n }\n const baseUrl = (input.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const url = `${baseUrl}/oauth/revoke`;\n const authMethod = input.authMethod ?? \"basic\";\n\n const form: Record<string, string> = {\n token: input.token,\n token_type_hint: \"access_token\",\n };\n const headers: Record<string, string> = {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"User-Agent\": `@atribu/node/${SDK_VERSION} (${runtimeTag()})`,\n };\n if (authMethod === \"basic\") {\n headers.Authorization = `Basic ${base64(`${input.clientId}:${input.clientSecret}`)}`;\n } else {\n form.client_id = input.clientId;\n form.client_secret = input.clientSecret;\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), input.timeoutMs ?? 30_000);\n const signal = input.signal ?? controller.signal;\n\n let res: Response;\n try {\n res = await fetchImpl(url, {\n method: \"POST\",\n headers,\n body: new URLSearchParams(form).toString(),\n signal,\n });\n } catch (err) {\n clearTimeout(timeout);\n throw new AtribuTransportError(\n err instanceof Error ? err.message : \"fetch failed\",\n err,\n );\n }\n clearTimeout(timeout);\n\n if (res.ok) return;\n const text = await res.text();\n let body: { error?: unknown; error_description?: unknown } = {};\n try {\n body = text ? (JSON.parse(text) as typeof body) : {};\n } catch {\n body = {};\n }\n throw new AtribuOauthError({\n code: typeof body.error === \"string\" ? body.error : \"server_error\",\n description: typeof body.error_description === \"string\" ? body.error_description : null,\n status: res.status,\n });\n}\n\nfunction base64(input: string): string {\n if (typeof btoa === \"function\") return btoa(input);\n return Buffer.from(input, \"utf8\").toString(\"base64\");\n}\n","/**\n * Sign an `id_token_hint` JWT (HS256) for an Atribu OAuth flow.\n *\n * Uses `jose` (optional peer dep). If `jose` isn't installed, throws a\n * clear runtime error. Vitrina-style consumers almost always already have\n * `jose` for their own auth.\n *\n * Why HS256 not RS256: the shared secret is the OAuth app's\n * `jwt_signing_secret` (rotatable, paired). RS256 would mean Atribu\n * publishes a JWKS endpoint and we manage keypairs — out of scope today.\n */\n\nimport { AtribuConfigError } from \"../errors\";\n\nexport interface IdTokenHintPayload {\n /** End-user's stable identifier in your system. */\n subject: string;\n /** End-user's email. Used by Atribu to silent-provision / find existing profile. */\n email: string;\n /** Token audience. Use \"atribu\" unless directed otherwise. */\n audience?: string;\n /** Issuer (your app's client_id, by convention). */\n issuer?: string;\n /** Expiration relative to now. Default \"5m\". Examples: \"5m\", \"10m\", numeric seconds. */\n expiresIn?: string | number;\n /** Atribu's recognized claims plus any custom ones. */\n extraClaims?: Record<string, unknown>;\n}\n\nexport interface SignIdTokenHintInput extends IdTokenHintPayload {\n /** The OAuth app's `jwt_signing_secret`. */\n jwtSigningSecret: string;\n}\n\ninterface JoseModule {\n SignJWT: new (payload: Record<string, unknown>) => {\n setProtectedHeader(header: { alg: string; typ?: string }): JoseSignJwt;\n setIssuedAt(time?: number): JoseSignJwt;\n setExpirationTime(time: string | number): JoseSignJwt;\n setIssuer(issuer: string): JoseSignJwt;\n setSubject(subject: string): JoseSignJwt;\n setAudience(audience: string | string[]): JoseSignJwt;\n sign(secret: Uint8Array | CryptoKey): Promise<string>;\n };\n}\ntype JoseSignJwt = InstanceType<JoseModule[\"SignJWT\"]>;\n\nlet cachedJose: JoseModule | null = null;\nlet joseLoadAttempted = false;\n\nasync function loadJose(): Promise<JoseModule> {\n if (cachedJose) return cachedJose;\n if (joseLoadAttempted && !cachedJose) {\n throw new AtribuConfigError(\n \"signIdTokenHint requires the `jose` peer dependency. Run `npm install jose`.\",\n );\n }\n joseLoadAttempted = true;\n try {\n const mod = (await import(\"jose\")) as unknown as JoseModule;\n cachedJose = mod;\n return mod;\n } catch (err) {\n const message = err instanceof Error ? err.message : \"import failed\";\n throw new AtribuConfigError(\n `signIdTokenHint requires the \\`jose\\` peer dependency. Install with \\`npm install jose\\`. (${message})`,\n );\n }\n}\n\nexport async function signIdTokenHint(input: SignIdTokenHintInput): Promise<string> {\n if (!input.jwtSigningSecret) {\n throw new AtribuConfigError(\"signIdTokenHint: jwtSigningSecret is required\");\n }\n if (!input.subject) throw new AtribuConfigError(\"signIdTokenHint: subject is required\");\n if (!input.email) throw new AtribuConfigError(\"signIdTokenHint: email is required\");\n\n const jose = await loadJose();\n const claims: Record<string, unknown> = { email: input.email, ...(input.extraClaims ?? {}) };\n\n const jwt = new jose.SignJWT(claims)\n .setProtectedHeader({ alg: \"HS256\", typ: \"JWT\" })\n .setIssuedAt()\n .setSubject(input.subject)\n .setAudience(input.audience ?? \"atribu\")\n .setExpirationTime(input.expiresIn ?? \"5m\");\n if (input.issuer) jwt.setIssuer(input.issuer);\n\n return jwt.sign(new TextEncoder().encode(input.jwtSigningSecret));\n}\n","/**\n * PKCE helpers (RFC 7636).\n *\n * Generates an unguessable `code_verifier` and the base64url(SHA-256) digest\n * to use as `code_challenge` with `code_challenge_method=S256`.\n */\n\nconst VERIFIER_CHARS =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~\";\n\nexport function generateCodeVerifier(length = 64): string {\n if (length < 43 || length > 128) {\n throw new Error(\"PKCE verifier length must be 43–128\");\n }\n const bytes = new Uint8Array(length);\n crypto.getRandomValues(bytes);\n let out = \"\";\n for (let i = 0; i < length; i++) {\n out += VERIFIER_CHARS[bytes[i]! % VERIFIER_CHARS.length];\n }\n return out;\n}\n\nexport async function computeCodeChallenge(verifier: string): Promise<string> {\n const data = new TextEncoder().encode(verifier);\n const digest = await crypto.subtle.digest(\"SHA-256\", data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let bin = \"\";\n for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);\n const b64 =\n typeof btoa === \"function\"\n ? btoa(bin)\n : Buffer.from(bytes).toString(\"base64\");\n return b64.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n"]}
@@ -0,0 +1,117 @@
1
+ export { e as AtribuOauthError, O as OauthErrorCode } from '../errors-D3ApBz8J.cjs';
2
+
3
+ type OauthProvider = "whatsapp" | "instagram";
4
+ type OauthScope = "whatsapp" | "instagram";
5
+ interface BuildAuthorizeUrlInput {
6
+ baseUrl?: string;
7
+ clientId: string;
8
+ redirectUri: string;
9
+ provider: OauthProvider;
10
+ scope: OauthScope | OauthScope[];
11
+ state: string;
12
+ /** Pre-signed `id_token_hint` JWT — use `signIdTokenHint` to mint. */
13
+ idTokenHint: string;
14
+ /** PKCE challenge (base64url of SHA-256). */
15
+ codeChallenge?: string;
16
+ codeChallengeMethod?: "S256" | "plain";
17
+ /** Forwards extra query params unchanged. */
18
+ extras?: Record<string, string>;
19
+ }
20
+ /**
21
+ * Build the `/oauth/authorize` URL the user should be redirected to.
22
+ *
23
+ * Pure function — returns a string. No network calls, no crypto. The only
24
+ * runtime check is required-arg validation.
25
+ */
26
+ declare function buildAuthorizeUrl(input: BuildAuthorizeUrlInput): string;
27
+
28
+ /**
29
+ * Exchange an authorization code for an Atribu access token.
30
+ *
31
+ * Calls `POST /oauth/token` with form-urlencoded body (RFC 6749 default).
32
+ * Tries `client_secret_basic` (Authorization header) by default; consumers
33
+ * can opt into `client_secret_post` via `authMethod: "body"`.
34
+ */
35
+ interface ExchangeCodeInput {
36
+ baseUrl?: string;
37
+ clientId: string;
38
+ clientSecret: string;
39
+ code: string;
40
+ redirectUri: string;
41
+ codeVerifier?: string;
42
+ /** "basic" (default) sends Authorization: Basic; "body" puts creds in form body. */
43
+ authMethod?: "basic" | "body";
44
+ fetch?: typeof fetch;
45
+ timeoutMs?: number;
46
+ signal?: AbortSignal;
47
+ }
48
+ interface ExchangeCodeResult {
49
+ accessToken: string;
50
+ tokenType: "bearer";
51
+ scope: string[];
52
+ connectionId: string | null;
53
+ profileId: string;
54
+ workspaceId: string;
55
+ }
56
+ declare function exchangeCode(input: ExchangeCodeInput): Promise<ExchangeCodeResult>;
57
+
58
+ /**
59
+ * Revoke an Atribu access token via RFC 7009.
60
+ *
61
+ * Always returns void on success — the server returns 200 regardless of
62
+ * whether the token existed (RFC §2.2; no enumeration). Authentication
63
+ * errors (bad client credentials) still throw AtribuOauthError.
64
+ */
65
+ interface RevokeTokenInput {
66
+ baseUrl?: string;
67
+ clientId: string;
68
+ clientSecret: string;
69
+ token: string;
70
+ authMethod?: "basic" | "body";
71
+ fetch?: typeof fetch;
72
+ timeoutMs?: number;
73
+ signal?: AbortSignal;
74
+ }
75
+ declare function revokeToken(input: RevokeTokenInput): Promise<void>;
76
+
77
+ /**
78
+ * Sign an `id_token_hint` JWT (HS256) for an Atribu OAuth flow.
79
+ *
80
+ * Uses `jose` (optional peer dep). If `jose` isn't installed, throws a
81
+ * clear runtime error. Vitrina-style consumers almost always already have
82
+ * `jose` for their own auth.
83
+ *
84
+ * Why HS256 not RS256: the shared secret is the OAuth app's
85
+ * `jwt_signing_secret` (rotatable, paired). RS256 would mean Atribu
86
+ * publishes a JWKS endpoint and we manage keypairs — out of scope today.
87
+ */
88
+ interface IdTokenHintPayload {
89
+ /** End-user's stable identifier in your system. */
90
+ subject: string;
91
+ /** End-user's email. Used by Atribu to silent-provision / find existing profile. */
92
+ email: string;
93
+ /** Token audience. Use "atribu" unless directed otherwise. */
94
+ audience?: string;
95
+ /** Issuer (your app's client_id, by convention). */
96
+ issuer?: string;
97
+ /** Expiration relative to now. Default "5m". Examples: "5m", "10m", numeric seconds. */
98
+ expiresIn?: string | number;
99
+ /** Atribu's recognized claims plus any custom ones. */
100
+ extraClaims?: Record<string, unknown>;
101
+ }
102
+ interface SignIdTokenHintInput extends IdTokenHintPayload {
103
+ /** The OAuth app's `jwt_signing_secret`. */
104
+ jwtSigningSecret: string;
105
+ }
106
+ declare function signIdTokenHint(input: SignIdTokenHintInput): Promise<string>;
107
+
108
+ /**
109
+ * PKCE helpers (RFC 7636).
110
+ *
111
+ * Generates an unguessable `code_verifier` and the base64url(SHA-256) digest
112
+ * to use as `code_challenge` with `code_challenge_method=S256`.
113
+ */
114
+ declare function generateCodeVerifier(length?: number): string;
115
+ declare function computeCodeChallenge(verifier: string): Promise<string>;
116
+
117
+ export { type BuildAuthorizeUrlInput, type ExchangeCodeInput, type ExchangeCodeResult, type IdTokenHintPayload, type OauthProvider, type OauthScope, type RevokeTokenInput, type SignIdTokenHintInput, buildAuthorizeUrl, computeCodeChallenge, exchangeCode, generateCodeVerifier, revokeToken, signIdTokenHint };
@@ -0,0 +1,117 @@
1
+ export { e as AtribuOauthError, O as OauthErrorCode } from '../errors-D3ApBz8J.js';
2
+
3
+ type OauthProvider = "whatsapp" | "instagram";
4
+ type OauthScope = "whatsapp" | "instagram";
5
+ interface BuildAuthorizeUrlInput {
6
+ baseUrl?: string;
7
+ clientId: string;
8
+ redirectUri: string;
9
+ provider: OauthProvider;
10
+ scope: OauthScope | OauthScope[];
11
+ state: string;
12
+ /** Pre-signed `id_token_hint` JWT — use `signIdTokenHint` to mint. */
13
+ idTokenHint: string;
14
+ /** PKCE challenge (base64url of SHA-256). */
15
+ codeChallenge?: string;
16
+ codeChallengeMethod?: "S256" | "plain";
17
+ /** Forwards extra query params unchanged. */
18
+ extras?: Record<string, string>;
19
+ }
20
+ /**
21
+ * Build the `/oauth/authorize` URL the user should be redirected to.
22
+ *
23
+ * Pure function — returns a string. No network calls, no crypto. The only
24
+ * runtime check is required-arg validation.
25
+ */
26
+ declare function buildAuthorizeUrl(input: BuildAuthorizeUrlInput): string;
27
+
28
+ /**
29
+ * Exchange an authorization code for an Atribu access token.
30
+ *
31
+ * Calls `POST /oauth/token` with form-urlencoded body (RFC 6749 default).
32
+ * Tries `client_secret_basic` (Authorization header) by default; consumers
33
+ * can opt into `client_secret_post` via `authMethod: "body"`.
34
+ */
35
+ interface ExchangeCodeInput {
36
+ baseUrl?: string;
37
+ clientId: string;
38
+ clientSecret: string;
39
+ code: string;
40
+ redirectUri: string;
41
+ codeVerifier?: string;
42
+ /** "basic" (default) sends Authorization: Basic; "body" puts creds in form body. */
43
+ authMethod?: "basic" | "body";
44
+ fetch?: typeof fetch;
45
+ timeoutMs?: number;
46
+ signal?: AbortSignal;
47
+ }
48
+ interface ExchangeCodeResult {
49
+ accessToken: string;
50
+ tokenType: "bearer";
51
+ scope: string[];
52
+ connectionId: string | null;
53
+ profileId: string;
54
+ workspaceId: string;
55
+ }
56
+ declare function exchangeCode(input: ExchangeCodeInput): Promise<ExchangeCodeResult>;
57
+
58
+ /**
59
+ * Revoke an Atribu access token via RFC 7009.
60
+ *
61
+ * Always returns void on success — the server returns 200 regardless of
62
+ * whether the token existed (RFC §2.2; no enumeration). Authentication
63
+ * errors (bad client credentials) still throw AtribuOauthError.
64
+ */
65
+ interface RevokeTokenInput {
66
+ baseUrl?: string;
67
+ clientId: string;
68
+ clientSecret: string;
69
+ token: string;
70
+ authMethod?: "basic" | "body";
71
+ fetch?: typeof fetch;
72
+ timeoutMs?: number;
73
+ signal?: AbortSignal;
74
+ }
75
+ declare function revokeToken(input: RevokeTokenInput): Promise<void>;
76
+
77
+ /**
78
+ * Sign an `id_token_hint` JWT (HS256) for an Atribu OAuth flow.
79
+ *
80
+ * Uses `jose` (optional peer dep). If `jose` isn't installed, throws a
81
+ * clear runtime error. Vitrina-style consumers almost always already have
82
+ * `jose` for their own auth.
83
+ *
84
+ * Why HS256 not RS256: the shared secret is the OAuth app's
85
+ * `jwt_signing_secret` (rotatable, paired). RS256 would mean Atribu
86
+ * publishes a JWKS endpoint and we manage keypairs — out of scope today.
87
+ */
88
+ interface IdTokenHintPayload {
89
+ /** End-user's stable identifier in your system. */
90
+ subject: string;
91
+ /** End-user's email. Used by Atribu to silent-provision / find existing profile. */
92
+ email: string;
93
+ /** Token audience. Use "atribu" unless directed otherwise. */
94
+ audience?: string;
95
+ /** Issuer (your app's client_id, by convention). */
96
+ issuer?: string;
97
+ /** Expiration relative to now. Default "5m". Examples: "5m", "10m", numeric seconds. */
98
+ expiresIn?: string | number;
99
+ /** Atribu's recognized claims plus any custom ones. */
100
+ extraClaims?: Record<string, unknown>;
101
+ }
102
+ interface SignIdTokenHintInput extends IdTokenHintPayload {
103
+ /** The OAuth app's `jwt_signing_secret`. */
104
+ jwtSigningSecret: string;
105
+ }
106
+ declare function signIdTokenHint(input: SignIdTokenHintInput): Promise<string>;
107
+
108
+ /**
109
+ * PKCE helpers (RFC 7636).
110
+ *
111
+ * Generates an unguessable `code_verifier` and the base64url(SHA-256) digest
112
+ * to use as `code_challenge` with `code_challenge_method=S256`.
113
+ */
114
+ declare function generateCodeVerifier(length?: number): string;
115
+ declare function computeCodeChallenge(verifier: string): Promise<string>;
116
+
117
+ export { type BuildAuthorizeUrlInput, type ExchangeCodeInput, type ExchangeCodeResult, type IdTokenHintPayload, type OauthProvider, type OauthScope, type RevokeTokenInput, type SignIdTokenHintInput, buildAuthorizeUrl, computeCodeChallenge, exchangeCode, generateCodeVerifier, revokeToken, signIdTokenHint };