@canva/cli 0.0.1-beta.2 → 0.0.1-beta.3

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 (35) hide show
  1. package/package.json +1 -1
  2. package/templates/base/backend/routers/oauth.ts +393 -0
  3. package/templates/base/package.json +1 -1
  4. package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  5. package/templates/base/utils/backend/bearer_middleware/index.ts +1 -0
  6. package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  7. package/templates/base/utils/use_add_element.ts +48 -0
  8. package/templates/base/utils/use_feature_support.ts +28 -0
  9. package/templates/common/README.md +0 -67
  10. package/templates/dam/backend/server.ts +0 -7
  11. package/templates/dam/package.json +6 -6
  12. package/templates/dam/src/app.tsx +2 -135
  13. package/templates/gen_ai/README.md +40 -1
  14. package/templates/gen_ai/backend/routers/oauth.ts +393 -0
  15. package/templates/gen_ai/backend/server.ts +1 -1
  16. package/templates/gen_ai/package.json +5 -5
  17. package/templates/gen_ai/src/api/api.ts +44 -27
  18. package/templates/gen_ai/src/components/footer.tsx +9 -5
  19. package/templates/gen_ai/src/components/image_grid.tsx +8 -6
  20. package/templates/gen_ai/src/components/loading_results.tsx +8 -4
  21. package/templates/gen_ai/src/context/app_context.tsx +8 -2
  22. package/templates/gen_ai/src/services/auth.tsx +5 -10
  23. package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  24. package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +1 -0
  25. package/templates/gen_ai/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  26. package/templates/hello_world/package.json +3 -2
  27. package/templates/hello_world/src/app.tsx +4 -2
  28. package/templates/hello_world/utils/use_add_element.ts +48 -0
  29. package/templates/hello_world/utils/use_feature_support.ts +28 -0
  30. package/templates/dam/backend/database/database.ts +0 -42
  31. package/templates/dam/backend/routers/auth.ts +0 -285
  32. package/templates/gen_ai/backend/routers/auth.ts +0 -285
  33. package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +0 -1
  34. package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +0 -229
  35. package/templates/gen_ai/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +0 -630
@@ -3,6 +3,8 @@ import { useIntl } from "react-intl";
3
3
  import type { ImageType, LoggedInState } from "src/api";
4
4
  import { checkAuthenticationStatus, getRemainingCredits } from "src/api";
5
5
  import { ContextMessages as Messages } from "./context.messages";
6
+ import type { Oauth } from "@canva/user";
7
+ import { auth } from "@canva/user";
6
8
 
