cauthy-auth 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -44,7 +44,18 @@ Built with Stackmyth? Give Cauthy's pages your application's look from its own t
44
44
  npx cauthy-auth theme --css node_modules/@stackmyth/core/core.vars.css --css src/styles/brand-theme.css --push
45
45
  ```
46
46
 
47
- Register your application in Cauthy with the redirect URI `https://<your app>/api/auth/callback`. `CAUTHY_SECRET` is any string of 32 characters or more: it encrypts the session cookie.
47
+ Connect your application to Cauthy in one step, from Cauthy's dashboard ("Connect a System") or from a terminal. It makes the client, registers `https://<your app>/api/auth/callback`, and prints every variable to set, `CAUTHY_SECRET` included:
48
+
49
+ ```bash
50
+ npx cauthy-auth init --system ledger --app-url https://app.example.com
51
+ ```
52
+
53
+ The same client is your application's own identity: it manages its organizations with no person's token.
54
+
55
+ ```ts
56
+ const org = await auth.system.organizations.create({ name: 'Acme' })
57
+ await auth.system.members.add(org.id, { role: 'owner', email: 'ana@acme.com' })
58
+ ```
48
59
 
49
60
  The full guide is in Cauthy's documentation, under "Auth SDK".
50
61
 
@@ -1,5 +1,5 @@
1
+ import { J as JsonValue, S as Session, f as SessionStatus, e as SessionOrganization, c as CauthySystem, P as PublicSession, b as CauthyOptions } from './system-BWLddIt2.js';
1
2
  import { JWTVerifyGetKey } from 'jose';
2
- import { J as JsonValue, S as Session, c as SessionStatus, b as SessionOrganization, P as PublicSession, a as CauthyOptions } from './types-CYmUVWzY.mjs';
3
3
 
4
4
  /** Something that happened in Cauthy, as a subscriber is told. Moments are UTC. */
