@olyzon/sdk 0.0.0 → 0.1.0-stg.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.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +17 -1
  3. package/dist/client.d.ts +62 -0
  4. package/dist/client.js +104 -0
  5. package/dist/core/config.d.ts +153 -0
  6. package/dist/core/config.js +368 -0
  7. package/dist/core/contracts.d.ts +52 -0
  8. package/dist/core/contracts.js +12 -0
  9. package/dist/core/dpop.d.ts +39 -0
  10. package/dist/core/dpop.js +63 -0
  11. package/dist/core/errors.d.ts +34 -0
  12. package/dist/core/errors.js +43 -0
  13. package/dist/core/session.d.ts +82 -0
  14. package/dist/core/session.js +170 -0
  15. package/dist/core/transport.d.ts +38 -0
  16. package/dist/core/transport.js +84 -0
  17. package/dist/generated/index.d.ts +24 -0
  18. package/dist/generated/index.js +20 -0
  19. package/dist/generated/manifest.json +13 -0
  20. package/dist/generated/projects/client/client.gen.d.ts +2 -0
  21. package/dist/generated/projects/client/client.gen.js +216 -0
  22. package/dist/generated/projects/client/index.d.ts +10 -0
  23. package/dist/generated/projects/client/index.js +6 -0
  24. package/dist/generated/projects/client/types.gen.d.ts +120 -0
  25. package/dist/generated/projects/client/types.gen.js +2 -0
  26. package/dist/generated/projects/client/utils.gen.d.ts +37 -0
  27. package/dist/generated/projects/client/utils.gen.js +228 -0
  28. package/dist/generated/projects/client.gen.d.ts +12 -0
  29. package/dist/generated/projects/client.gen.js +3 -0
  30. package/dist/generated/projects/core/auth.gen.d.ts +25 -0
  31. package/dist/generated/projects/core/auth.gen.js +14 -0
  32. package/dist/generated/projects/core/bodySerializer.gen.d.ts +25 -0
  33. package/dist/generated/projects/core/bodySerializer.gen.js +57 -0
  34. package/dist/generated/projects/core/params.gen.d.ts +43 -0
  35. package/dist/generated/projects/core/params.gen.js +109 -0
  36. package/dist/generated/projects/core/pathSerializer.gen.d.ts +33 -0
  37. package/dist/generated/projects/core/pathSerializer.gen.js +106 -0
  38. package/dist/generated/projects/core/queryKeySerializer.gen.d.ts +18 -0
  39. package/dist/generated/projects/core/queryKeySerializer.gen.js +92 -0
  40. package/dist/generated/projects/core/serverSentEvents.gen.d.ts +71 -0
  41. package/dist/generated/projects/core/serverSentEvents.gen.js +132 -0
  42. package/dist/generated/projects/core/types.gen.d.ts +83 -0
  43. package/dist/generated/projects/core/types.gen.js +2 -0
  44. package/dist/generated/projects/core/utils.gen.d.ts +19 -0
  45. package/dist/generated/projects/core/utils.gen.js +87 -0
  46. package/dist/generated/projects/index.d.ts +2 -0
  47. package/dist/generated/projects/index.js +2 -0
  48. package/dist/generated/projects/sdk.gen.d.ts +47 -0
  49. package/dist/generated/projects/sdk.gen.js +55 -0
  50. package/dist/generated/projects/types.gen.d.ts +388 -0
  51. package/dist/generated/projects/types.gen.js +2 -0
  52. package/dist/generated/projects.d.ts +54 -0
  53. package/dist/generated/projects.js +58 -0
  54. package/dist/generated/specs/projects.json +872 -0
  55. package/dist/generated/specs/sts.json +942 -0
  56. package/dist/generated/sts/client/client.gen.d.ts +2 -0
  57. package/dist/generated/sts/client/client.gen.js +216 -0
  58. package/dist/generated/sts/client/index.d.ts +10 -0
  59. package/dist/generated/sts/client/index.js +6 -0
  60. package/dist/generated/sts/client/types.gen.d.ts +120 -0
  61. package/dist/generated/sts/client/types.gen.js +2 -0
  62. package/dist/generated/sts/client/utils.gen.d.ts +37 -0
  63. package/dist/generated/sts/client/utils.gen.js +228 -0
  64. package/dist/generated/sts/client.gen.d.ts +12 -0
  65. package/dist/generated/sts/client.gen.js +3 -0
  66. package/dist/generated/sts/core/auth.gen.d.ts +25 -0
  67. package/dist/generated/sts/core/auth.gen.js +14 -0
  68. package/dist/generated/sts/core/bodySerializer.gen.d.ts +25 -0
  69. package/dist/generated/sts/core/bodySerializer.gen.js +57 -0
  70. package/dist/generated/sts/core/params.gen.d.ts +43 -0
  71. package/dist/generated/sts/core/params.gen.js +109 -0
  72. package/dist/generated/sts/core/pathSerializer.gen.d.ts +33 -0
  73. package/dist/generated/sts/core/pathSerializer.gen.js +106 -0
  74. package/dist/generated/sts/core/queryKeySerializer.gen.d.ts +18 -0
  75. package/dist/generated/sts/core/queryKeySerializer.gen.js +92 -0
  76. package/dist/generated/sts/core/serverSentEvents.gen.d.ts +71 -0
  77. package/dist/generated/sts/core/serverSentEvents.gen.js +132 -0
  78. package/dist/generated/sts/core/types.gen.d.ts +83 -0
  79. package/dist/generated/sts/core/types.gen.js +2 -0
  80. package/dist/generated/sts/core/utils.gen.d.ts +19 -0
  81. package/dist/generated/sts/core/utils.gen.js +87 -0
  82. package/dist/generated/sts/index.d.ts +2 -0
  83. package/dist/generated/sts/index.js +2 -0
  84. package/dist/generated/sts/sdk.gen.d.ts +41 -0
  85. package/dist/generated/sts/sdk.gen.js +44 -0
  86. package/dist/generated/sts/types.gen.d.ts +445 -0
  87. package/dist/generated/sts/types.gen.js +2 -0
  88. package/dist/generated/sts.d.ts +44 -0
  89. package/dist/generated/sts.js +49 -0
  90. package/dist/index.d.ts +14 -0
  91. package/dist/index.js +13 -0
  92. package/package.json +42 -5
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Client configuration (spec §10.6): which credential a client uses, as whom
3
+ * (org, role), and where its calls go (environment, region, origins).
4
+ *
5
+ * Every setting is taken from the first place that has it: the client's
6
+ * options, then `OLYZON_*` environment variables, then the profile of the
7
+ * config and credentials files (`~/.config/olyzon/config`, `credentials`),
8
+ * then built-in defaults; in a browser, a page's Clerk session is the last
9
+ * credential tried. Environment variables and files are read once, when the
10
+ * client is created, and never in a browser.
11
+ *
12
+ * Environments and regions are named as in the hosts:
13
+ * `<service>.<region>.<environment>.api.olyzon.ai` (`sts.us.stg.api.olyzon.ai`).
14
+ * Nothing here knows any service: the generated index gives their names.
15
+ */
16
+ import { ConfigurationError } from "./errors.js";
17
+ export const ENVIRONMENTS = ["local", "stg", "prod"];
18
+ export const REGIONS = ["us", "eu"];
19
+ /** `https://sts.us.stg.api.olyzon.ai` */
20
+ export function deployedOrigin(service, environment, region) {
21
+ return `https://${service}.${region}.${environment}.api.olyzon.ai`;
22
+ }
23
+ /** Settings a profile in the config file may hold, besides one origin per API. */
24
+ export const CONFIG_KEYS = new Set([
25
+ "environment",
26
+ "region",
27
+ "org_id",
28
+ "role",
29
+ ]);
30
+ /** Settings a profile in the credentials file may hold: one of them. */
31
+ export const CREDENTIAL_KEYS = {
32
+ api_key: "apiKey",
33
+ m2m_token: "m2mToken",
34
+ };
35
+ const ENV_CREDENTIALS = {
36
+ OLYZON_API_KEY: "apiKey",
37
+ OLYZON_M2M_TOKEN: "m2mToken",
38
+ };
39
+ const OPTION_CREDENTIALS = [
40
+ "user",
41
+ "apiKey",
42
+ "m2mToken",
43
+ "clerk",
44
+ "getClerkToken",
45
+ ];
46
+ /** `OLYZON_STS_URL` for `sts`, `OLYZON_AD_REPORTS_URL` for `ad-reports`. */
47
+ export function originVariable(service) {
48
+ return `OLYZON_${service.toUpperCase().replaceAll("-", "_")}_URL`;
49
+ }
50
+ /**
51
+ * The config and credentials files: `OLYZON_CONFIG_FILE` and
52
+ * `OLYZON_CREDENTIALS_FILE`, else `$XDG_CONFIG_HOME/olyzon/{config,credentials}`,
53
+ * by default under `~/.config`; `""` without a home directory.
54
+ */
55
+ export function configFiles(env, home) {
56
+ const base = env.XDG_CONFIG_HOME ?? (home ? `${home}/.config` : undefined);
57
+ return {
58
+ config: env.OLYZON_CONFIG_FILE ?? (base ? `${base}/olyzon/config` : ""),
59
+ credentials: env.OLYZON_CREDENTIALS_FILE ?? (base ? `${base}/olyzon/credentials` : ""),
60
+ };
61
+ }
62
+ /**
63
+ * An INI file: `[profile]` sections of `key = value` lines; `#` and `;` start
64
+ * a comment line. Keys are lowercased. Strict, like Python's configparser
65
+ * with the same settings: a repeated section or key, a line outside a section
66
+ * or without `=`, or a continuation line is an error.
67
+ */
68
+ export function parseIni(text, file) {
69
+ const sections = new Map();
70
+ let current;
71
+ text.split(/\r?\n/).forEach((raw, index) => {
72
+ const where = `${file}:${index + 1}`;
73
+ const line = raw.trim();
74
+ if (line === "" || line.startsWith("#") || line.startsWith(";"))
75
+ return;
76
+ if (/^\s/.test(raw))
77
+ throw new ConfigurationError(`${where}: indented line (continuation lines are not supported)`);
78
+ const header = /^\[(.+)\]$/.exec(line);
79
+ if (header) {
80
+ const name = (header[1] ?? "").trim();
81
+ if (sections.has(name))
82
+ throw new ConfigurationError(`${where}: [${name}] is repeated`);
83
+ current = new Map();
84
+ sections.set(name, current);
85
+ return;
86
+ }
87
+ const equals = line.indexOf("=");
88
+ if (equals < 1)
89
+ throw new ConfigurationError(`${where}: expected key = value`);
90
+ if (!current)
91
+ throw new ConfigurationError(`${where}: setting outside a [profile]`);
92
+ const key = line.slice(0, equals).trim().toLowerCase();
93
+ if (current.has(key))
94
+ throw new ConfigurationError(`${where}: ${key} is repeated`);
95
+ current.set(key, line.slice(equals + 1).trim());
96
+ });
97
+ return sections;
98
+ }
99
+ /** Node's `process` (Deno and Bun have one too); none in a browser. */
100
+ function nodeProcess() {
101
+ const candidate = globalThis.process;
102
+ return candidate?.env ? candidate : undefined;
103
+ }
104
+ function defaultReadFile(path) {
105
+ const fs = nodeProcess()?.getBuiltinModule?.("node:fs");
106
+ if (!fs)
107
+ return undefined;
108
+ try {
109
+ return fs.readFileSync(path, "utf8");
110
+ }
111
+ catch (error) {
112
+ if (error.code === "ENOENT")
113
+ return undefined;
114
+ throw error;
115
+ }
116
+ }
117
+ function defaultHome() {
118
+ const os = nodeProcess()?.getBuiltinModule?.("node:os");
119
+ return os?.homedir();
120
+ }
121
+ function defaultBrowserClerk() {
122
+ const scope = globalThis;
123
+ return scope.window !== undefined ? scope.Clerk : undefined;
124
+ }
125
+ /** `https://host/` → `https://host`; anything but an http(s) origin is refused. */
126
+ function origin(value, from) {
127
+ let url;
128
+ try {
129
+ url = new URL(value);
130
+ }
131
+ catch {
132
+ throw new ConfigurationError(`${from}: ${value} is not a URL`);
133
+ }
134
+ if (!["http:", "https:"].includes(url.protocol) ||
135
+ url.pathname !== "/" ||
136
+ url.search !== "" ||
137
+ url.hash !== "" ||
138
+ url.username !== "")
139
+ throw new ConfigurationError(`${from}: ${value} must be an origin (http(s)://host[:port])`);
140
+ return url.origin;
141
+ }
142
+ /** The first value set (an empty string is unset), with where it came from. */
143
+ function first(...candidates) {
144
+ for (const [value, from] of candidates)
145
+ if (value !== undefined && value !== null && value !== "")
146
+ return [value, from];
147
+ return undefined;
148
+ }
149
+ const isEnvironment = (value) => ENVIRONMENTS.includes(value);
150
+ /** Resolves a client's configuration (spec §10.6). Throws `ConfigurationError`. */
151
+ export function resolveClientConfig(options, context) {
152
+ const services = context.services.includes("sts")
153
+ ? [...context.services]
154
+ : ["sts", ...context.services];
155
+ const ambient = options.fromEnvironment !== false;
156
+ const env = ambient
157
+ ? (context.env ?? nodeProcess()?.env ?? {})
158
+ : {};
159
+ const from = {};
160
+ // The profile: its config and credentials sections.
161
+ const explicitProfile = first([options.profile, "options.profile"], [env.OLYZON_PROFILE, "OLYZON_PROFILE"]);
162
+ if (explicitProfile && !ambient)
163
+ throw new ConfigurationError(`${explicitProfile[1]}: profiles live in files, which fromEnvironment: false turns off`);
164
+ const profile = explicitProfile?.[0] ?? "default";
165
+ if (isEnvironment(profile))
166
+ throw new ConfigurationError(`${explicitProfile?.[1] ?? "profile"}: "${profile}" is an environment, not a profile: set environment "${profile}" (OLYZON_ENVIRONMENT=${profile})`);
167
+ const { config: configFile, credentials: credentialsFile } = configFiles(env, context.home ?? defaultHome());
168
+ let config;
169
+ let credentials;
170
+ if (ambient) {
171
+ const read = context.readFile ?? defaultReadFile;
172
+ const load = (file, allowed) => {
173
+ const text = file ? read(file) : undefined;
174
+ if (text === undefined)
175
+ return undefined;
176
+ const sections = parseIni(text, file);
177
+ for (const [name, settings] of sections) {
178
+ if (isEnvironment(name))
179
+ throw new ConfigurationError(`${file}: [${name}] is an environment and cannot be a profile: name it otherwise and set environment = ${name} in it`);
180
+ for (const key of settings.keys())
181
+ if (!allowed(key))
182
+ throw new ConfigurationError(`${file}: [${name}] ${key} is not a setting`);
183
+ }
184
+ return sections.get(profile);
185
+ };
186
+ config = load(configFile, (key) => CONFIG_KEYS.has(key) || services.includes(key));
187
+ credentials = load(credentialsFile, (key) => key in CREDENTIAL_KEYS);
188
+ if (explicitProfile && !config && !credentials)
189
+ throw new ConfigurationError(`${explicitProfile[1]}: no profile [${profile}] in ${configFile} or ${credentialsFile}`);
190
+ }
191
+ const inConfig = `config [${profile}]`;
192
+ const inCredentials = `credentials [${profile}]`;
193
+ // The credential: the first place that has one, which must have only one.
194
+ const credential = (() => {
195
+ const given = OPTION_CREDENTIALS.filter((kind) => options[kind] !== undefined && options[kind] !== "");
196
+ if (given.length > 1)
197
+ throw new ConfigurationError(`give one credential, not ${given.map((k) => `options.${k}`).join(" and ")}`);
198
+ const option = given[0];
199
+ if (option) {
200
+ from.credential = `options.${option}`;
201
+ return { kind: option, [option]: options[option] };
202
+ }
203
+ const variables = Object.keys(ENV_CREDENTIALS).filter((v) => env[v]);
204
+ if (variables.length > 1)
205
+ throw new ConfigurationError(`set one credential, not ${variables.join(" and ")}`);
206
+ const variable = variables[0];
207
+ if (variable) {
208
+ const kind = ENV_CREDENTIALS[variable];
209
+ from.credential = variable;
210
+ return { kind, [kind]: env[variable] };
211
+ }
212
+ const keys = Object.keys(CREDENTIAL_KEYS).filter((k) => credentials?.get(k));
213
+ if (keys.length > 1)
214
+ throw new ConfigurationError(`${credentialsFile}: [${profile}] has ${keys.join(" and ")}: keep one`);
215
+ const key = keys[0];
216
+ if (key) {
217
+ const kind = CREDENTIAL_KEYS[key];
218
+ from.credential = `${inCredentials} ${key}`;
219
+ return { kind, [kind]: credentials?.get(key) };
220
+ }
221
+ const clerk = context.browserClerk ?? defaultBrowserClerk();
222
+ if (clerk) {
223
+ from.credential = "Clerk";
224
+ return { kind: "clerk", clerk };
225
+ }
226
+ throw new ConfigurationError([
227
+ "no credential found. Looked in:",
228
+ `- options: ${OPTION_CREDENTIALS.join(", ")}`,
229
+ ambient
230
+ ? `- environment: ${Object.keys(ENV_CREDENTIALS).join(", ")}`
231
+ : "- environment: not read (fromEnvironment: false)",
232
+ ambient
233
+ ? `- ${credentialsFile || "credentials file"} [${profile}]: ${Object.keys(CREDENTIAL_KEYS).join(", ")}`
234
+ : "- files: not read (fromEnvironment: false)",
235
+ "- the page's Clerk session (browser only)",
236
+ ].join("\n"));
237
+ })();
238
+ // As whom.
239
+ const orgSetting = first([options.orgId, "options.orgId"], [env.OLYZON_ORG_ID, "OLYZON_ORG_ID"], [config?.get("org_id"), `${inConfig} org_id`]);
240
+ let orgId;
241
+ if (orgSetting) {
242
+ const [value, source] = orgSetting;
243
+ // Clerk's org IDs all start with org_: anything else (an API key pasted
244
+ // in the wrong place) is refused here, before it reaches the STS.
245
+ if (typeof value === "string" && !value.startsWith("org_"))
246
+ throw new ConfigurationError(`${source}: "${value.slice(0, 6)}…" is not an org ID: Clerk's org IDs start with org_`);
247
+ orgId = typeof value === "function" ? () => value() ?? undefined : value;
248
+ from.orgId = source;
249
+ }
250
+ else if (credential.kind === "clerk") {
251
+ const { clerk } = credential;
252
+ orgId = () => clerk.organization?.id;
253
+ from.orgId = "Clerk (active org)";
254
+ }
255
+ const roleSetting = first([options.role, "options.role"], [env.OLYZON_ROLE, "OLYZON_ROLE"], [config?.get("role"), `${inConfig} role`]);
256
+ const role = roleSetting?.[0];
257
+ if (roleSetting)
258
+ from.role = roleSetting[1];
259
+ const orgFrom = from.orgId ?? "orgId";
260
+ const roleFrom = from.role ?? "role";
261
+ switch (credential.kind) {
262
+ case "apiKey":
263
+ if (orgId !== undefined && role !== undefined)
264
+ throw new ConfigurationError(`an API key acts either as you in an org (a user API key: ${orgFrom}) or as its org with a role (an org API key: ${roleFrom}), not both: remove one`);
265
+ if (orgId === undefined && role === undefined)
266
+ throw new ConfigurationError(`an API key needs an org (a user API key: OLYZON_ORG_ID) or a role (an org API key: OLYZON_ROLE), from ${from.credential}`);
267
+ break;
268
+ // A machine's org can come later, from the caller it forwards
269
+ // (`clientScope`); its role cannot.
270
+ case "m2mToken":
271
+ // Machines hold short-lived tokens only, never the secret that mints
272
+ // them: a secret given here would reach the STS, which refuses it.
273
+ if (!credential.m2mToken.startsWith("mt_"))
274
+ throw new ConfigurationError(`${from.credential} is not an M2M token (mt_…): machines hold M2M tokens minted with an expiry, never their Clerk machine secret`);
275
+ if (role === undefined)
276
+ throw new ConfigurationError(`a machine credential (${from.credential}) needs a role (OLYZON_ROLE)`);
277
+ break;
278
+ }
279
+ // Where.
280
+ const environmentSetting = first([options.environment, "options.environment"], [env.OLYZON_ENVIRONMENT, "OLYZON_ENVIRONMENT"], [config?.get("environment"), `${inConfig} environment`]) ?? [context.defaultEnvironment, "built-in"];
281
+ const [environmentValue, environmentFrom] = environmentSetting;
282
+ if (!isEnvironment(environmentValue))
283
+ throw new ConfigurationError(`${environmentFrom}: "${environmentValue}" is not ${ENVIRONMENTS.join(", ")}`);
284
+ const environment = environmentValue;
285
+ from.environment = environmentFrom;
286
+ const regionSetting = first([options.region, "options.region"], [env.OLYZON_REGION, "OLYZON_REGION"], [config?.get("region"), `${inConfig} region`]);
287
+ if (regionSetting &&
288
+ !REGIONS.includes(regionSetting[0]))
289
+ throw new ConfigurationError(`${regionSetting[1]}: "${regionSetting[0]}" is not ${REGIONS.join(" or ")}`);
290
+ const region = regionSetting?.[0];
291
+ if (regionSetting)
292
+ from.region = regionSetting[1];
293
+ for (const name of Object.keys(options.endpoints ?? {}))
294
+ if (!services.includes(name))
295
+ throw new ConfigurationError(`options.endpoints.${name}: no such API (${services.join(", ")})`);
296
+ const origins = {};
297
+ for (const service of services) {
298
+ const variable = originVariable(service);
299
+ const set = first([options.endpoints?.[service], `options.endpoints.${service}`], [env[variable], variable], [config?.get(service), `${inConfig} ${service}`]);
300
+ if (set) {
301
+ origins[service] = origin(set[0], set[1]);
302
+ from[service] = set[1];
303
+ }
304
+ else if (environment === "local") {
305
+ const port = context.localPorts[service];
306
+ if (port === undefined)
307
+ throw new ConfigurationError(`no local port for ${service}: set ${variable} or options.endpoints.${service}`);
308
+ origins[service] = `http://localhost:${port}`;
309
+ from[service] = "built-in";
310
+ }
311
+ else {
312
+ if (!region)
313
+ throw new ConfigurationError(`${environment} hosts depend on the region, and none is set: set region (option), OLYZON_REGION or region in your profile: ${REGIONS.join(" or ")}`);
314
+ origins[service] = deployedOrigin(service, environment, region);
315
+ from[service] = "built-in";
316
+ }
317
+ }
318
+ return {
319
+ credential,
320
+ orgId,
321
+ role,
322
+ environment,
323
+ region,
324
+ profile: config || credentials ? profile : undefined,
325
+ origins,
326
+ from,
327
+ };
328
+ }
329
+ /** The configuration without the credential itself. */
330
+ export function clientSettings(config) {
331
+ const { credential, orgId, ...rest } = config;
332
+ return {
333
+ ...rest,
334
+ credential: credential.kind,
335
+ orgId: typeof orgId === "function" ? undefined : orgId,
336
+ };
337
+ }
338
+ /** The org and session of a client's own calls, from its configuration. */
339
+ export function clientScope(config) {
340
+ const { credential, orgId, role } = config;
341
+ const machine = credential.kind === "m2mToken";
342
+ const scope = {
343
+ orgId: () => (typeof orgId === "function" ? orgId() : orgId),
344
+ session() {
345
+ const org = scope.orgId();
346
+ if (machine && org === undefined)
347
+ throw new ConfigurationError(`a machine credential (${config.from.credential}) needs an org (OLYZON_ORG_ID) for calls of its own; without one, it only calls on behalf of a caller (onBehalfOf)`);
348
+ return { orgId: org, role };
349
+ },
350
+ };
351
+ return scope;
352
+ }
353
+ /**
354
+ * The Clerk token the STS exchanges, for any credential but an existing user
355
+ * client: read again at every exchange.
356
+ */
357
+ export function clerkTokenSource(credential) {
358
+ switch (credential.kind) {
359
+ case "apiKey":
360
+ return () => Promise.resolve(credential.apiKey);
361
+ case "m2mToken":
362
+ return () => Promise.resolve(credential.m2mToken);
363
+ case "clerk":
364
+ return async () => (await credential.clerk.session?.getToken()) ?? null;
365
+ case "getClerkToken":
366
+ return credential.getClerkToken;
367
+ }
368
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * What the SDK and the STS agree on (shady-packages' `@olyzon-tv/contracts`): RFC
3
+ * 8693's names, the token endpoint's answers and a session's claims.
4
+ */
5
+ /** RFC 8693's grant type: the only one the STS supports. */
6
+ export declare const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
7
+ /** Every Clerk credential is exchanged with this subject token type. */
8
+ export declare const CLERK_TOKEN_TYPE = "urn:olyzon:token-type:clerk";
9
+ /** A grant's ID, exchanged by its actor (spec §6.3). */
10
+ export declare const GRANT_TOKEN_TYPE = "urn:olyzon:token-type:grant";
11
+ /** The only token the STS issues: a DPoP-bound access token, the session. */
12
+ export declare const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
13
+ /** The token endpoint's answer. */
14
+ export interface TokenResponse {
15
+ access_token: string;
16
+ token_type: string;
17
+ issued_token_type?: string;
18
+ /** Seconds. */
19
+ expires_in: number;
20
+ }
21
+ /** An Olyzon session's claims (a JWT signed by the STS), as far as clients read them. */
22
+ export interface SessionClaims {
23
+ iss: string;
24
+ sub: string;
25
+ kind: "user" | "org" | "service";
26
+ /** The workspace (Clerk org) the session acts in. */
27
+ org: string;
28
+ org_name?: string;
29
+ role: string;
30
+ azp: string;
31
+ cred: "session" | "oauth" | "api_key" | "m2m" | "grant";
32
+ kn?: string;
33
+ name?: string;
34
+ email?: string;
35
+ /** The one service a delegated session is for (its origin). */
36
+ aud?: string;
37
+ act?: {
38
+ sub: string;
39
+ act?: unknown;
40
+ };
41
+ grant?: {
42
+ id: string;
43
+ actions: string[];
44
+ };
45
+ sid: string;
46
+ /** The key the session is bound to: this client's. */
47
+ cnf: {
48
+ jkt: string;
49
+ };
50
+ iat: number;
51
+ exp: number;
52
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * What the SDK and the STS agree on (shady-packages' `@olyzon-tv/contracts`): RFC
3
+ * 8693's names, the token endpoint's answers and a session's claims.
4
+ */
5
+ /** RFC 8693's grant type: the only one the STS supports. */
6
+ export const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
7
+ /** Every Clerk credential is exchanged with this subject token type. */
8
+ export const CLERK_TOKEN_TYPE = "urn:olyzon:token-type:clerk";
9
+ /** A grant's ID, exchanged by its actor (spec §6.3). */
10
+ export const GRANT_TOKEN_TYPE = "urn:olyzon:token-type:grant";
11
+ /** The only token the STS issues: a DPoP-bound access token, the session. */
12
+ export const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
@@ -0,0 +1,39 @@
1
+ /** The forwarded caller's session (spec §6.1). */
2
+ export declare const FORWARDED_SESSION_HEADER = "X-Olyzon-User-Session";
3
+ /** The proof the forwarded caller sent with it. */
4
+ export declare const FORWARDED_PROOF_HEADER = "X-Olyzon-User-Proof";
5
+ export interface PublicJwk {
6
+ kty: "EC";
7
+ crv: "P-256";
8
+ x: string;
9
+ y: string;
10
+ }
11
+ export interface DpopKeyPair {
12
+ /** Non-extractable private key: it never leaves the WebCrypto store. */
13
+ privateKey: CryptoKey;
14
+ publicJwk: PublicJwk;
15
+ /** RFC 7638 thumbprint of `publicJwk`: a session's `cnf.jkt`. */
16
+ jkt: string;
17
+ }
18
+ /** base64url(SHA-256(data)), a string hashed as UTF-8. */
19
+ export declare function sha256(data: string | Uint8Array): Promise<string>;
20
+ /** An ES256 key pair whose private key cannot be exported. */
21
+ export declare function generateDpopKeyPair(): Promise<DpopKeyPair>;
22
+ export interface CreateProofOptions {
23
+ key: DpopKeyPair;
24
+ method: string;
25
+ /** The full request URL, exactly as it is fetched. */
26
+ url: string | URL;
27
+ /** The exact body bytes (a string is hashed as UTF-8); omitted means empty. */
28
+ body?: Uint8Array | string;
29
+ /** The session the proof accompanies (`ath`); none at the token endpoint. */
30
+ accessToken?: string;
31
+ /** The server's nonce (`DPoP-Nonce`), where one is required. */
32
+ nonce?: string;
33
+ /** The forwarded credentials the request carries: their `forwardedHash`. */
34
+ obo?: string;
35
+ }
36
+ /** What a forwarding service's proof says of the credentials it forwards (`obo`). */
37
+ export declare function forwardedHash(session: string, proof: string): Promise<string>;
38
+ /** A signed proof for one request. */
39
+ export declare function createProof(options: CreateProofOptions): Promise<string>;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * DPoP proofs (RFC 9449) with Olyzon's claims, the client side of shady-sts's
3
+ * `@olyzon-tv/dpop` (shady-packages), which verifies them: keep the two in
4
+ * step. The published SDK cannot depend on that private package: the
5
+ * repository's tests check this copy against it (test/dpop-conformance.test.ts).
6
+ *
7
+ * Besides RFC 9449's claims, a proof covers the request's query (`htq`) and
8
+ * its body (`hbd`), so a proof copied from one request is useless with any
9
+ * other query or body. A service calling another one for its caller forwards
10
+ * the caller's session and proof, and its own proof covers them (`obo`).
11
+ * WebCrypto only: the same code runs in Node, browsers and other runtimes.
12
+ */
13
+ import { SignJWT, base64url, calculateJwkThumbprint } from "jose";
14
+ /** The forwarded caller's session (spec §6.1). */
15
+ export const FORWARDED_SESSION_HEADER = "X-Olyzon-User-Session";
16
+ /** The proof the forwarded caller sent with it. */
17
+ export const FORWARDED_PROOF_HEADER = "X-Olyzon-User-Proof";
18
+ /** base64url(SHA-256(data)), a string hashed as UTF-8. */
19
+ export async function sha256(data) {
20
+ const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
21
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
22
+ return base64url.encode(new Uint8Array(digest));
23
+ }
24
+ /** An ES256 key pair whose private key cannot be exported. */
25
+ export async function generateDpopKeyPair() {
26
+ const { privateKey, publicKey } = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
27
+ const { x, y } = await crypto.subtle.exportKey("jwk", publicKey);
28
+ if (!x || !y)
29
+ throw new Error("the generated key has no coordinates");
30
+ const publicJwk = { kty: "EC", crv: "P-256", x, y };
31
+ const jkt = await calculateJwkThumbprint(publicJwk, "sha256");
32
+ return { privateKey, publicJwk, jkt };
33
+ }
34
+ /** What a forwarding service's proof says of the credentials it forwards (`obo`). */
35
+ export function forwardedHash(session, proof) {
36
+ return sha256(`${session}.${proof}`);
37
+ }
38
+ /** A signed proof for one request. */
39
+ export async function createProof(options) {
40
+ const url = new URL(options.url);
41
+ const claims = {
42
+ jti: crypto.randomUUID(),
43
+ htm: options.method.toUpperCase(),
44
+ // Scheme, host and path: no query, no fragment (`@olyzon-tv/dpop`'s htu).
45
+ htu: url.origin + url.pathname,
46
+ iat: Math.floor(Date.now() / 1000),
47
+ htq: await sha256(url.search.slice(1)),
48
+ hbd: await sha256(options.body ?? ""),
49
+ };
50
+ if (options.accessToken !== undefined)
51
+ claims.ath = await sha256(options.accessToken);
52
+ if (options.nonce !== undefined)
53
+ claims.nonce = options.nonce;
54
+ if (options.obo !== undefined)
55
+ claims.obo = options.obo;
56
+ return new SignJWT(claims)
57
+ .setProtectedHeader({
58
+ typ: "dpop+jwt",
59
+ alg: "ES256",
60
+ jwk: options.key.publicJwk,
61
+ })
62
+ .sign(options.key.privateKey);
63
+ }
@@ -0,0 +1,34 @@
1
+ /** The errors the SDK throws, besides the platform's own (`TypeError` for network failures). */
2
+ /** A configuration the SDK refuses: the message says what to change. */
3
+ export declare class ConfigurationError extends Error {
4
+ constructor(message: string);
5
+ }
6
+ /**
7
+ * The STS refused to issue a session: RFC 6749's `error` (`invalid_grant`,
8
+ * `invalid_target`, `invalid_dpop_proof`, …) and its description.
9
+ */
10
+ export declare class StsError extends Error {
11
+ readonly code: string;
12
+ readonly status: number | undefined;
13
+ constructor(code: string, message: string, status?: number);
14
+ }
15
+ /** An error answered by an Olyzon service: its `{ error, error_description }` and the HTTP status. */
16
+ export declare class ServiceError extends Error {
17
+ /** The service that answered: `sts`, … */
18
+ readonly service: string;
19
+ readonly status: number;
20
+ /** The body's `error`: `invalid_request`, `forbidden`, `not_found`, … */
21
+ readonly code: string;
22
+ /** The answer's body, parsed when it is JSON. */
23
+ readonly body: unknown;
24
+ /** `WWW-Authenticate` of a 401: the DPoP challenge. */
25
+ readonly challenge: string | undefined;
26
+ constructor(options: {
27
+ service: string;
28
+ status: number;
29
+ code: string;
30
+ message: string;
31
+ body?: unknown;
32
+ challenge?: string | undefined;
33
+ });
34
+ }
@@ -0,0 +1,43 @@
1
+ /** The errors the SDK throws, besides the platform's own (`TypeError` for network failures). */
2
+ /** A configuration the SDK refuses: the message says what to change. */
3
+ export class ConfigurationError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = "ConfigurationError";
7
+ }
8
+ }
9
+ /**
10
+ * The STS refused to issue a session: RFC 6749's `error` (`invalid_grant`,
11
+ * `invalid_target`, `invalid_dpop_proof`, …) and its description.
12
+ */
13
+ export class StsError extends Error {
14
+ code;
15
+ status;
16
+ constructor(code, message, status) {
17
+ super(message);
18
+ this.name = "StsError";
19
+ this.code = code;
20
+ this.status = status;
21
+ }
22
+ }
23
+ /** An error answered by an Olyzon service: its `{ error, error_description }` and the HTTP status. */
24
+ export class ServiceError extends Error {
25
+ /** The service that answered: `sts`, … */
26
+ service;
27
+ status;
28
+ /** The body's `error`: `invalid_request`, `forbidden`, `not_found`, … */
29
+ code;
30
+ /** The answer's body, parsed when it is JSON. */
31
+ body;
32
+ /** `WWW-Authenticate` of a 401: the DPoP challenge. */
33
+ challenge;
34
+ constructor(options) {
35
+ super(options.message);
36
+ this.name = "ServiceError";
37
+ this.service = options.service;
38
+ this.status = options.status;
39
+ this.code = options.code;
40
+ this.body = options.body;
41
+ this.challenge = options.challenge;
42
+ }
43
+ }