7
9
  export interface AppContextType {
8
10
  loggedInState: LoggedInState;
@@ -25,6 +27,7 @@ export interface AppContextType {
25
27
  setPromptInputError: (value: string) => void;
26
28
  generatedImages: ImageType[];
27
29
  setGeneratedImages: (value: ImageType[]) => void;
30
+ oauth: Oauth;
28
31
  }
29
32
 
30
33
  export const AppContext = createContext<AppContextType>({
@@ -48,6 +51,7 @@ export const AppContext = createContext<AppContextType>({
48
51
  setPromptInputError: () => {},
49
52
  generatedImages: [] as ImageType[],
50
53
  setGeneratedImages: () => {},
54
+ oauth: {} as Oauth,
51
55
  });
52
56
 
53
57
  /**
@@ -77,6 +81,7 @@ export const ContextProvider = ({
77
81
  const [generatedImages, setGeneratedImages] = useState<ImageType[]>([]);
78
82
  const [creditsError, setCreditsError] = useState<string>("");
79
83
  const intl = useIntl();
84
+ const oauth = auth.initOauth();
80
85
 
81
86
  // Fetches initial data on component mount
82
87
  useEffect(() => {
@@ -86,7 +91,7 @@ export const ContextProvider = ({
86
91
 
87
92
  // Fetch remaining credits
88
93
  try {
89
- const { credits } = await getRemainingCredits();
94
+ const { credits } = await getRemainingCredits(oauth);
90
95
  setRemainingCredits(credits);
91
96
  } catch (error) {
92
97
  setAppError(
@@ -98,7 +103,7 @@ export const ContextProvider = ({
98
103
 
99
104
  // Fetch login status
100
105
  try {
101
- checkAuthenticationStatus();
106
+ checkAuthenticationStatus(oauth);
102
107
  } catch (error) {
103
108
  setAppError(
104
109
  intl.formatMessage(Messages.appErrorGetLoggedInStatusFailed),
@@ -168,6 +173,7 @@ export const ContextProvider = ({
168
173
  setPromptInputError,
169
174
  generatedImages,
170
175
  setGeneratedImages,
176
+ oauth,
171
177
  };
172
178
 
173
179
  return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
@@ -1,25 +1,20 @@
1
- import { auth } from "@canva/user";
2
1
  import { useAppContext } from "src/context";
3
2
 
4
3
  export const useAuth = () => {
5
- const { setLoggedInState } = useAppContext();
4
+ const { setLoggedInState, oauth } = useAppContext();
6
5
 
7
6
  const requestAuthentication = async () => {
8
7
  try {
9
- const response = await auth.requestAuthentication();
8
+ const response = await oauth.requestAuthorization();
10
9
  switch (response.status) {
11
- case "COMPLETED":
12
- setLoggedInState("authenticated");
13
- break;
14
- case "ABORTED":
10
+ case "aborted":
15
11
  setLoggedInState("not_authenticated");
16
12
  break;
17
- case "DENIED":
18
- setLoggedInState("not_authenticated");
13
+ case "completed":
14
+ setLoggedInState("authenticated");
19
15
  break;
20
16
  default:
21
17
  setLoggedInState("not_authenticated");
22
- break;
23
18
  }
24
19
  } catch (e) {
25
20
  // eslint-disable-next-line no-console
@@ -0,0 +1,101 @@
1
+ /* eslint-disable no-console */
2
+ import * as debug from "debug";
3
+ import type { Request, Response, NextFunction } from "express";
4
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
5
+ import Express from "express-serve-static-core";
6
+
7
+ /**
8
+ * Prefix your start command with `DEBUG=express:middleware:bearer` to enable debug logging
9
+ * for this middleware
10
+ */
11
+ const debugLogger = debug("express:middleware:bearer");
12
+
13
+ /**
14
+ * Augment the Express request context to include the appId/userId/brandId fields decoded
15
+ * from the JWT.
16
+ */
17
+ declare module "express-serve-static-core" {
18
+ export interface Request {
19
+ user_id: string;
20
+ }
21
+ }
22
+
23
+ const sendUnauthorizedResponse = (res: Response, message?: string) =>
24
+ res.status(401).json({ error: "unauthorized", message });
25
+
26
+ /**
27
+ * An Express.js middleware verifying a Bearer token.
28
+ * This middleware extracts the token from the `Authorization` header.
29
+ *
30
+ * @param getTokenFromRequest - A function that extracts a token from the request. If a token isn't found, throw a `JWTAuthorizationError`.
31
+ * @returns An Express.js middleware for verifying and decoding JWTs.
32
+ */
33
+ export function createBearerMiddleware(
34
+ tokenToUser: (access_token: string) => Promise<string | undefined>,
35
+ getTokenFromRequest: GetTokenFromRequest = getTokenFromHttpHeader,
36
+ ): (req: Request, res: Response, next: NextFunction) => void {
37
+ return async (req, res, next) => {
38
+ try {
39
+ debugLogger(`processing token for '${req.url}'`);
40
+
41
+ const token = await getTokenFromRequest(req);
42
+ const user = await tokenToUser(token);
43
+
44
+ if (!user) {
45
+ throw new AuthorizationError("Token is invalid");
46
+ }
47
+
48
+ req.user_id = user;
49
+
50
+ next();
51
+ } catch (e) {
52
+ if (e instanceof AuthorizationError) {
53
+ return sendUnauthorizedResponse(res, e.message);
54
+ }
55
+
56
+ next(e);
57
+ }
58
+ };
59
+ }
60
+
61
+ export type GetTokenFromRequest = (req: Request) => Promise<string> | string;
62
+
63
+ export const getTokenFromHttpHeader: GetTokenFromRequest = (
64
+ req: Request,
65
+ ): string => {
66
+ // The names of a HTTP header bearing the JWT, and a scheme
67
+ const headerName = "Authorization";
68
+ const schemeName = "Bearer";
69
+
70
+ const header = req.header(headerName);
71
+ if (!header) {
72
+ throw new AuthorizationError(`Missing the "${headerName}" header`);
73
+ }
74
+
75
+ if (!header.match(new RegExp(`^${schemeName}\\s+[^\\s]+$`, "i"))) {
76
+ console.trace(
77
+ `jwtMiddleware: failed to match token in "${headerName}" header`,
78
+ );
79
+ throw new AuthorizationError(
80
+ `Missing a "${schemeName}" token in the "${headerName}" header`,
81
+ );
82
+ }
83
+
84
+ const token = header.replace(new RegExp(`^${schemeName}\\s+`, "i"), "");
85
+
86
+ return token;
87
+ };
88
+
89
+ /**
90
+ * A class representing JWT validation errors in the JWT middleware.
91
+ * The error message provided to the constructor will be forwarded to the
92
+ * API consumer trying to access a JWT-protected endpoint.
93
+ * @private
94
+ */
95
+ export class AuthorizationError extends Error {
96
+ constructor(message: string) {
97
+ super(message);
98
+
99
+ Object.setPrototypeOf(this, AuthorizationError.prototype);
100
+ }
101
+ }
@@ -0,0 +1 @@
1
+ export { createBearerMiddleware } from "./bearer_middleware";
@@ -0,0 +1,192 @@
1
+ /* eslint-disable @typescript-eslint/no-require-imports */
2
+ import type { NextFunction, Request, Response } from "express";
3
+ import type {
4
+ createBearerMiddleware,
5
+ GetTokenFromRequest,
6
+ } from "../bearer_middleware";
7
+
8
+ type Middleware = (req: Request, res: Response, next: NextFunction) => void;
9
+
10
+ describe("createBearerMiddleware", () => {
11
+ let fakeGetTokenFromRequest: jest.MockedFn<GetTokenFromRequest>;
12
+ let verify: jest.MockedFn<(token: string) => Promise<string | undefined>>;
13
+
14
+ let req: Request;
15
+ let res: Response;
16
+ let next: jest.MockedFn<() => void>;
17
+
18
+ let AuthorizationError: typeof Error;
19
+ let createBearerMiddlewareFn: typeof createBearerMiddleware;
20
+ let bearerMiddleware: Middleware;
21
+
22
+ beforeEach(() => {
23
+ jest.resetAllMocks();
24
+ jest.resetModules();
25
+
26
+ fakeGetTokenFromRequest = jest.fn();
27
+ verify = jest.fn();
28
+
29
+ const middlewareModule = require("../bearer_middleware");
30
+ createBearerMiddlewareFn = middlewareModule.createBearerMiddleware;
31
+ AuthorizationError = middlewareModule.AuthorizationError;
32
+ });
33
+
34
+ describe("When called", () => {
35
+ beforeEach(() => {
36
+ req = {
37
+ header: (_name: string) => undefined,
38
+ } as Request;
39
+
40
+ res = {
41
+ status: jest.fn().mockReturnThis(),
42
+ json: jest.fn().mockReturnThis(),
43
+ send: jest.fn().mockReturnThis(),
44
+ } as unknown as Response;
45
+
46
+ next = jest.fn();
47
+
48
+ bearerMiddleware = createBearerMiddlewareFn(
49
+ verify,
50
+ fakeGetTokenFromRequest,
51
+ );
52
+ });
53
+
54
+ describe("When `getTokenFromRequest` throws an exception ('Fake error')", () => {
55
+ beforeEach(() => {
56
+ fakeGetTokenFromRequest.mockRejectedValue(
57
+ new AuthorizationError("Fake error"),
58
+ );
59
+ });
60
+
61
+ it(`Does not call next() and returns HTTP 401 with error = "unauthorized" and message = "Fake error"`, async () => {
62
+ expect.assertions(8);
63
+
64
+ expect(fakeGetTokenFromRequest).not.toHaveBeenCalled();
65
+ await bearerMiddleware(req, res, next);
66
+
67
+ expect(fakeGetTokenFromRequest).toHaveBeenCalledTimes(1);
68
+ expect(fakeGetTokenFromRequest).toHaveBeenLastCalledWith(req);
69
+
70
+ expect(res.status).toHaveBeenCalledTimes(1);
71
+ expect(res.status).toHaveBeenLastCalledWith(401);
72
+
73
+ expect(res.json).toHaveBeenCalledTimes(1);
74
+ expect(res.json).toHaveBeenLastCalledWith({
75
+ error: "unauthorized",
76
+ message: "Fake error",
77
+ });
78
+
79
+ expect(next).not.toHaveBeenCalled();
80
+ });
81
+ });
82
+
83
+ describe("When the middleware cannot verify the token", () => {
84
+ beforeEach(() => {
85
+ fakeGetTokenFromRequest.mockReturnValue("TOKEN");
86
+
87
+ verify.mockImplementation(() => Promise.resolve(undefined));
88
+ });
89
+
90
+ it(`Does not call next() and returns HTTP 401 with error = "unauthorized" and message = "Token is invalid"`, async () => {
91
+ expect.assertions(5);
92
+
93
+ await bearerMiddleware(req, res, next);
94
+
95
+ expect(res.status).toHaveBeenCalledTimes(1);
96
+ expect(res.status).toHaveBeenLastCalledWith(401);
97
+
98
+ expect(res.json).toHaveBeenCalledTimes(1);
99
+ expect(res.json).toHaveBeenLastCalledWith({
100
+ error: "unauthorized",
101
+ message: "Token is invalid",
102
+ });
103
+
104
+ expect(next).not.toHaveBeenCalled();
105
+ });
106
+ });
107
+ });
108
+ });
109
+
110
+ describe("getTokenFromHttpHeader", () => {
111
+ let getHeader: jest.MockedFn<(name: string) => string | undefined>;
112
+ let req: Request;
113
+ let getTokenFromHttpHeader: (req: Request) => string;
114
+ let AuthorizationError: typeof Error;
115
+
116
+ beforeEach(() => {
117
+ getHeader = jest.fn();
118
+ req = {
119
+ header: (name: string) => getHeader(name),
120
+ } as Request;
121
+
122
+ const bearerMiddlewareModule = require("../bearer_middleware");
123
+ getTokenFromHttpHeader = bearerMiddlewareModule.getTokenFromHttpHeader;
124
+ AuthorizationError = bearerMiddlewareModule.AuthorizationError;
125
+ });
126
+
127
+ describe("When the 'Authorization' header is missing", () => {
128
+ beforeEach(() => {
129
+ getHeader.mockReturnValue(undefined);
130
+ });
131
+
132
+ it(`Throws a AuthorizationError with message = 'Missing the "Authorization" header'`, async () => {
133
+ expect.assertions(3);
134
+
135
+ expect(() => getTokenFromHttpHeader(req)).toThrow(
136
+ new AuthorizationError('Missing the "Authorization" header'),
137
+ );
138
+ expect(getHeader).toHaveBeenCalledTimes(1);
139
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
140
+ });
141
+ });
142
+
143
+ describe("When the 'Authorization' header doesn't have a Bearer scheme", () => {
144
+ beforeEach(() => {
145
+ getHeader.mockReturnValue("Beerer FAKE_TOKEN");
146
+ });
147
+
148
+ it(`Throws a AuthorizationError with message = 'Missing a "Bearer" token in the "Authorization" header''`, async () => {
149
+ expect.assertions(3);
150
+
151
+ expect(() => getTokenFromHttpHeader(req)).toThrow(
152
+ new AuthorizationError(
153
+ 'Missing a "Bearer" token in the "Authorization" header',
154
+ ),
155
+ );
156
+ expect(getHeader).toHaveBeenCalledTimes(1);
157
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
158
+ });
159
+ });
160
+
161
+ describe("When the 'Authorization' Bearer scheme header doesn't have a token", () => {
162
+ beforeEach(() => {
163
+ getHeader.mockReturnValue("Bearer ");
164
+ });
165
+
166
+ it(`Throws a AuthorizationError with message = 'Missing a "Bearer" token in the "Authorization" header'`, async () => {
167
+ expect.assertions(3);
168
+
169
+ expect(() => getTokenFromHttpHeader(req)).toThrow(
170
+ new AuthorizationError(
171
+ 'Missing a "Bearer" token in the "Authorization" header',
172
+ ),
173
+ );
174
+ expect(getHeader).toHaveBeenCalledTimes(1);
175
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
176
+ });
177
+ });
178
+
179
+ describe("When the 'Authorization' Bearer scheme header has a token", () => {
180
+ beforeEach(() => {
181
+ getHeader.mockReturnValue("Bearer TOKEN");
182
+ });
183
+
184
+ it(`Returns the token`, async () => {
185
+ expect.assertions(3);
186
+
187
+ expect(getTokenFromHttpHeader(req)).toEqual("TOKEN");
188
+ expect(getHeader).toHaveBeenCalledTimes(1);
189
+ expect(getHeader).toHaveBeenLastCalledWith("Authorization");
190
+ });
191
+ });
192
+ });
@@ -16,9 +16,10 @@
16
16
  "test:watch": "jest --watchAll"
17
17
  },
18
18
  "dependencies": {
19
- "@canva/app-ui-kit": "^3.8.0",
19
+ "@canva/app-ui-kit": "^4.0.0",
20
20
  "@canva/app-i18n-kit": "^0.0.1-beta.5",
21
- "@canva/design": "^2.0.0",
21
+ "@canva/design": "^2.1.0",
22
+ "@canva/platform": "^2.0.0",
22
23
  "@canva/error": "^2.0.0",
23
24
  "react": "18.3.1",
24
25
  "react-dom": "18.3.1",
@@ -1,11 +1,13 @@
1
1
  import { Button, Rows, Text } from "@canva/app-ui-kit";
2
- import { addElementAtPoint } from "@canva/design";
3
2
  import { FormattedMessage, useIntl } from "react-intl";
4
3
  import * as styles from "styles/components.css";
4
+ import { useAddElement } from "utils/use_add_element";
5
5
 
6
6
  export const App = () => {
7
+ const addElement = useAddElement();
8
+
7
9
  const onClick = () => {
8
- addElementAtPoint({
10
+ addElement({
9
11
  type: "text",
10
12
  children: ["Hello world!"],
11
13
  });
@@ -0,0 +1,48 @@
1
+ import type {
2
+ EmbedElement,
3
+ ImageElement,
4
+ RichtextElement,
5
+ TableElement,
6
+ TextElement,
7
+ VideoElement,
8
+ } from "@canva/design";
9
+ import { addElementAtCursor, addElementAtPoint } from "@canva/design";
10
+ import { useFeatureSupport } from "./use_feature_support";
11
+ import { features } from "@canva/platform";
12
+ import { useEffect, useState } from "react";
13
+
14
+ type AddElementParams =
15
+ | ImageElement
16
+ | VideoElement
17
+ | EmbedElement
18
+ | TextElement
19
+ | RichtextElement
20
+ | TableElement;
21
+
22
+ export const useAddElement = () => {
23
+ const isSupported = useFeatureSupport();
24
+
25
+ // Store a wrapped addElement function that checks feature support
26
+ const [addElement, setAddElement] = useState(() => {
27
+ return (element: AddElementParams) => {
28
+ if (features.isSupported(addElementAtPoint)) {
29
+ return addElementAtPoint(element);
30
+ } else if (features.isSupported(addElementAtCursor)) {
31
+ return addElementAtCursor(element);
32
+ }
33
+ };
34
+ });
35
+
36
+ useEffect(() => {
37
+ const addElement = (element: AddElementParams) => {
38
+ if (isSupported(addElementAtPoint)) {
39
+ return addElementAtPoint(element);
40
+ } else if (isSupported(addElementAtCursor)) {
41
+ return addElementAtCursor(element);
42
+ }
43
+ };
44
+ setAddElement(() => addElement);
45
+ }, [isSupported]);
46
+
47
+ return addElement;
48
+ };
@@ -0,0 +1,28 @@
1
+ import { features } from "@canva/platform";
2
+ import type { Feature } from "@canva/platform";
3
+ import { useState, useEffect } from "react";
4
+
5
+ /**
6
+ * This hook allows re-rendering of a React component whenever
7
+ * the state of feature support changes in Canva.
8
+ *
9
+ * @returns isSupported - callback to inspect a Canva SDK method.
10
+ **/
11
+ export function useFeatureSupport() {
12
+ // Store a wrapped function that checks feature support
13
+ const [isSupported, setIsSupported] = useState(() => {
14
+ return (...args: Feature[]) => features.isSupported(...args);
15
+ });
16
+
17
+ useEffect(() => {
18
+ // create new function ref when feature support changes to trigger
19
+ // re-render
20
+ return features.registerOnSupportChange(() => {
21
+ setIsSupported(() => {
22
+ return (...args: Feature[]) => features.isSupported(...args);
23
+ });
24
+ });
25
+ }, []);
26
+
27
+ return isSupported;
28
+ }
@@ -1,42 +0,0 @@
1
- import * as fs from "fs/promises";
2
- import * as path from "path";
3
-
4
- /**
5
- * This file creates a "database" out of a JSON file. It's only for
6
- * demonstration purposes. A real app should use a real database.
7
- */
8
- const DATABASE_FILE_PATH = path.join(__dirname, "db.json");
9
-
10
- interface Database<T> {
11
- read(): Promise<T>;
12
- write(data: T): Promise<void>;
13
- }
14
-
15
- export class JSONFileDatabase<T> implements Database<T> {
16
- constructor(private readonly seedData: T) {}
17
-
18
- // Creates a database file if one doesn't already exist
19
- private async init(): Promise<void> {
20
- try {
21
- // Do nothing, since the database is initialized
22
- await fs.stat(DATABASE_FILE_PATH);
23
- } catch {
24
- const file = JSON.stringify(this.seedData);
25
- await fs.writeFile(DATABASE_FILE_PATH, file);
26
- }
27
- }
28
-
29
- // Loads and parses the database file
30
- async read(): Promise<T> {
31
- await this.init();
32
- const file = await fs.readFile(DATABASE_FILE_PATH, "utf8");
33
- return JSON.parse(file);
34
- }
35
-
36
- // Overwrites the database file with provided data
37
- async write(data: T): Promise<void> {
38
- await this.init();
39
- const file = JSON.stringify(data);
40
- await fs.writeFile(DATABASE_FILE_PATH, file);
41
- }
42
- }