5
5
  interface CauthyEvent {
@@ -86,6 +86,12 @@ interface Cauthy {
86
86
  * delivery is signed with Cauthy's own key.
87
87
  */
88
88
  webhook(request: Request, options?: Pick<VerifyWebhookOptions, 'jwks' | 'now' | 'url'>): Promise<CauthyEvent>;
89
+ /**
90
+ * The application acting on its own, with no person's token: its
91
+ * organizations, their members, invitations. Needs the client's secret, or
92
+ * `systemKey`.
93
+ */
94
+ system: CauthySystem;
89
95
  /** What the browser may be told of a session. */
90
96
  toPublic(session: Session): Promise<PublicSession>;
91
97
  /** Paths of this application that start a sign-in, a sign-out, or open the account page. */
@@ -1,5 +1,5 @@
1
+ import { J as JsonValue, S as Session, f as SessionStatus, e as SessionOrganization, c as CauthySystem, P as PublicSession, b as CauthyOptions } from './system-BWLddIt2.mjs';
1
2
  import { JWTVerifyGetKey } from 'jose';
2
- import { J as JsonValue, S as Session, c as SessionStatus, b as SessionOrganization, P as PublicSession, a as CauthyOptions } from './types-CYmUVWzY.js';
3
3
 
4
4
  /** Something that happened in Cauthy, as a subscriber is told. Moments are UTC. */
5
5
  interface CauthyEvent {
@@ -86,6 +86,12 @@ interface Cauthy {
86
86
  * delivery is signed with Cauthy's own key.
87
87
  */
88
88
  webhook(request: Request, options?: Pick<VerifyWebhookOptions, 'jwks' | 'now' | 'url'>): Promise<CauthyEvent>;
89
+ /**
90
+ * The application acting on its own, with no person's token: its
91
+ * organizations, their members, invitations. Needs the client's secret, or
92
+ * `systemKey`.
93
+ */
94
+ system: CauthySystem;
89
95
  /** What the browser may be told of a session. */
90
96
  toPublic(session: Session): Promise<PublicSession>;
91
97
  /** Paths of this application that start a sign-in, a sign-out, or open the account page. */
package/dist/cli.js CHANGED
@@ -4,6 +4,53 @@
4
4
  // src/cli.ts
5
5
  var import_node_fs = require("fs");
6
6
 
7
+ // src/connect.ts
8
+ function sessionSecret() {
9
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
10
+ let s = "";
11
+ for (const b of bytes) s += String.fromCharCode(b);
12
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
13
+ }
14
+ async function connectSystem(o) {
15
+ const env = (n) => typeof process !== "undefined" ? process.env?.[n] : void 0;
16
+ const issuer = (o.issuer ?? env("CAUTHY_ISSUER") ?? "").replace(/\/+$/, "");
17
+ const tenant = o.tenant ?? env("CAUTHY_TENANT") ?? "";
18
+ const token = o.token ?? env("CAUTHY_TOKEN") ?? "";
19
+ for (const [name, v] of Object.entries({ CAUTHY_ISSUER: issuer, CAUTHY_TENANT: tenant, CAUTHY_TOKEN: token })) {
20
+ if (v === "") throw new Error(`cauthy-auth: ${name} is required to connect a system`);
21
+ }
22
+ const res = await (o.fetch ?? fetch)(`${issuer}/v1/connect`, {
23
+ method: "POST",
24
+ headers: { authorization: `Bearer ${token}`, "x-tenant-key": tenant, "content-type": "application/json" },
25
+ body: JSON.stringify({
26
+ system: o.system,
27
+ app_url: o.appUrl,
28
+ name: o.name,
29
+ callback_path: o.callbackPath,
30
+ events_url: o.eventsUrl,
31
+ events: o.events,
32
+ jwks_uri: o.jwksUri
33
+ })
34
+ });
35
+ const body = await res.json().catch(() => null);
36
+ if (!res.ok || !body?.data) {
37
+ const why = (body?.errors ?? []).map((e) => e.message).filter(Boolean).join("; ") || res.statusText;
38
+ throw new Error(`cauthy-auth: Cauthy did not connect the system (${res.status}): ${why}`);
39
+ }
40
+ const d = body.data;
41
+ return {
42
+ system: d.system,
43
+ clientId: d.client.client_id,
44
+ clientSecret: d.client_secret,
45
+ redirectUris: d.client.redirect_uris,
46
+ webhook: d.webhook,
47
+ env: { ...d.env, CAUTHY_SECRET: sessionSecret() }
48
+ };
49
+ }
50
+ function envFile(env) {
51
+ return Object.entries(env).map(([k, v]) => `${k}=${v}`).join("\n") + "\n";
52
+ }
53
+
7
54
  // src/permissions.ts
8
55
  async function pushPolicy(o) {
9
56
  const env = (n) => typeof process !== "undefined" ? process.env?.[n] : void 0;
@@ -246,6 +293,77 @@ async function pushTheme(o) {
246
293
  }
247
294
 
248
295
  // src/cli.ts
296
+ var INIT_HELP = `cauthy-auth init --system <name> --app-url <address> [options]
297
+
298
+ Connects an application to Cauthy: makes its client, registers where its people
299
+ come back to and where it hears events, and prints the variables to set.
300
+
301
+ --system <name> The system's name: lowercase letters, digits, - or _.
302
+ --app-url <address> The application's public address: https://app.example.com,
303
+ or http://localhost:3000 while developing.
304
+ --name <name> Shown to people on Cauthy's pages. Default: the system's name.
305
+ --callback-path <path> Where the application serves the return from a sign-in.
306
+ Default: /api/auth/callback.
307
+ --events-url <address> An https address of the application that receives
308
+ Cauthy's events (verify them with auth.webhook).
309
+ --jwks-uri <address> Where the application publishes its keys, to prove
310
+ itself with a signature instead of its secret.
311
+ --write <file> Append the variables to this file instead of printing
312
+ them (they include the client's secret, shown once).
313
+
314
+ Needs CAUTHY_ISSUER, CAUTHY_TENANT (the workspace's slug) and CAUTHY_TOKEN (a
315
+ personal access token with systems:connect).
316
+ `;
317
+ async function init(argv) {
318
+ if (argv.includes("--help") || argv.includes("-h")) {
319
+ process.stdout.write(INIT_HELP);
320
+ return;
321
+ }
322
+ const given = {};
323
+ const flags = ["--system", "--app-url", "--name", "--callback-path", "--events-url", "--jwks-uri", "--write"];
324
+ for (let i = 0; i < argv.length; i++) {
325
+ const arg = argv[i];
326
+ if (!flags.includes(arg)) fail(`unknown option ${arg}
327
+
328
+ ${INIT_HELP}`);
329
+ given[arg] = argv[++i] ?? fail(`${arg} needs a value`);
330
+ }
331
+ if (!given["--system"] || !given["--app-url"]) fail("give --system and --app-url\n\n" + INIT_HELP);
332
+ const done = await connectSystem({
333
+ system: given["--system"],
334
+ appUrl: given["--app-url"],
335
+ name: given["--name"],
336
+ callbackPath: given["--callback-path"],
337
+ eventsUrl: given["--events-url"],
338
+ jwksUri: given["--jwks-uri"]
339
+ });
340
+ const vars = envFile(done.env);
341
+ process.stdout.write(`Connected: the system ${done.system} is the client ${done.clientId}.
342
+ `);
343
+ process.stdout.write(` people come back to ${done.redirectUris.join(", ")}
344
+ `);
345
+ if (done.webhook) process.stdout.write(` events are sent to ${done.webhook.url}
346
+ `);
347
+ if (given["--write"]) {
348
+ (0, import_node_fs.appendFileSync)(given["--write"], vars, { mode: 384 });
349
+ process.stdout.write(`
350
+ The variables were added to ${given["--write"]}. Keep that file out of the repository.
351
+ `);
352
+ } else {
353
+ process.stdout.write(`
354
+ Set these where the application runs. The secret is shown this once:
355
+
356
+ ${vars}`);
357
+ }
358
+ process.stdout.write(`
359
+ Then, in the application:
360
+
361
+ import { createCauthy } from 'cauthy-auth'
362
+ export const auth = createCauthy()
363
+
364
+ and serve auth.handler(request) under ${(given["--callback-path"] ?? "/api/auth/callback").replace(/\/callback$/, "")}/*.
365
+ `);
366
+ }
249
367
  var POLICY_HELP = `cauthy-auth policy --file <roles.json> [--system <name>] [--push]
250
368
 
251
369
  Loads a system's catalog of roles into Cauthy from a file:
@@ -303,7 +421,9 @@ ${POLICY_HELP}`);
303
421
  process.stdout.write("Not sent. Add --push to give it to Cauthy.\n");
304
422
  }
305
423
  }
306
- var HELP = `cauthy-auth theme [options]
424
+ var HELP = `cauthy-auth init \u2026 connect an application to Cauthy (cauthy-auth init --help)
425
+ cauthy-auth policy \u2026 load a system's catalog of roles (cauthy-auth policy --help)
426
+ cauthy-auth theme [options]
307
427
 
308
428
  Reads the application's Stackmyth theme and gives it to Cauthy's hosted pages.
309
429
 
@@ -326,6 +446,7 @@ function fail(message) {
326
446
  }
327
447
  async function main(argv) {
328
448
  if (argv[0] === "policy") return policy(argv.slice(1));
449
+ if (argv[0] === "init") return init(argv.slice(1));
329
450
  if (argv[0] !== "theme" || argv.includes("--help") || argv.includes("-h")) {
330
451
  process.stdout.write(HELP);
331
452
  process.exit(argv[0] === "theme" || argv.length === 0 || argv.includes("--help") || argv.includes("-h") ? 0 : 1);
@@ -377,4 +498,4 @@ ${HELP}`);
377
498
  process.stdout.write("Not sent. Add --push to give it to Cauthy.\n");
378
499
  }
379
500
  }
380
- main(process.argv.slice(2)).catch((err) => fail(err instanceof Error ? err.message.replace(/^@cauthy\/auth: /, "") : String(err)));
501
+ main(process.argv.slice(2)).catch((err) => fail(err instanceof Error ? err.message.replace(/^cauthy-auth: /, "") : String(err)));
@@ -1,6 +1,6 @@
1
1
  import { FastifyReply, FastifyPluginAsync } from 'fastify';
2
- import { C as Cauthy } from './cauthy-BrIMaoj1.mjs';
3
- import { S as Session } from './types-CYmUVWzY.mjs';
2
+ import { C as Cauthy } from './cauthy-mNADGlNl.mjs';
3
+ import { S as Session } from './system-BWLddIt2.mjs';
4
4
  import 'jose';
5
5
 
6
6
  declare module 'fastify' {
package/dist/fastify.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { FastifyReply, FastifyPluginAsync } from 'fastify';
2
- import { C as Cauthy } from './cauthy-CCZc9w8r.js';
3
- import { S as Session } from './types-CYmUVWzY.js';
2
+ import { C as Cauthy } from './cauthy-C5_lopMQ.js';
3
+ import { S as Session } from './system-BWLddIt2.js';
4
4
  import 'jose';
5
5
 
6
6
  declare module 'fastify' {
package/dist/index.d.mts CHANGED
@@ -1,5 +1,49 @@
1
- export { C as Cauthy, a as CauthyEvent, b as CauthyWebhookError, R as Resolved, V as VerifyWebhookOptions, c as createCauthy, v as verifyWebhook } from './cauthy-BrIMaoj1.mjs';
2
- export { C as CauthyConfigError, a as CauthyOptions, J as JsonValue, P as PublicSession, S as Session, b as SessionOrganization, c as SessionStatus, d as SessionUser } from './types-CYmUVWzY.mjs';
1
+ export { C as Cauthy, a as CauthyEvent, b as CauthyWebhookError, R as Resolved, V as VerifyWebhookOptions, c as createCauthy, v as verifyWebhook } from './cauthy-mNADGlNl.mjs';
2
+ export { C as CauthyApiError, a as CauthyConfigError, b as CauthyOptions, c as CauthySystem, J as JsonValue, N as NewMember, O as Organization, d as OrganizationMember, P as PublicSession, S as Session, e as SessionOrganization, f as SessionStatus, g as SessionUser, h as SystemKey, i as SystemOptions, j as createSystem } from './system-BWLddIt2.mjs';
3
3
  export { CauthyTheme, ImportedTheme, PushThemeOptions, StackmythThemeOptions, pushTheme, themeFromStackmyth } from './theme.mjs';
4
4
  export { P as Permitted, a as PolicyPermission, b as PolicyRole, c as PushPolicyOptions, d as can, p as pushPolicy } from './permissions-B-a3eN0h.mjs';
5
5
  import 'jose';
6
+
7
+ interface ConnectOptions {
8
+ /** The system's name, as its organizations are filed under: lowercase, digits, - or _. */
9
+ system: string;
10
+ /** The application's public address: `https://app.example.com`, or `http://localhost:3000` while developing. */
11
+ appUrl: string;
12
+ /** Shown to people on Cauthy's pages. Default: the system's name. */
13
+ name?: string;
14
+ /** Where the application serves the return from a sign-in. Default: `/api/auth/callback`. */
15
+ callbackPath?: string;
16
+ /** An https address of the application that receives Cauthy's events. */
17
+ eventsUrl?: string;
18
+ /** The events to receive. Default: all of them. */
19
+ events?: string[];
20
+ /** Where the application publishes its keys, to prove itself without a secret. */
21
+ jwksUri?: string;
22
+ /** Cauthy's address. Default: `CAUTHY_ISSUER`. */
23
+ issuer?: string;
24
+ /** The workspace's slug. Default: `CAUTHY_TENANT`. */
25
+ tenant?: string;
26
+ /** A personal access token with `systems:connect`. Default: `CAUTHY_TOKEN`. */
27
+ token?: string;
28
+ fetch?: typeof fetch;
29
+ }
30
+ interface Connected {
31
+ system: string;
32
+ clientId: string;
33
+ /** Shown this once: Cauthy keeps only its hash. */
34
+ clientSecret: string;
35
+ redirectUris: string[];
36
+ webhook: {
37
+ id: string;
38
+ url: string;
39
+ events: string[];
40
+ } | null;
41
+ /**
42
+ * Everything the application sets: what Cauthy answered, plus CAUTHY_SECRET,
43
+ * the key of the session cookie, generated here and known to nobody else.
44
+ */
45
+ env: Record<string, string>;
46
+ }
47
+ declare function connectSystem(o: ConnectOptions): Promise<Connected>;
48
+
49
+ export { type ConnectOptions, type Connected, connectSystem };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,49 @@
1
- export { C as Cauthy, a as CauthyEvent, b as CauthyWebhookError, R as Resolved, V as VerifyWebhookOptions, c as createCauthy, v as verifyWebhook } from './cauthy-CCZc9w8r.js';
2
- export { C as CauthyConfigError, a as CauthyOptions, J as JsonValue, P as PublicSession, S as Session, b as SessionOrganization, c as SessionStatus, d as SessionUser } from './types-CYmUVWzY.js';
1
+ export { C as Cauthy, a as CauthyEvent, b as CauthyWebhookError, R as Resolved, V as VerifyWebhookOptions, c as createCauthy, v as verifyWebhook } from './cauthy-C5_lopMQ.js';
2
+ export { C as CauthyApiError, a as CauthyConfigError, b as CauthyOptions, c as CauthySystem, J as JsonValue, N as NewMember, O as Organization, d as OrganizationMember, P as PublicSession, S as Session, e as SessionOrganization, f as SessionStatus, g as SessionUser, h as SystemKey, i as SystemOptions, j as createSystem } from './system-BWLddIt2.js';
3
3
  export { CauthyTheme, ImportedTheme, PushThemeOptions, StackmythThemeOptions, pushTheme, themeFromStackmyth } from './theme.js';
4
4
  export { P as Permitted, a as PolicyPermission, b as PolicyRole, c as PushPolicyOptions, d as can, p as pushPolicy } from './permissions-B-a3eN0h.js';
5
5
  import 'jose';
6
+
7
+ interface ConnectOptions {
8
+ /** The system's name, as its organizations are filed under: lowercase, digits, - or _. */
9
+ system: string;
10
+ /** The application's public address: `https://app.example.com`, or `http://localhost:3000` while developing. */
11
+ appUrl: string;
12
+ /** Shown to people on Cauthy's pages. Default: the system's name. */
13
+ name?: string;
14
+ /** Where the application serves the return from a sign-in. Default: `/api/auth/callback`. */
15
+ callbackPath?: string;
16
+ /** An https address of the application that receives Cauthy's events. */
17
+ eventsUrl?: string;
18
+ /** The events to receive. Default: all of them. */
19
+ events?: string[];
20
+ /** Where the application publishes its keys, to prove itself without a secret. */
21
+ jwksUri?: string;
22
+ /** Cauthy's address. Default: `CAUTHY_ISSUER`. */
23
+ issuer?: string;
24
+ /** The workspace's slug. Default: `CAUTHY_TENANT`. */
25
+ tenant?: string;
26
+ /** A personal access token with `systems:connect`. Default: `CAUTHY_TOKEN`. */
27
+ token?: string;
28
+ fetch?: typeof fetch;
29
+ }
30
+ interface Connected {
31
+ system: string;
32
+ clientId: string;
33
+ /** Shown this once: Cauthy keeps only its hash. */
34
+ clientSecret: string;
35
+ redirectUris: string[];
36
+ webhook: {
37
+ id: string;
38
+ url: string;
39
+ events: string[];
40
+ } | null;
41
+ /**
42
+ * Everything the application sets: what Cauthy answered, plus CAUTHY_SECRET,
43
+ * the key of the session cookie, generated here and known to nobody else.
44
+ */
45
+ env: Record<string, string>;
46
+ }
47
+ declare function connectSystem(o: ConnectOptions): Promise<Connected>;
48
+
49
+ export { type ConnectOptions, type Connected, connectSystem };