@insaeng/auth 0.3.0 → 0.5.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 (45) hide show
  1. package/dist/app/cli/types-command.d.ts +11 -0
  2. package/dist/app/cli/types-command.d.ts.map +1 -0
  3. package/dist/app/cli/types-command.js +45 -0
  4. package/dist/app/http/auth-error-handler.d.ts +3 -0
  5. package/dist/app/http/auth-error-handler.d.ts.map +1 -0
  6. package/dist/app/http/auth-error-handler.js +29 -0
  7. package/dist/app/http/auth-middleware.d.ts +16 -0
  8. package/dist/app/http/auth-middleware.d.ts.map +1 -0
  9. package/dist/app/http/auth-middleware.js +73 -0
  10. package/dist/data/auth/auth-repo.d.ts +8 -1
  11. package/dist/data/auth/auth-repo.d.ts.map +1 -1
  12. package/dist/data/auth/auth-repo.js +23 -1
  13. package/dist/data/sources/cedar/cedar-schema-source.d.ts +3 -0
  14. package/dist/data/sources/cedar/cedar-schema-source.d.ts.map +1 -0
  15. package/dist/data/sources/cedar/cedar-schema-source.js +67 -0
  16. package/dist/data/sources/cedar/cedar-source.d.ts +17 -0
  17. package/dist/data/sources/cedar/cedar-source.d.ts.map +1 -0
  18. package/dist/data/sources/cedar/cedar-source.js +75 -0
  19. package/dist/data/sources/oauth/oauth-source.d.ts +18 -0
  20. package/dist/data/sources/oauth/oauth-source.d.ts.map +1 -0
  21. package/dist/data/sources/oauth/oauth-source.js +104 -0
  22. package/dist/dependencies.d.ts +10 -5
  23. package/dist/dependencies.d.ts.map +1 -1
  24. package/dist/dependencies.js +7 -4
  25. package/dist/domain/authz-types/authz-types-entity.d.ts +37 -0
  26. package/dist/domain/authz-types/authz-types-entity.d.ts.map +1 -0
  27. package/dist/domain/authz-types/authz-types-entity.js +1 -0
  28. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.d.ts +4 -0
  29. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.d.ts.map +1 -0
  30. package/dist/domain/authz-types/use-cases/generate-authz-types-use-case.js +64 -0
  31. package/dist/main.d.ts +3 -0
  32. package/dist/main.d.ts.map +1 -0
  33. package/dist/main.js +11 -0
  34. package/package.json +29 -2
  35. package/src/app/cli/types-command.ts +62 -0
  36. package/src/app/http/auth-error-handler.ts +39 -0
  37. package/src/app/http/auth-middleware.ts +104 -0
  38. package/src/data/auth/auth-repo.ts +43 -1
  39. package/src/data/sources/cedar/cedar-schema-source.ts +92 -0
  40. package/src/data/sources/cedar/cedar-source.ts +116 -0
  41. package/src/data/sources/oauth/oauth-source.ts +140 -0
  42. package/src/dependencies.ts +16 -7
  43. package/src/domain/authz-types/authz-types-entity.ts +29 -0
  44. package/src/domain/authz-types/use-cases/generate-authz-types-use-case.ts +85 -0
  45. package/src/main.ts +12 -0
