Skip to content

Commit 823e73b

Browse files
authored
fix(actions): better runtime check for invalid usages (#12402)
1 parent f5f7109 commit 823e73b

File tree

8 files changed

+47
-5
lines changed

8 files changed

+47
-5
lines changed

.changeset/dull-lemons-check.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Fixes a case where Astro allowed to call an action without using `Astro.callAction`. This is now invalid, and Astro will show a proper error.
6+
7+
```diff
8+
---
9+
import { actions } from "astro:actions";
10+
11+
-const result = actions.getUser({ userId: 123 });
12+
+const result = Astro.callAction(actions.getUser, { userId: 123 });
13+
---
14+
```

packages/astro/src/actions/runtime/middleware.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { APIContext, MiddlewareNext } from '../../@types/astro.js';
33
import { defineMiddleware } from '../../core/middleware/index.js';
44
import { getOriginPathname } from '../../core/routing/rewrite.js';
55
import { ACTION_QUERY_PARAMS } from '../consts.js';
6-
import { formContentTypes, hasContentType } from './utils.js';
6+
import { ACTION_API_CONTEXT_SYMBOL, formContentTypes, hasContentType } from './utils.js';
77
import { getAction } from './virtual/get-action.js';
88
import {
99
type SafeResult,
@@ -100,6 +100,7 @@ async function handlePost({
100100
formData = await request.clone().formData();
101101
}
102102
const { getActionResult, callAction, props, redirect, ...actionAPIContext } = context;
103+
Reflect.set(actionAPIContext, ACTION_API_CONTEXT_SYMBOL, true);
103104
const action = baseAction.bind(actionAPIContext);
104105
const actionResult = await action(formData);
105106

packages/astro/src/actions/runtime/route.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { APIRoute } from '../../@types/astro.js';
2-
import { formContentTypes, hasContentType } from './utils.js';
2+
import { ACTION_API_CONTEXT_SYMBOL, formContentTypes, hasContentType } from './utils.js';
33
import { getAction } from './virtual/get-action.js';
44
import { serializeActionResult } from './virtual/shared.js';
55

@@ -28,6 +28,7 @@ export const POST: APIRoute = async (context) => {
2828
return new Response(null, { status: 415 });
2929
}
3030
const { getActionResult, callAction, props, redirect, ...actionAPIContext } = context;
31+
Reflect.set(actionAPIContext, ACTION_API_CONTEXT_SYMBOL, true);
3132
const action = baseAction.bind(actionAPIContext);
3233
const result = await action(args);
3334
const serialized = serializeActionResult(result);

packages/astro/src/actions/runtime/utils.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { APIContext } from '../../@types/astro.js';
22

3+
export const ACTION_API_CONTEXT_SYMBOL = Symbol.for('astro.actionAPIContext');
4+
35
export const formContentTypes = ['application/x-www-form-urlencoded', 'multipart/form-data'];
46

57
export function hasContentType(contentType: string, expected: string[]) {
@@ -26,3 +28,8 @@ export type MaybePromise<T> = T | Promise<T>;
2628
* `result.error.fields` will be typed with the `name` field.
2729
*/
2830
export type ErrorInferenceObject = Record<string, any>;
31+
32+
export function isActionAPIContext(ctx: ActionAPIContext): boolean {
33+
const symbol = Reflect.get(ctx, ACTION_API_CONTEXT_SYMBOL);
34+
return symbol === true;
35+
}

packages/astro/src/actions/runtime/virtual/server.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import { z } from 'zod';
22
import { ActionCalledFromServerError } from '../../../core/errors/errors-data.js';
33
import { AstroError } from '../../../core/errors/errors.js';
4-
import type { ActionAPIContext, ErrorInferenceObject, MaybePromise } from '../utils.js';
4+
import {
5+
type ActionAPIContext,
6+
type ErrorInferenceObject,
7+
type MaybePromise,
8+
isActionAPIContext,
9+
} from '../utils.js';
510
import { ActionError, ActionInputError, type SafeResult, callSafely } from './shared.js';
611

712
export * from './shared.js';
@@ -60,7 +65,8 @@ export function defineAction<
6065
: getJsonServerHandler(handler, inputSchema);
6166

6267
async function safeServerHandler(this: ActionAPIContext, unparsedInput: unknown) {
63-
if (typeof this === 'function') {
68+
// The ActionAPIContext should always contain the `params` property
69+
if (typeof this === 'function' || !isActionAPIContext(this)) {
6470
throw new AstroError(ActionCalledFromServerError);
6571
}
6672
return callSafely(() => serverHandler(unparsedInput, this));

packages/astro/src/actions/utils.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type fsMod from 'node:fs';
22
import * as eslexer from 'es-module-lexer';
33
import type { APIContext } from '../@types/astro.js';
44
import type { Locals } from './runtime/middleware.js';
5-
import type { ActionAPIContext } from './runtime/utils.js';
5+
import { ACTION_API_CONTEXT_SYMBOL, type ActionAPIContext } from './runtime/utils.js';
66
import { deserializeActionResult, getActionQueryString } from './runtime/virtual/shared.js';
77

88
export function hasActionPayload(locals: APIContext['locals']): locals is Locals {
@@ -23,6 +23,7 @@ export function createGetActionResult(locals: APIContext['locals']): APIContext[
2323

2424
export function createCallAction(context: ActionAPIContext): APIContext['callAction'] {
2525
return (baseAction, input) => {
26+
Reflect.set(context, ACTION_API_CONTEXT_SYMBOL, true);
2627
const action = baseAction.bind(context);
2728
return action(input) as any;
2829
};

packages/astro/test/actions.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,12 @@ describe('Astro Actions', () => {
132132
assert.equal(data, 'Hello, ben!');
133133
}
134134
});
135+
136+
it('Should fail when calling an action without using Astro.callAction', async () => {
137+
const res = await fixture.fetch('/invalid/');
138+
const text = await res.text();
139+
assert.match(text, /ActionCalledFromServerError/);
140+
});
135141
});
136142

137143
describe('build', () => {
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
import { actions } from "astro:actions";
3+
4+
// this is invalid, it should fail
5+
const result = await actions.imageUploadInChunks();
6+
---

0 commit comments

Comments
 (0)