@artemis-apps/app-server 0.0.0-stage → 0.1.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 (64) hide show
  1. package/dist/account-deletion/account-deletion.service.d.ts +18 -0
  2. package/dist/account-deletion/account-deletion.service.js +18 -0
  3. package/dist/activity/core-activity.client.d.ts +20 -0
  4. package/dist/activity/core-activity.client.js +32 -0
  5. package/dist/core-api/core-api.client.d.ts +25 -0
  6. package/dist/core-api/core-api.client.js +63 -0
  7. package/dist/enrollment/enrollment.service.d.ts +30 -0
  8. package/dist/enrollment/enrollment.service.js +103 -0
  9. package/dist/entity-grants/entity-grant.service.d.ts +22 -0
  10. package/dist/entity-grants/entity-grant.service.js +49 -0
  11. package/dist/events/security-event.routes.d.ts +24 -0
  12. package/dist/events/security-event.routes.js +28 -0
  13. package/dist/handlers/handler.routes.d.ts +32 -0
  14. package/dist/handlers/handler.routes.js +74 -0
  15. package/dist/icon/app-icon.routes.d.ts +15 -0
  16. package/dist/icon/app-icon.routes.js +18 -0
  17. package/dist/index.d.ts +11 -0
  18. package/dist/index.js +4 -0
  19. package/dist/keys/app-key.entity.d.ts +67 -0
  20. package/dist/keys/app-key.entity.js +10 -0
  21. package/dist/keys/app-key.repository.d.ts +14 -0
  22. package/dist/keys/app-key.repository.js +38 -0
  23. package/dist/manifest/manifest.routes.d.ts +115 -0
  24. package/dist/manifest/manifest.routes.js +9 -0
  25. package/dist/oidc/account-claims.d.ts +5 -0
  26. package/dist/oidc/account-claims.js +22 -0
  27. package/dist/oidc/oidc.client.d.ts +64 -0
  28. package/dist/oidc/oidc.client.js +205 -0
  29. package/dist/platform.config.d.ts +22 -0
  30. package/dist/platform.config.js +0 -0
  31. package/dist/platform.d.ts +387 -0
  32. package/dist/platform.js +125 -0
  33. package/dist/platform.tables.d.ts +448 -0
  34. package/dist/platform.tables.js +9 -0
  35. package/dist/providers/provider.routes.d.ts +78 -0
  36. package/dist/providers/provider.routes.js +208 -0
  37. package/dist/relay/core-relay.routes.d.ts +26 -0
  38. package/dist/relay/core-relay.routes.js +64 -0
  39. package/dist/session/app-session.entity.d.ts +301 -0
  40. package/dist/session/app-session.entity.js +26 -0
  41. package/dist/session/app-session.repository.d.ts +34 -0
  42. package/dist/session/app-session.repository.js +87 -0
  43. package/dist/session/app-sign-in-attempt.entity.d.ts +82 -0
  44. package/dist/session/app-sign-in-attempt.entity.js +8 -0
  45. package/dist/session/app-sign-in-attempt.repository.d.ts +15 -0
  46. package/dist/session/app-sign-in-attempt.repository.js +29 -0
  47. package/dist/session/app.cookies.d.ts +22 -0
  48. package/dist/session/app.cookies.js +18 -0
  49. package/dist/session/require-permissions.middleware.d.ts +36 -0
  50. package/dist/session/require-permissions.middleware.js +34 -0
  51. package/dist/session/session.routes.d.ts +204 -0
  52. package/dist/session/session.routes.js +92 -0
  53. package/dist/session/session.service.d.ts +50 -0
  54. package/dist/session/session.service.js +137 -0
  55. package/dist/storage/core-storage.client.d.ts +27 -0
  56. package/dist/storage/core-storage.client.js +71 -0
  57. package/dist/testing/index.d.ts +2 -0
  58. package/dist/testing/index.js +3 -0
  59. package/dist/testing/platform-fixtures.d.ts +24 -0
  60. package/dist/testing/platform-fixtures.js +25 -0
  61. package/dist/testing/test-core.d.ts +73 -0
  62. package/dist/testing/test-core.js +134 -0
  63. package/package.json +45 -3
  64. package/README.md +0 -3