@@ -0,0 +1,140 @@
1
+ import { importJWK, SignJWT, type JWK } from "jose";
2
+
3
+ export interface OauthSourceOptions {
4
+ tokenEndpoint: string | URL;
5
+ clientId: string;
6
+ privateKey: JWK;
7
+ resource: string;
8
+ fetch?: typeof fetch;
9
+ }
10
+
11
+ export interface OauthSource {
12
+ getToken(): Promise<string>;
13
+ }
14
+
15
+ export class TokenRequestError extends Error {
16
+ readonly status: number;
17
+ readonly error: string | undefined;
18
+
19
+ constructor(status: number, error: string | undefined) {
20
+ super(
21
+ `Token request failed with status ${String(status)}` +
22
+ (error === undefined ? "" : `: ${error}`),
23
+ );
24
+ this.name = "TokenRequestError";
25
+ this.status = status;
26
+ this.error = error;
27
+ }
28
+ }
29
+
30
+ const ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
31
+ const ASSERTION_LIFETIME_SECONDS = 60;
32
+ const REFRESH_MARGIN_MS = 30_000;
33
+
34
+ interface CachedToken {
35
+ accessToken: string;
36
+ expiresAt: number;
37
+ }
38
+
39
+ function isRecord(value: unknown): value is Record<string, unknown> {
40
+ return typeof value === "object" && value !== null;
41
+ }
42
+
43
+ async function readJson(response: Response): Promise<unknown> {
44
+ try {
45
+ return await response.json();
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ function toCachedToken(body: unknown): CachedToken {
52
+ if (!isRecord(body)) {
53
+ throw new TypeError("Token response must be a JSON object");
54
+ }
55
+ const { access_token, expires_in } = body;
56
+ if (typeof access_token !== "string" || access_token === "") {
57
+ throw new TypeError('Token response "access_token" must be a string');
58
+ }
59
+ if (
60
+ typeof expires_in !== "number" ||
61
+ !Number.isFinite(expires_in) ||
62
+ expires_in <= 0
63
+ ) {
64
+ throw new TypeError(
65
+ 'Token response "expires_in" must be a positive number',
66
+ );
67
+ }
68
+ return {
69
+ accessToken: access_token,
70
+ expiresAt: Date.now() + expires_in * 1000,
71
+ };
72
+ }
73
+
74
+ export function createOauthSource(options: OauthSourceOptions): OauthSource {
75
+ const { clientId, privateKey, resource } = options;
76
+ const tokenEndpoint = String(options.tokenEndpoint);
77
+ const fetchToken = options.fetch ?? globalThis.fetch;
78
+ const kid = privateKey.kid ?? "";
79
+ if (kid === "") {
80
+ throw new TypeError('Client private key must have a "kid"');
81
+ }
82
+
83
+ let key: ReturnType<typeof importJWK> | undefined;
84
+ let cached: CachedToken | undefined;
85
+ let pending: Promise<string> | undefined;
86
+
87
+ async function signAssertion(): Promise<string> {
88
+ key ??= importJWK(privateKey, "EdDSA");
89
+ return new SignJWT()
90
+ .setProtectedHeader({ alg: "EdDSA", kid })
91
+ .setIssuer(clientId)
92
+ .setSubject(clientId)
93
+ .setAudience(tokenEndpoint)
94
+ .setJti(crypto.randomUUID())
95
+ .setIssuedAt()
96
+ .setExpirationTime(`${String(ASSERTION_LIFETIME_SECONDS)}s`)
97
+ .sign(await key);
98
+ }
99
+
100
+ async function requestToken(): Promise<string> {
101
+ const response = await fetchToken(tokenEndpoint, {
102
+ method: "POST",
103
+ headers: {
104
+ accept: "application/json",
105
+ "content-type": "application/x-www-form-urlencoded",
106
+ },
107
+ body: new URLSearchParams({
108
+ grant_type: "client_credentials",
109
+ client_assertion_type: ASSERTION_TYPE,
110
+ client_assertion: await signAssertion(),
111
+ resource,
112
+ }),
113
+ });
114
+ const body = await readJson(response);
115
+ if (!response.ok) {
116
+ const error =
117
+ isRecord(body) && typeof body.error === "string"
118
+ ? body.error
119
+ : undefined;
120
+ throw new TokenRequestError(response.status, error);
121
+ }
122
+ cached = toCachedToken(body);
123
+ return cached.accessToken;
124
+ }
125
+
126
+ return {
127
+ getToken() {
128
+ if (
129
+ cached !== undefined &&
130
+ cached.expiresAt - Date.now() > REFRESH_MARGIN_MS
131
+ ) {
132
+ return Promise.resolve(cached.accessToken);
133
+ }
134
+ pending ??= requestToken().finally(() => {
135
+ pending = undefined;
136
+ });
137
+ return pending;
138
+ },
139
+ };
140
+ }
@@ -1,28 +1,37 @@
1
- import { createAuthRepo } from "./data/auth/auth-repo.js";
1
+ import { createAuthRepo, type AuthResource } from "./data/auth/auth-repo.js";
2
+ import { createCedarSource } from "./data/sources/cedar/cedar-source.js";
2
3
  import {
3
4
  createJwksSource,
4
5
  type JwksSourceOptions,
5
6
  } from "./data/sources/jwks/jwks-source.js";
6
7
  import type { AuthRepo } from "./domain/auth/auth-repo.js";
8
+ import {
9
+ assertCanUseCase,
10
+ type AssertCan,
11
+ } from "./domain/auth/use-cases/assert-can-use-case.js";
7
12
  import {
8
13
  verifyAccessTokenUseCase,
9
14
  type VerifyAccessToken,
10
15
  } from "./domain/auth/use-cases/verify-access-token-use-case.js";
11
16
 
12
- export type { JwksSourceOptions };
13
- export { assertCanUseCase } from "./domain/auth/use-cases/assert-can-use-case.js";
14
- export { verifyAccessTokenUseCase };
17
+ export type { AuthResource, JwksSourceOptions };
18
+ export { assertCanUseCase, verifyAccessTokenUseCase };
19
+
20
+ export type AuthOptions = JwksSourceOptions & { authzDir: string };
15
21
 
16
22
  export interface Auth {
17
- authRepo: Pick<AuthRepo, "findPrincipal">;
23
+ authRepo: AuthRepo<string, AuthResource>;
18
24
  verifyAccessToken: VerifyAccessToken;
25
+ assertCan: AssertCan<string, AuthResource>;
19
26
  }
20
27
 
21
- export function createAuth(options: JwksSourceOptions): Auth {
28
+ export function createAuth({ authzDir, ...options }: AuthOptions): Auth {
22
29
  const jwks = createJwksSource(options);
23
- const authRepo = createAuthRepo({ jwks });
30
+ const cedar = createCedarSource({ dir: authzDir });
31
+ const authRepo = createAuthRepo({ jwks, cedar });
24
32
  return {
25
33
  authRepo,
26
34
  verifyAccessToken: verifyAccessTokenUseCase({ authRepo }),
35
+ assertCan: assertCanUseCase({ authRepo }),
27
36
  };
28
37
  }
@@ -0,0 +1,29 @@
1
+ export type AuthzType =
2
+ | { kind: "string" }
3
+ | { kind: "long" }
4
+ | { kind: "boolean" }
5
+ | { kind: "set"; element: AuthzType }
6
+ | { kind: "record"; attributes: AuthzAttribute[] }
7
+ | { kind: "entity"; name: string }
8
+ | { kind: "extension"; name: string };
9
+
10
+ export interface AuthzAttribute {
11
+ name: string;
12
+ type: AuthzType;
13
+ required: boolean;
14
+ }
15
+
16
+ export interface AuthzEntityType {
17
+ name: string;
18
+ attributes: AuthzAttribute[];
19
+ }
20
+
21
+ export interface AuthzNamespace {
22
+ name: string;
23
+ entityTypes: AuthzEntityType[];
24
+ actions: string[];
25
+ }
26
+
27
+ export interface AuthzSchema {
28
+ namespaces: AuthzNamespace[];
29
+ }
@@ -0,0 +1,85 @@
1
+ import type {
2
+ AuthzAttribute,
3
+ AuthzSchema,
4
+ AuthzType,
5
+ } from "../authz-types-entity.js";
6
+
7
+ export type GenerateAuthzTypes = (schema: AuthzSchema) => string;
8
+
9
+ const maxLineLength = 80;
10
+
11
+ function byName(a: { name: string }, b: { name: string }): number {
12
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
13
+ }
14
+
15
+ function propertyName(name: string): string {
16
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
17
+ }
18
+
19
+ function renderAttributes(attributes: AuthzAttribute[], indent: string) {
20
+ return [...attributes]
21
+ .sort(byName)
22
+ .map(
23
+ ({ name, type, required }) =>
24
+ `${indent} ${propertyName(name)}${required ? "" : "?"}: ${renderType(type, `${indent} `)};\n`,
25
+ )
26
+ .join("");
27
+ }
28
+
29
+ function renderType(type: AuthzType, indent: string): string {
30
+ switch (type.kind) {
31
+ case "string":
32
+ case "extension":
33
+ return "string";
34
+ case "long":
35
+ return "number";
36
+ case "boolean":
37
+ return "boolean";
38
+ case "set":
39
+ return `${renderType(type.element, indent)}[]`;
40
+ case "entity":
41
+ return `EntityUid<${JSON.stringify(type.name)}>`;
42
+ case "record":
43
+ return type.attributes.length === 0
44
+ ? "Record<string, never>"
45
+ : `{\n${renderAttributes(type.attributes, indent)}${indent}}`;
46
+ }
47
+ }
48
+
49
+ function renderAction(actions: string[]): string {
50
+ if (actions.length === 0) {
51
+ return "export type Action = never;\n";
52
+ }
53
+ const union = `${actions.map((action) => JSON.stringify(action)).join(" | ")};`;
54
+ if (`export type Action = ${union}`.length <= maxLineLength) {
55
+ return `export type Action = ${union}\n`;
56
+ }
57
+ if (` ${union}`.length <= maxLineLength) {
58
+ return `export type Action =\n ${union}\n`;
59
+ }
60
+ return `export type Action =\n${actions.map((action) => ` | ${JSON.stringify(action)}`).join("\n")};\n`;
61
+ }
62
+
63
+ export function generateAuthzTypesUseCase(schema: AuthzSchema): string {
64
+ const actions = [
65
+ ...new Set(schema.namespaces.flatMap(({ actions }) => actions)),
66
+ ].sort();
67
+ const entities = schema.namespaces
68
+ .flatMap(({ name: namespace, entityTypes }) =>
69
+ entityTypes.map(({ name, attributes }) => ({
70
+ name: [...namespace.split("::"), name].join(""),
71
+ attributes,
72
+ })),
73
+ )
74
+ .sort(byName)
75
+ .map(({ name, attributes }) =>
76
+ attributes.length === 0
77
+ ? `export type ${name} = Record<string, never>;\n`
78
+ : `export interface ${name} {\n${renderAttributes(attributes, "")}}\n`,
79
+ );
80
+ return [
81
+ renderAction(actions),
82
+ "export interface EntityUid<Type extends string> {\n type: Type;\n id: string;\n}\n",
83
+ ...entities,
84
+ ].join("\n");
85
+ }
package/src/main.ts ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import { typesCommand } from "./app/cli/types-command.js";
3
+ import { readCedarSchemaSource } from "./data/sources/cedar/cedar-schema-source.js";
4
+ import { generateAuthzTypesUseCase } from "./domain/authz-types/use-cases/generate-authz-types-use-case.js";
5
+
6
+ process.exitCode = typesCommand(process.argv.slice(2), {
7
+ readAuthzSchema: readCedarSchemaSource,
8
+ generateAuthzTypes: generateAuthzTypesUseCase,
9
+ cwd: process.cwd(),
10
+ log: console.log,
11
+ error: console.error,
12
+ });