@canva/cli 0.0.1-beta.1 → 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 (43) hide show
  1. package/cli.js +134 -134
  2. package/package.json +1 -1
  3. package/templates/base/backend/routers/oauth.ts +393 -0
  4. package/templates/base/eslint.config.mjs +5 -275
  5. package/templates/base/package.json +1 -1
  6. package/templates/base/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  7. package/templates/base/utils/backend/bearer_middleware/index.ts +1 -0
  8. package/templates/base/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  9. package/templates/base/utils/use_add_element.ts +48 -0
  10. package/templates/base/utils/use_feature_support.ts +28 -0
  11. package/templates/common/README.md +0 -67
  12. package/templates/common/conf/eslint-general.mjs +277 -0
  13. package/templates/common/conf/eslint-i18n.mjs +23 -0
  14. package/templates/dam/backend/server.ts +0 -7
  15. package/templates/dam/eslint.config.mjs +6 -275
  16. package/templates/dam/package.json +8 -7
  17. package/templates/dam/src/app.tsx +2 -135
  18. package/templates/gen_ai/README.md +40 -1
  19. package/templates/gen_ai/backend/routers/oauth.ts +393 -0
  20. package/templates/gen_ai/backend/server.ts +1 -1
  21. package/templates/gen_ai/eslint.config.mjs +5 -275
  22. package/templates/gen_ai/package.json +7 -6
  23. package/templates/gen_ai/src/api/api.ts +44 -27
  24. package/templates/gen_ai/src/components/footer.tsx +9 -5
  25. package/templates/gen_ai/src/components/image_grid.tsx +9 -7
  26. package/templates/gen_ai/src/components/loading_results.tsx +8 -4
  27. package/templates/gen_ai/src/components/prompt_input.tsx +2 -0
  28. package/templates/gen_ai/src/context/app_context.tsx +8 -2
  29. package/templates/gen_ai/src/services/auth.tsx +5 -10
  30. package/templates/gen_ai/utils/backend/bearer_middleware/bearer_middleware.ts +101 -0
  31. package/templates/gen_ai/utils/backend/bearer_middleware/index.ts +1 -0
  32. package/templates/gen_ai/utils/backend/bearer_middleware/tests/bearer_middleware.tests.ts +192 -0
  33. package/templates/hello_world/eslint.config.mjs +5 -275
  34. package/templates/hello_world/package.json +7 -5
  35. package/templates/hello_world/src/app.tsx +5 -3
  36. package/templates/hello_world/utils/use_add_element.ts +48 -0
  37. package/templates/hello_world/utils/use_feature_support.ts +28 -0
  38. package/templates/dam/backend/database/database.ts +0 -42
  39. package/templates/dam/backend/routers/auth.ts +0 -285
  40. package/templates/gen_ai/backend/routers/auth.ts +0 -285
  41. package/templates/gen_ai/utils/backend/jwt_middleware/index.ts +0 -1
  42. package/templates/gen_ai/utils/backend/jwt_middleware/jwt_middleware.ts +0 -229
  43. package/templates/gen_ai/utils/backend/jwt_middleware/tests/jwt_middleware.tests.ts +0 -630
@@ -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
+ });
@@ -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
+ }
@@ -181,70 +181,3 @@ To use ngrok, you'll need to do the following:
181
181
  ```
182
182
 
183
183
  This environment variable is available for the current terminal session, so the command must be re-run for each new session. Alternatively, you can add the variable to your terminal's default parameters.
184
-
185
- ## Run the development server with ngrok and add authentication to the app
186
-
187
- These steps demonstrate how to start the local development server with ngrok.
188
-
189
- From your app's root directory
190
-
191
- 1. Stop any running scripts, and run the following command to launch the backend and frontend development servers. The `--ngrok` parameter exposes the backend server via a publicly accessible URL.
192
-
193
- ```bash
194
- npm start --ngrok
195
- ```
196
-
197
- 2. After ngrok is running, copy your ngrok url
198
- (e.g. `https://0000-0000.ngrok-free.app`) to the clipboard.
199
-
200
- 1. Go to your app in the [Developer Portal](https://www.canva.com/developers/apps).
201
- 2. Navigate to the "Add authentication" section of your app.
202
- 3. Check "This app requires authentication"
203
- 4. In the "Redirect URL" text box, enter your ngrok url followed by `/redirect-url` e.g.
204
- `https://0000-0000.ngrok-free.app/redirect-url`
205
- 5. In the "Authentication base URL" text box, enter your ngrok url followed by `/` e.g.
206
- `https://0000-0000.ngrok-free.app/`
207
- Note: Your ngrok URL changes each time you restart ngrok. Keep these fields up to
208
- date to ensure your example authentication step will run.
209
-
210
- 3. Make sure the app is authenticating users by making the following changes:
211
-
212
- 1. Replace
213
-
214
- `router.post("/resources/find", async (req, res) => {`
215
-
216
- with
217
-
218
- `router.post("/api/resources/find", async (req, res) => {`
219
-
220
- in [./backend/routers/auth.ts](./backend/routers/auth.ts). Adding `/api/` to the route ensures
221
- the JWT middleware authenticates requests.
222
-
223
- 2. Replace
224
-
225
- ``const url = new URL(`${BACKEND_HOST}/resources/find`);``
226
-
227
- with
228
-
229
- ``const url = new URL(`${BACKEND_HOST}/api/resources/find`);``
230
-
231
- in [./adapter.ts](./adapter.ts)
232
-
233
- 3. Comment out these lines in [./app.tsx](./app.tsx)
234
-
235
- ```typescript
236
- // Comment this next line out for production apps
237
- setAuthState("authenticated");
238
- ```
239
-
240
- 4. Navigate to your app at `https://www.canva.com/developers/apps`, and click **Preview** to preview the app.
241
- 1. A new screen will appear asking if you want to authenticate.
242
- Press **Connect** to start the authentication flow.
243
- 2. A ngrok screen may appear. If it does, select **Visit Site**
244
- 3. An authentication popup will appear. For the username, enter `username`, and
245
- for the password enter `password`.
246
- 4. If successful, you will be redirected back to your app.
247
- 5. You can now modify the `/redirect-url` function in `server.ts` to authenticate with your third-party
248
- asset manager, and `/api/resources/find` to pull assets from your third-party asset manager.
249
-
250
- See `https://www.canva.dev/docs/apps/authenticating-users/` for more details.