@@ -0,0 +1,18 @@
1
+ import type { Logger } from '@artemis-apps/server-kit';
2
+ import type { AppSessionRepository } from '../session/app-session.repository.ts';
3
+ /** What an app drops of its own when an account is deleted (its entities, their files...). */
4
+ export type AccountDeletionHandler = (accountId: string) => void | Promise<void>;
5
+ export interface AccountDeletionServiceOptions {
6
+ sessions: Pick<AppSessionRepository, 'deleteByAccount'>;
7
+ /** The app's own clean-up, after the platform's. */
8
+ onAccountDeleted?: AccountDeletionHandler;
9
+ logger: Logger;
10
+ }
11
+ /**
12
+ * Forgets a deleted account: signs it out of the app, then lets the app drop what it owned (the
13
+ * core drops the shares). Safe to repeat: the core may announce the same account twice.
14
+ */
15
+ export declare function createAccountDeletionService({ sessions, onAccountDeleted, logger, }: AccountDeletionServiceOptions): {
16
+ forget(accountId: string): Promise<void>;
17
+ };
18
+ export type AccountDeletionService = ReturnType<typeof createAccountDeletionService>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Forgets a deleted account: signs it out of the app, then lets the app drop what it owned (the
3
+ * core drops the shares). Safe to repeat: the core may announce the same account twice.
4
+ */
5
+ export function createAccountDeletionService({ sessions, onAccountDeleted, logger, }) {
6
+ return {
7
+ async forget(accountId) {
8
+ sessions.deleteByAccount(accountId);
9
+ try {
10
+ await onAccountDeleted?.(accountId);
11
+ }
12
+ catch (error) {
13
+ logger.error({ err: error, accountId }, 'Could not drop the data of a deleted account');
14
+ throw error;
15
+ }
16
+ },
17
+ };
18
+ }
@@ -0,0 +1,20 @@
1
+ import { type ActivityReport } from '@artemis-apps/contracts';
2
+ import type { Logger } from '@artemis-apps/server-kit';
3
+ import type { CoreApiClient } from '../core-api/core-api.client.ts';
4
+ export interface CoreActivityClientOptions {
5
+ coreApi: Pick<CoreApiClient, 'asApp'>;
6
+ logger: Logger;
7
+ }
8
+ /**
9
+ * Reports the app's own events to the core's activity log, server to server, with the app's
10
+ * own token. Actions must be in the app's namespaces (those of its permissions, e.g.
11
+ * `contacts:contact-created`): the core refuses the others.
12
+ */
13
+ export declare function createCoreActivityClient({ coreApi, logger }: CoreActivityClientOptions): {
14
+ /**
15
+ * Fire and forget: never throws and never needs awaiting, so reporting can't break or slow
16
+ * the request. Failures are logged. The returned promise settles once the core answered.
17
+ */
18
+ record(report: ActivityReport): Promise<void>;
19
+ };
20
+ export type CoreActivityClient = ReturnType<typeof createCoreActivityClient>;
@@ -0,0 +1,32 @@
1
+ import { CORE_ACTIVITY_PATHS } from '@artemis-apps/contracts';
2
+ /**
3
+ * Reports the app's own events to the core's activity log, server to server, with the app's
4
+ * own token. Actions must be in the app's namespaces (those of its permissions, e.g.
5
+ * `contacts:contact-created`): the core refuses the others.
6
+ */
7
+ export function createCoreActivityClient({ coreApi, logger }) {
8
+ async function send(report) {
9
+ try {
10
+ const response = await coreApi.asApp(CORE_ACTIVITY_PATHS.reports, {
11
+ method: 'POST',
12
+ headers: { 'content-type': 'application/json' },
13
+ body: JSON.stringify(report),
14
+ });
15
+ if (!response.ok) {
16
+ logger.error({ action: report.action, status: response.status }, 'The core refused an activity report');
17
+ }
18
+ }
19
+ catch (error) {
20
+ logger.error({ err: error, action: report.action }, 'Activity not reported: the core is unreachable or the app not enrolled');
21
+ }
22
+ }
23
+ return {
24
+ /**
25
+ * Fire and forget: never throws and never needs awaiting, so reporting can't break or slow
26
+ * the request. Failures are logged. The returned promise settles once the core answered.
27
+ */
28
+ record(report) {
29
+ return send(report);
30
+ },
31
+ };
32
+ }
@@ -0,0 +1,25 @@
1
+ import type { EnrollmentService } from '../enrollment/enrollment.service.ts';
2
+ import type { PlatformConfig } from '../platform.config.ts';
3
+ import type { AppSession } from '../session/app-session.repository.ts';
4
+ import type { SessionService } from '../session/session.service.ts';
5
+ export interface CoreApiClientOptions {
6
+ config: PlatformConfig;
7
+ enrollment: Pick<EnrollmentService, 'appToken' | 'renewAppToken'>;
8
+ sessionService: Pick<SessionService, 'renew'>;
9
+ }
10
+ /**
11
+ * The app's server calling the core's API, with a bearer token: its own (`client_credentials`)
12
+ * or an account's. A token the core refuses before its expiry is renewed once.
13
+ */
14
+ export declare function createCoreApiClient({ config, enrollment, sessionService }: CoreApiClientOptions): {
15
+ /** As the app itself: its files, its activity reports, a provider's `server` actions. */
16
+ asApp(path: string, init?: RequestInit): Promise<Response>;
17
+ /**
18
+ * With a token the app holds apart from any session (an entity grant), as it is: a 401 means
19
+ * it expired, and nothing renews it.
20
+ */
21
+ withToken(accessToken: string, path: string, init?: RequestInit): Promise<Response>;
22
+ /** On behalf of the session's account: the relay (entities, entity types, directory, launcher). */
23
+ forAccount(session: AppSession, path: string, init?: RequestInit): Promise<Response>;
24
+ };
25
+ export type CoreApiClient = ReturnType<typeof createCoreApiClient>;
@@ -0,0 +1,63 @@
1
+ import { HTTPException } from 'hono/http-exception';
2
+ /** The core answers within this delay, or the request fails (unless the caller gives a signal). */
3
+ const CORE_REQUEST_TIMEOUT_MS = 30_000;
4
+ const signInRequired = () => new HTTPException(401, { message: 'Sign in to continue.' });
5
+ /**
6
+ * The app's server calling the core's API, with a bearer token: its own (`client_credentials`)
7
+ * or an account's. A token the core refuses before its expiry is renewed once.
8
+ */
9
+ export function createCoreApiClient({ config, enrollment, sessionService }) {
10
+ async function send(path, token, init) {
11
+ const headers = new Headers(init.headers);
12
+ headers.set('authorization', `Bearer ${token}`);
13
+ if (!headers.has('accept'))
14
+ headers.set('accept', 'application/json');
15
+ try {
16
+ return await (config.fetch ?? fetch)(new URL(path, config.coreUrl), {
17
+ ...init,
18
+ headers,
19
+ redirect: 'error',
20
+ // A caller expecting a longer answer (a preview the core waits for) gives its own signal.
21
+ signal: init.signal ?? AbortSignal.timeout(CORE_REQUEST_TIMEOUT_MS),
22
+ });
23
+ }
24
+ catch {
25
+ throw new HTTPException(502, { message: 'The core is unreachable.' });
26
+ }
27
+ }
28
+ return {
29
+ /** As the app itself: its files, its activity reports, a provider's `server` actions. */
30
+ async asApp(path, init = {}) {
31
+ const token = await enrollment.appToken();
32
+ if (!token)
33
+ throw new HTTPException(409, { message: 'This app is not enrolled.' });
34
+ const response = await send(path, token, init);
35
+ if (response.status !== 401)
36
+ return response;
37
+ const renewed = await enrollment.renewAppToken(token);
38
+ if (!renewed)
39
+ throw new HTTPException(409, { message: 'This app is not enrolled.' });
40
+ return send(path, renewed, init);
41
+ },
42
+ /**
43
+ * With a token the app holds apart from any session (an entity grant), as it is: a 401 means
44
+ * it expired, and nothing renews it.
45
+ */
46
+ withToken(accessToken, path, init = {}) {
47
+ return send(path, accessToken, init);
48
+ },
49
+ /** On behalf of the session's account: the relay (entities, entity types, directory, launcher). */
50
+ async forAccount(session, path, init = {}) {
51
+ const response = await send(path, session.accessToken, init);
52
+ if (response.status !== 401)
53
+ return response;
54
+ const renewed = await sessionService.renew(session);
55
+ if (!renewed)
56
+ throw signInRequired();
57
+ const retried = await send(path, renewed.accessToken, init);
58
+ if (retried.status === 401)
59
+ throw signInRequired();
60
+ return retried;
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,30 @@
1
+ import { type AppManifest } from '@artemis-apps/contracts';
2
+ import type { Logger } from '@artemis-apps/server-kit';
3
+ import { type OidcClient } from '../oidc/oidc.client.ts';
4
+ import type { PlatformConfig } from '../platform.config.ts';
5
+ import type { AppSessionRepository } from '../session/app-session.repository.ts';
6
+ import type { AppSignInAttemptRepository } from '../session/app-sign-in-attempt.repository.ts';
7
+ export interface EnrollmentServiceOptions {
8
+ config: PlatformConfig;
9
+ oidcClient: Pick<OidcClient, 'requestAppToken'>;
10
+ manifest: () => Promise<AppManifest>;
11
+ sessions: Pick<AppSessionRepository, 'deleteAll'>;
12
+ signInAttempts: Pick<AppSignInAttemptRepository, 'deleteAll'>;
13
+ /** Where a manifest the core refused is logged. */
14
+ logger: Logger;
15
+ }
16
+ /**
17
+ * Whether the core accepts this app, learnt by asking it for a `client_credentials` token: the
18
+ * app stores nothing about its enrollment but its key (see docs/architecture/enrollment.md).
19
+ * The token it gets is the one the app calls the core with, as itself.
20
+ */
21
+ export declare function createEnrollmentService({ config, oidcClient, manifest, sessions, signInAttempts, logger, }: EnrollmentServiceOptions): {
22
+ isEnrolled(): Promise<boolean>;
23
+ /** The app's own access token; `undefined` while it is not enrolled. */
24
+ appToken(): Promise<string | undefined>;
25
+ /** The core refused the app token before its expiry: get another one. */
26
+ renewAppToken(refused: string): Promise<string | undefined>;
27
+ /** The core revoked the app, or does not know it any more (`invalid_client`). */
28
+ forget: () => void;
29
+ };
30
+ export type EnrollmentService = ReturnType<typeof createEnrollmentService>;
@@ -0,0 +1,103 @@
1
+ import { CORE_API_PATHS } from '@artemis-apps/contracts';
2
+ import { HTTPException } from 'hono/http-exception';
3
+ import { InvalidClientError } from '../oidc/oidc.client.js';
4
+ /** While unenrolled, the core is asked at most this often (the manifest page polls). */
5
+ const ENROLLMENT_PROBE_INTERVAL_MS = 5 * 1000;
6
+ /** An app token is renewed slightly before it expires. */
7
+ const APP_TOKEN_MARGIN_MS = 30 * 1000;
8
+ /**
9
+ * Whether the core accepts this app, learnt by asking it for a `client_credentials` token: the
10
+ * app stores nothing about its enrollment but its key (see docs/architecture/enrollment.md).
11
+ * The token it gets is the one the app calls the core with, as itself.
12
+ */
13
+ export function createEnrollmentService({ config, oidcClient, manifest, sessions, signInAttempts, logger, }) {
14
+ let appToken;
15
+ /** Whether the core last accepted the app: a refusal then means it was revoked meanwhile. */
16
+ let enrolled = false;
17
+ /** When the core last said it does not know the app. */
18
+ let refusedAt;
19
+ /** Whether the manifest went to the core since the app started or was enrolled again. */
20
+ let manifestSent = false;
21
+ let pending;
22
+ /** Sends the manifest to the core, which applies it or keeps it for an administrator. */
23
+ async function sendManifest(token) {
24
+ try {
25
+ const response = await (config.fetch ?? fetch)(new URL(CORE_API_PATHS.appManifest, config.coreUrl), {
26
+ method: 'PUT',
27
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
28
+ body: JSON.stringify(await manifest()),
29
+ });
30
+ if (!response.ok) {
31
+ logger.error({ status: response.status }, 'The core refused the app manifest');
32
+ }
33
+ }
34
+ catch (error) {
35
+ logger.error({ err: error }, 'The core is unreachable: manifest not sent');
36
+ }
37
+ }
38
+ /** Forgets the enrollment: sessions and pending sign-ins belong to the revoked client. */
39
+ function forget() {
40
+ appToken = undefined;
41
+ enrolled = false;
42
+ refusedAt = Date.now();
43
+ manifestSent = false;
44
+ sessions.deleteAll();
45
+ signInAttempts.deleteAll();
46
+ }
47
+ async function requestToken() {
48
+ try {
49
+ const token = await oidcClient.requestAppToken();
50
+ appToken = token;
51
+ enrolled = true;
52
+ refusedAt = undefined;
53
+ if (!manifestSent) {
54
+ manifestSent = true;
55
+ void sendManifest(token.accessToken);
56
+ }
57
+ return token;
58
+ }
59
+ catch (error) {
60
+ if (!(error instanceof InvalidClientError)) {
61
+ logger.error({ err: error }, 'The core could not grant the app token');
62
+ throw new HTTPException(502, { message: 'The core is unreachable.' });
63
+ }
64
+ // Revoked since the last token (expired, or refused and dropped by `renewAppToken`): what
65
+ // belonged to the client goes. Already unenrolled: no need to clear anything again, only
66
+ // to wait before asking again.
67
+ if (enrolled)
68
+ forget();
69
+ else
70
+ refusedAt = Date.now();
71
+ return undefined;
72
+ }
73
+ }
74
+ /** A valid app token, or `undefined` while the app is not enrolled. One request at a time. */
75
+ async function currentToken() {
76
+ const now = Date.now();
77
+ if (appToken && appToken.expiresAt.getTime() - APP_TOKEN_MARGIN_MS > now)
78
+ return appToken;
79
+ if (refusedAt !== undefined && now - refusedAt < ENROLLMENT_PROBE_INTERVAL_MS)
80
+ return undefined;
81
+ pending ??= requestToken().finally(() => {
82
+ pending = undefined;
83
+ });
84
+ return pending;
85
+ }
86
+ return {
87
+ async isEnrolled() {
88
+ return (await currentToken()) !== undefined;
89
+ },
90
+ /** The app's own access token; `undefined` while it is not enrolled. */
91
+ async appToken() {
92
+ return (await currentToken())?.accessToken;
93
+ },
94
+ /** The core refused the app token before its expiry: get another one. */
95
+ async renewAppToken(refused) {
96
+ if (appToken?.accessToken === refused)
97
+ appToken = undefined;
98
+ return (await currentToken())?.accessToken;
99
+ },
100
+ /** The core revoked the app, or does not know it any more (`invalid_client`). */
101
+ forget,
102
+ };
103
+ }
@@ -0,0 +1,22 @@
1
+ import type { EntityGrantTarget, TypePermission } from '@artemis-apps/contracts';
2
+ import type { EntityGrant, OidcClient } from '../oidc/oidc.client.ts';
3
+ import type { AppSession } from '../session/app-session.repository.ts';
4
+ import type { SessionService } from '../session/session.service.ts';
5
+ export interface EntityGrantServiceOptions {
6
+ oidcClient: Pick<OidcClient, 'exchangeEntityGrant'>;
7
+ sessionService: Pick<SessionService, 'current' | 'renew' | 'asClient'>;
8
+ }
9
+ /**
10
+ * Entity grants (see docs/architecture/entities/entity-grants.md): the app exchanges the access
11
+ * token of an account's session for one reaching a single entity, which outlives the session (an
12
+ * editor saving a document after its last editor left). Call the core with it through
13
+ * `platform.core.withToken`.
14
+ */
15
+ export declare function createEntityGrantService({ oidcClient, sessionService, }: EntityGrantServiceOptions): {
16
+ /**
17
+ * A grant of `permissions` (of the entity's type) on `target`, for the session's account:
18
+ * a 403 when it doesn't reach the entity with them, a 401 once the session is gone.
19
+ */
20
+ exchange(session: AppSession, target: EntityGrantTarget, permissions: readonly TypePermission[]): Promise<EntityGrant>;
21
+ };
22
+ export type EntityGrantService = ReturnType<typeof createEntityGrantService>;
@@ -0,0 +1,49 @@
1
+ import { HTTPException } from 'hono/http-exception';
2
+ import { ResponseBodyError } from 'openid-client';
3
+ const signInRequired = () => new HTTPException(401, { message: 'Sign in to continue.' });
4
+ /**
5
+ * Entity grants (see docs/architecture/entities/entity-grants.md): the app exchanges the access
6
+ * token of an account's session for one reaching a single entity, which outlives the session (an
7
+ * editor saving a document after its last editor left). Call the core with it through
8
+ * `platform.core.withToken`.
9
+ */
10
+ export function createEntityGrantService({ oidcClient, sessionService, }) {
11
+ const exchangeOnce = (session, target, permissions) => sessionService.asClient(() => oidcClient.exchangeEntityGrant(session.accessToken, target, permissions));
12
+ return {
13
+ /**
14
+ * A grant of `permissions` (of the entity's type) on `target`, for the session's account:
15
+ * a 403 when it doesn't reach the entity with them, a 401 once the session is gone.
16
+ */
17
+ async exchange(session, target, permissions) {
18
+ const current = await sessionService.current(session);
19
+ if (!current)
20
+ throw signInRequired();
21
+ try {
22
+ return await exchangeOnce(current, target, [...permissions]);
23
+ }
24
+ catch (error) {
25
+ if (!(error instanceof ResponseBodyError))
26
+ throw error;
27
+ if (error.error !== 'invalid_request') {
28
+ // The account doesn't reach the entity with these permissions, or the app lacks them.
29
+ throw new HTTPException(403, { message: error.error_description ?? error.error });
30
+ }
31
+ // `invalid_request` also says the subject token is no good (RFC 8693 §2.2.2): the core
32
+ // refused the session's token before its expiry (it restarted, its grant changed). Once
33
+ // renewed, the exchange is tried again, once: a request malformed fails the same way.
34
+ const renewed = await sessionService.renew(current);
35
+ if (!renewed)
36
+ throw signInRequired();
37
+ try {
38
+ return await exchangeOnce(renewed, target, [...permissions]);
39
+ }
40
+ catch (retried) {
41
+ if (retried instanceof ResponseBodyError) {
42
+ throw new HTTPException(403, { message: retried.error_description ?? retried.error });
43
+ }
44
+ throw retried;
45
+ }
46
+ }
47
+ },
48
+ };
49
+ }
@@ -0,0 +1,24 @@
1
+ import type { AccountDeletionService } from '../account-deletion/account-deletion.service.ts';
2
+ import type { EnrollmentService } from '../enrollment/enrollment.service.ts';
3
+ import type { OidcClient } from '../oidc/oidc.client.ts';
4
+ export interface SecurityEventRoutesOptions {
5
+ /** This app's id: the audience of the events, and the subject of its revocation. */
6
+ appId: string;
7
+ oidcClient: Pick<OidcClient, 'verifyCoreToken'>;
8
+ enrollment: Pick<EnrollmentService, 'forget'>;
9
+ accountDeletionService: AccountDeletionService;
10
+ }
11
+ /**
12
+ * Where the core pushes Security Event Tokens (RFC 8935): signed by the core for this app, one
13
+ * event each. Handling the same event twice is harmless.
14
+ */
15
+ export declare function createSecurityEventRoutes({ appId, oidcClient, enrollment, accountDeletionService, }: SecurityEventRoutesOptions): import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, {
16
+ "/.well-known/artemis/events": {
17
+ $post: {
18
+ output: null;
19
+ outputFormat: "body";
20
+ status: 202;
21
+ input: {};
22
+ };
23
+ };
24
+ }, "/", "/.well-known/artemis/events">;
@@ -0,0 +1,28 @@
1
+ import { APP_PROTOCOL_PATHS, SECURITY_EVENT_TOKEN_TYPE, SECURITY_EVENTS, SecurityEventSchema, } from '@artemis-apps/contracts';
2
+ import { Hono } from 'hono';
3
+ import { HTTPException } from 'hono/http-exception';
4
+ /**
5
+ * Where the core pushes Security Event Tokens (RFC 8935): signed by the core for this app, one
6
+ * event each. Handling the same event twice is harmless.
7
+ */
8
+ export function createSecurityEventRoutes({ appId, oidcClient, enrollment, accountDeletionService, }) {
9
+ return new Hono().post(APP_PROTOCOL_PATHS.events, async (context) => {
10
+ const claims = await oidcClient.verifyCoreToken(await context.req.text(), SECURITY_EVENT_TOKEN_TYPE);
11
+ const events = Object.keys(claims.events ?? {});
12
+ const event = SecurityEventSchema.safeParse(events.length === 1 ? events[0] : undefined);
13
+ if (!event.success || typeof claims.sub !== 'string') {
14
+ throw new HTTPException(400, { message: 'Expected one known security event.' });
15
+ }
16
+ switch (event.data) {
17
+ case SECURITY_EVENTS.accountDeleted:
18
+ await accountDeletionService.forget(claims.sub);
19
+ break;
20
+ case SECURITY_EVENTS.appRevoked:
21
+ if (claims.sub !== appId)
22
+ throw new HTTPException(400, { message: 'Not this app.' });
23
+ enrollment.forget();
24
+ break;
25
+ }
26
+ return context.body(null, 202);
27
+ });
28
+ }
@@ -0,0 +1,32 @@
1
+ import { type AppManifestDeclaration, type HandledActionCall } from '@artemis-apps/contracts';
2
+ import { Hono } from 'hono';
3
+ import type { OidcClient } from '../oidc/oidc.client.ts';
4
+ /** A `server` action the core asks the app to run, and who asked for it. */
5
+ export interface HandledAction extends HandledActionCall {
6
+ /** The app that asked the core (a consumer for its account, or the entity's provider). */
7
+ callerAppId: string;
8
+ }
9
+ /**
10
+ * Runs a `server` action on the call's entity, reaching it with `call.grant` (through
11
+ * `platform.core.withToken`); its answer goes back to the caller as it is. The request's JSON
12
+ * body is read already: it is the call.
13
+ */
14
+ export type ActionHandler = (call: HandledAction, request: Request) => Promise<Response>;
15
+ /** The app's `server` actions, by entity type id then by action, as its manifest `handles` them. */
16
+ export type Handlers = Record<string, Record<string, ActionHandler>>;
17
+ /**
18
+ * Throws when the handlers and the manifest's `handles` disagree: a handler of an action the
19
+ * manifest doesn't handle, or isn't a `server` one; a `server` action handled with no handler.
20
+ */
21
+ export declare function checkHandlers(manifest: AppManifestDeclaration, handlers: Handlers): void;
22
+ export interface HandlerRoutesOptions {
23
+ manifest: AppManifestDeclaration;
24
+ handlers: Handlers;
25
+ oidcClient: Pick<OidcClient, 'verifyCoreToken'>;
26
+ }
27
+ /**
28
+ * The app's `server` actions (`APP_PROTOCOL_PATHS.handledAction`), called by the core only, with
29
+ * a token it signed for this app (`HANDLER_TOKEN_TYPE`): the call names the entity, its kind, and
30
+ * a grant of that entity for this app.
31
+ */
32
+ export declare function createHandlerRoutes({ manifest, handlers, oidcClient }: HandlerRoutesOptions): Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
@@ -0,0 +1,74 @@
1
+ import { APP_PROTOCOL_PATHS, entityAction, fillPath, HANDLER_TOKEN_TYPE, HandledActionCallSchema, } from '@artemis-apps/contracts';
2
+ import { Hono } from 'hono';
3
+ import { HTTPException } from 'hono/http-exception';
4
+ import { z } from 'zod';
5
+ /** The claims of the token the core signs to call a `server` action. */
6
+ const HandlerTokenClaimsSchema = z.object({
7
+ sub: z.string().min(1),
8
+ client_id: z.string().min(1),
9
+ });
10
+ const BEARER_PATTERN = /^Bearer\s+(\S+)$/i;
11
+ /** The `server` actions a manifest handles, as `<type> <action>` keys. */
12
+ function serverActionsOf(manifest) {
13
+ const actions = new Set();
14
+ for (const [typeId, handled] of Object.entries(manifest.handles ?? {})) {
15
+ const type = manifest.types.find((candidate) => candidate.id === typeId);
16
+ for (const action of Object.keys(handled)) {
17
+ if (type && entityAction(type, action)?.target === 'server')
18
+ actions.add(`${typeId} ${action}`);
19
+ }
20
+ }
21
+ return actions;
22
+ }
23
+ /**
24
+ * Throws when the handlers and the manifest's `handles` disagree: a handler of an action the
25
+ * manifest doesn't handle, or isn't a `server` one; a `server` action handled with no handler.
26
+ */
27
+ export function checkHandlers(manifest, handlers) {
28
+ const declared = serverActionsOf(manifest);
29
+ for (const [typeId, actions] of Object.entries(handlers)) {
30
+ for (const action of Object.keys(actions)) {
31
+ if (!declared.delete(`${typeId} ${action}`)) {
32
+ throw new Error(`Handle the server action "${action}" of "${typeId}" in the manifest to give it a handler.`);
33
+ }
34
+ }
35
+ }
36
+ const [missing] = declared;
37
+ if (missing) {
38
+ const [typeId, action] = missing.split(' ');
39
+ throw new Error(`Give the server action "${action}" of "${typeId}" a handler: the manifest handles it.`);
40
+ }
41
+ }
42
+ /**
43
+ * The app's `server` actions (`APP_PROTOCOL_PATHS.handledAction`), called by the core only, with
44
+ * a token it signed for this app (`HANDLER_TOKEN_TYPE`): the call names the entity, its kind, and
45
+ * a grant of that entity for this app.
46
+ */
47
+ export function createHandlerRoutes({ manifest, handlers, oidcClient }) {
48
+ checkHandlers(manifest, handlers);
49
+ const routes = new Hono();
50
+ for (const [typeId, actions] of Object.entries(handlers)) {
51
+ for (const [action, handler] of Object.entries(actions)) {
52
+ const kinds = manifest.handles?.[typeId]?.[action] ?? [];
53
+ routes.post(fillPath(APP_PROTOCOL_PATHS.handledAction, { type: typeId, action }), async (context) => {
54
+ const token = context.req.header('Authorization')?.match(BEARER_PATTERN)?.[1];
55
+ if (!token)
56
+ throw new HTTPException(401, { message: 'A core token is required.' });
57
+ const claims = HandlerTokenClaimsSchema.safeParse(await oidcClient.verifyCoreToken(token, HANDLER_TOKEN_TYPE));
58
+ if (!claims.success)
59
+ throw new HTTPException(401, { message: 'Invalid token.' });
60
+ const call = HandledActionCallSchema.safeParse(await context.req.json().catch(() => undefined));
61
+ if (!call.success || call.data.entity.type !== typeId) {
62
+ throw new HTTPException(400, { message: 'Expected a call of this action.' });
63
+ }
64
+ if (!kinds.includes(call.data.kind)) {
65
+ throw new HTTPException(404, {
66
+ message: `This app does not handle \`${call.data.kind}\`.`,
67
+ });
68
+ }
69
+ return handler({ ...call.data, callerAppId: claims.data.client_id }, context.req.raw);
70
+ });
71
+ }
72
+ }
73
+ return routes;
74
+ }
@@ -0,0 +1,15 @@
1
+ export interface AppIconRoutesOptions {
2
+ /** SVG document; `undefined` when the app has no icon. */
3
+ icon: string | undefined;
4
+ }
5
+ /** The app's icon, at the path every app shares (`APP_PROTOCOL_PATHS.icon`). */
6
+ export declare function createAppIconRoutes({ icon }: AppIconRoutesOptions): import("hono/hono-base").HonoBase<import("hono/types").BlankEnv, {
7
+ "/.well-known/artemis/icon.svg": {
8
+ $get: {
9
+ output: string;
10
+ outputFormat: "body";
11
+ status: import("hono/utils/http-status").ContentfulStatusCode;
12
+ input: {};
13
+ };
14
+ };
15
+ }, "/", "/.well-known/artemis/icon.svg">;
@@ -0,0 +1,18 @@
1
+ import { APP_PROTOCOL_PATHS } from '@artemis-apps/contracts';
2
+ import { Hono } from 'hono';
3
+ import { HTTPException } from 'hono/http-exception';
4
+ /** Browsers of every account load it (the core's app switcher): cached, but not forever. */
5
+ const ICON_CACHE = 'public, max-age=86400';
6
+ /** The SVG is an image: if opened as a document, nothing in it may run or load. */
7
+ const ICON_CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'";
8
+ /** The app's icon, at the path every app shares (`APP_PROTOCOL_PATHS.icon`). */
9
+ export function createAppIconRoutes({ icon }) {
10
+ return new Hono().get(APP_PROTOCOL_PATHS.icon, (context) => {
11
+ if (icon === undefined)
12
+ throw new HTTPException(404, { message: 'This app has no icon.' });
13
+ context.header('Content-Type', 'image/svg+xml; charset=utf-8');
14
+ context.header('Cache-Control', ICON_CACHE);
15
+ context.header('Content-Security-Policy', ICON_CONTENT_SECURITY_POLICY);
16
+ return context.body(icon);
17
+ });
18
+ }
@@ -0,0 +1,11 @@
1
+ export type { AccountDeletionHandler } from './account-deletion/account-deletion.service.ts';
2
+ export { type CoreActivityClient, createCoreActivityClient, } from './activity/core-activity.client.ts';
3
+ export type { ActionHandler, HandledAction, Handlers, } from './handlers/handler.routes.ts';
4
+ export type { EntityGrant } from './oidc/oidc.client.ts';
5
+ export type { PlatformConfig } from './platform.config.ts';
6
+ export { type PlatformDatabase, platformTables } from './platform.tables.ts';
7
+ export { createPlatform, type Platform, type PlatformOptions } from './platform.ts';
8
+ export type { ProviderCall, ProviderInput, Providers, TypeProvider, } from './providers/provider.routes.ts';
9
+ export type { AppSession } from './session/app-session.repository.ts';
10
+ export type { RequirePermissions, RequirePermissionsEnv, } from './session/require-permissions.middleware.ts';
11
+ export { type CoreStorageClient, createCoreStorageClient, type FileUpload, publicFileUrl, } from './storage/core-storage.client.ts';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createCoreActivityClient, } from './activity/core-activity.client.js';
2
+ export { platformTables } from './platform.tables.js';
3
+ export { createPlatform } from './platform.js';
4
+ export { createCoreStorageClient, publicFileUrl, } from './storage/core-storage.client.js';