@orthograph/host-cloudflare 0.0.0-stage → 0.1.0-next.1
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.
- package/LICENSE +202 -0
- package/README.md +2 -2
- package/dist/index.d.ts +21 -0
- package/dist/index.js +12 -0
- package/dist/modules/actors/internal/tables.d.ts +1 -0
- package/dist/modules/actors/internal/tables.js +5 -0
- package/dist/modules/actors/service.d.ts +18 -0
- package/dist/modules/actors/service.js +51 -0
- package/dist/modules/actors/types.d.ts +35 -0
- package/dist/modules/actors/types.js +1 -0
- package/dist/modules/auth/internal/instance.d.ts +4462 -0
- package/dist/modules/auth/internal/instance.js +36 -0
- package/dist/modules/auth/internal/oauth.d.ts +20 -0
- package/dist/modules/auth/internal/oauth.js +70 -0
- package/dist/modules/auth/internal/options.d.ts +4886 -0
- package/dist/modules/auth/internal/options.js +75 -0
- package/dist/modules/auth/internal/schema.d.ts +2 -0
- package/dist/modules/auth/internal/schema.js +41 -0
- package/dist/modules/auth/internal/world-token.d.ts +15 -0
- package/dist/modules/auth/internal/world-token.js +40 -0
- package/dist/modules/auth/service.d.ts +9 -0
- package/dist/modules/auth/service.js +96 -0
- package/dist/modules/auth/types.d.ts +75 -0
- package/dist/modules/auth/types.js +1 -0
- package/dist/modules/clock/internal/date.d.ts +17 -0
- package/dist/modules/clock/internal/date.js +45 -0
- package/dist/modules/clock/internal/door.d.ts +2 -0
- package/dist/modules/clock/internal/door.js +49 -0
- package/dist/modules/clock/internal/state.d.ts +5 -0
- package/dist/modules/clock/internal/state.js +78 -0
- package/dist/modules/clock/service.d.ts +2 -0
- package/dist/modules/clock/service.js +36 -0
- package/dist/modules/clock/types.d.ts +152 -0
- package/dist/modules/clock/types.js +1 -0
- package/dist/modules/database/service.d.ts +2 -0
- package/dist/modules/database/service.js +6 -0
- package/dist/modules/database/types.d.ts +7 -0
- package/dist/modules/database/types.js +1 -0
- package/dist/modules/follower/internal/entries.d.ts +9 -0
- package/dist/modules/follower/internal/entries.js +20 -0
- package/dist/modules/follower/internal/health.d.ts +18 -0
- package/dist/modules/follower/internal/health.js +27 -0
- package/dist/modules/follower/internal/outbox.d.ts +26 -0
- package/dist/modules/follower/internal/outbox.js +35 -0
- package/dist/modules/follower/internal/poll.d.ts +21 -0
- package/dist/modules/follower/internal/poll.js +23 -0
- package/dist/modules/follower/service.d.ts +31 -0
- package/dist/modules/follower/service.js +87 -0
- package/dist/modules/follower/types.d.ts +71 -0
- package/dist/modules/follower/types.js +4 -0
- package/dist/modules/inbound/internal/accept.d.ts +26 -0
- package/dist/modules/inbound/internal/accept.js +10 -0
- package/dist/modules/inbound/internal/read.d.ts +10 -0
- package/dist/modules/inbound/internal/read.js +26 -0
- package/dist/modules/inbound/internal/same.d.ts +1 -0
- package/dist/modules/inbound/internal/same.js +12 -0
- package/dist/modules/inbound/internal/verify.d.ts +6 -0
- package/dist/modules/inbound/internal/verify.js +57 -0
- package/dist/modules/inbound/service.d.ts +2 -0
- package/dist/modules/inbound/service.js +110 -0
- package/dist/modules/inbound/types.d.ts +28 -0
- package/dist/modules/inbound/types.js +1 -0
- package/dist/modules/journal/service.d.ts +2 -0
- package/dist/modules/journal/service.js +23 -0
- package/dist/modules/journal/types.d.ts +8 -0
- package/dist/modules/journal/types.js +1 -0
- package/dist/modules/relayer/internal/adopt.d.ts +19 -0
- package/dist/modules/relayer/internal/adopt.js +34 -0
- package/dist/modules/relayer/internal/check.d.ts +16 -0
- package/dist/modules/relayer/internal/check.js +141 -0
- package/dist/modules/relayer/internal/health.d.ts +5 -0
- package/dist/modules/relayer/internal/health.js +7 -0
- package/dist/modules/relayer/internal/live.d.ts +26 -0
- package/dist/modules/relayer/internal/live.js +25 -0
- package/dist/modules/relayer/internal/relay.d.ts +22 -0
- package/dist/modules/relayer/internal/relay.js +44 -0
- package/dist/modules/relayer/internal/store.d.ts +41 -0
- package/dist/modules/relayer/internal/store.js +44 -0
- package/dist/modules/relayer/service.d.ts +58 -0
- package/dist/modules/relayer/service.js +124 -0
- package/dist/modules/relayer/types.d.ts +75 -0
- package/dist/modules/relayer/types.js +1 -0
- package/dist/modules/store/internal/actors.d.ts +6 -0
- package/dist/modules/store/internal/actors.js +24 -0
- package/dist/modules/store/internal/commit.d.ts +10 -0
- package/dist/modules/store/internal/commit.js +57 -0
- package/dist/modules/store/internal/list.d.ts +10 -0
- package/dist/modules/store/internal/list.js +28 -0
- package/dist/modules/store/internal/rows.d.ts +14 -0
- package/dist/modules/store/internal/rows.js +29 -0
- package/dist/modules/store/internal/unique.d.ts +3 -0
- package/dist/modules/store/internal/unique.js +17 -0
- package/dist/modules/store/service.d.ts +2 -0
- package/dist/modules/store/service.js +71 -0
- package/dist/modules/store/types.d.ts +36 -0
- package/dist/modules/store/types.js +1 -0
- package/dist/modules/telemetry/internal/exporters.d.ts +21 -0
- package/dist/modules/telemetry/internal/exporters.js +66 -0
- package/dist/modules/telemetry/service.d.ts +2 -0
- package/dist/modules/telemetry/service.js +52 -0
- package/dist/modules/telemetry/types.d.ts +36 -0
- package/dist/modules/telemetry/types.js +1 -0
- package/dist/modules/timers/internal/controller.d.ts +13 -0
- package/dist/modules/timers/internal/controller.js +63 -0
- package/dist/modules/timers/internal/count.d.ts +39 -0
- package/dist/modules/timers/internal/count.js +105 -0
- package/dist/modules/timers/internal/limits.d.ts +4 -0
- package/dist/modules/timers/internal/limits.js +8 -0
- package/dist/modules/timers/internal/table.d.ts +52 -0
- package/dist/modules/timers/internal/table.js +181 -0
- package/dist/modules/timers/service.d.ts +12 -0
- package/dist/modules/timers/service.js +136 -0
- package/dist/modules/timers/types.d.ts +82 -0
- package/dist/modules/timers/types.js +1 -0
- package/dist/modules/world/internal/entry.d.ts +34 -0
- package/dist/modules/world/internal/entry.js +69 -0
- package/dist/modules/world/internal/facts.d.ts +5 -0
- package/dist/modules/world/internal/facts.js +31 -0
- package/dist/modules/world/internal/fence.d.ts +9 -0
- package/dist/modules/world/internal/fence.js +90 -0
- package/dist/modules/world/internal/front-door.d.ts +5 -0
- package/dist/modules/world/internal/front-door.js +50 -0
- package/dist/modules/world/internal/leases.d.ts +33 -0
- package/dist/modules/world/internal/leases.js +79 -0
- package/dist/modules/world/internal/reset.d.ts +6 -0
- package/dist/modules/world/internal/reset.js +24 -0
- package/dist/modules/world/internal/work.d.ts +11 -0
- package/dist/modules/world/internal/work.js +73 -0
- package/dist/modules/world/internal/worlds.d.ts +7 -0
- package/dist/modules/world/internal/worlds.js +48 -0
- package/dist/modules/world/service.d.ts +80 -0
- package/dist/modules/world/service.js +209 -0
- package/dist/modules/world/types.d.ts +47 -0
- package/dist/modules/world/types.js +1 -0
- package/package.json +41 -3
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { bearer, deviceAuthorization, jwt } from "better-auth/plugins";
|
|
2
|
+
import { apiKey } from "@better-auth/api-key";
|
|
3
|
+
import { oauthProvider } from "@better-auth/oauth-provider";
|
|
4
|
+
const PREFIXES = { user: "per", session: "ses", account: "acc", verification: "ver", apikey: "key" };
|
|
5
|
+
const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
6
|
+
/** 16 lowercase base36 characters, rejection-sampled so none is likelier than another. */
|
|
7
|
+
const suffix = () => {
|
|
8
|
+
let out = "";
|
|
9
|
+
while (out.length < 16)
|
|
10
|
+
for (const b of crypto.getRandomValues(new Uint8Array(16)))
|
|
11
|
+
if (b < 252 && out.length < 16)
|
|
12
|
+
out += ALPHABET[b % 36];
|
|
13
|
+
return out;
|
|
14
|
+
};
|
|
15
|
+
/** API keys start `ak_`, so a bearer credential says which kind it is. */
|
|
16
|
+
export const KEY_PREFIX = "ak_";
|
|
17
|
+
/**
|
|
18
|
+
* The plugin's per-key limit is off, on purpose (#449). Left unset, `@better-auth/api-key` 1.7.15 refuses a key after 10
|
|
19
|
+
* calls in 24 hours (`dist/index.mjs:2338-2339`), and `rateLimit: { enabled: false }` below does not reach it, so an
|
|
20
|
+
* agent holding a key went anonymous on its 11th call. Nothing in design/ or docs/canon asks for a per-key limit, and a
|
|
21
|
+
* counter kept in the key's row would write to D1 on every call. A limit on keys is the host's to set, as it is for every
|
|
22
|
+
* other caller; a blueprint-declared one can come with that work, never as this silent default.
|
|
23
|
+
*/
|
|
24
|
+
export const NO_KEY_LIMIT = { enabled: false };
|
|
25
|
+
/** The mark on a key made for an agent (`metadata.acts`): a call made with it is an agent's, acting for the key's person (M2-auth, fork 2). */
|
|
26
|
+
export const ACTS_FOR_AN_AGENT = "agent";
|
|
27
|
+
/** The device flow's polling interval; a client that polls faster is told `slow_down`. */
|
|
28
|
+
export const DEVICE_INTERVAL = "5s";
|
|
29
|
+
/** The one client the device flow answers to: the project's own CLI, `<project>-cli`. Any other id is refused. */
|
|
30
|
+
export const deviceClient = (cli) => deviceAuthorization({
|
|
31
|
+
verificationUri: "/device",
|
|
32
|
+
interval: DEVICE_INTERVAL,
|
|
33
|
+
validateClient: (clientId) => clientId === cli,
|
|
34
|
+
schema: { deviceCode: { modelName: "auth_device_code" } },
|
|
35
|
+
});
|
|
36
|
+
/** The scopes a client may ask for. A token says who the person is; what they may do is the operation's role check. */
|
|
37
|
+
export const SCOPES = ["openid", "profile", "email", "offline_access"];
|
|
38
|
+
/** Where the remote MCP server is, given the server's own origin: the one resource an access token may name. */
|
|
39
|
+
export const mcpResource = (origin) => `${origin}/mcp`;
|
|
40
|
+
const t = (name) => ({ modelName: `auth_${name}` });
|
|
41
|
+
/**
|
|
42
|
+
* OAuth 2.1 for the remote MCP server (D3 #122, the `mcp-oauth` spike): Better Auth's `oauthProvider` on the `jwt` plugin
|
|
43
|
+
* (EdDSA, the key in `auth_jwks`). Clients register themselves (MCP clients do); `infer` makes a loopback redirect a native
|
|
44
|
+
* client's, which the default `web` refuses. With an origin, the access token is a JWT whose audience is that origin's `/mcp`.
|
|
45
|
+
*/
|
|
46
|
+
const oauth = (origin) => [
|
|
47
|
+
jwt({ schema: { jwks: t("jwks") } }),
|
|
48
|
+
oauthProvider({
|
|
49
|
+
loginPage: "/login",
|
|
50
|
+
consentPage: "/consent",
|
|
51
|
+
allowDynamicClientRegistration: true,
|
|
52
|
+
allowUnauthenticatedClientRegistration: true,
|
|
53
|
+
clientRegistrationDefaultApplicationType: "infer",
|
|
54
|
+
scopes: [...SCOPES],
|
|
55
|
+
clientRegistrationAllowedScopes: [...SCOPES],
|
|
56
|
+
...(origin === undefined ? {} : { resources: [mcpResource(origin)], clientRegistrationDefaultResources: [mcpResource(origin)] }),
|
|
57
|
+
schema: {
|
|
58
|
+
oauthClient: t("oauth_client"), oauthRefreshToken: t("oauth_refresh_token"), oauthAccessToken: t("oauth_access_token"),
|
|
59
|
+
oauthConsent: t("oauth_consent"), oauthResource: t("oauth_resource"), oauthClientResource: t("oauth_client_resource"),
|
|
60
|
+
oauthClientAssertion: t("oauth_client_assertion"),
|
|
61
|
+
},
|
|
62
|
+
}),
|
|
63
|
+
];
|
|
64
|
+
export const optionsFor = (cli, origin) => ({
|
|
65
|
+
emailAndPassword: { enabled: true },
|
|
66
|
+
user: { modelName: "auth_user" },
|
|
67
|
+
session: { modelName: "auth_session" },
|
|
68
|
+
account: { modelName: "auth_account" },
|
|
69
|
+
verification: { modelName: "auth_verification" },
|
|
70
|
+
advanced: { database: { generateId: ({ model }) => `${PREFIXES[model] ?? model.slice(0, 3)}_${suffix()}` } },
|
|
71
|
+
rateLimit: { enabled: false },
|
|
72
|
+
// The jwt plugin's own /token would mint tokens that are not OAuth's; the provider's /oauth2/token is the one.
|
|
73
|
+
disabledPaths: ["/token"],
|
|
74
|
+
plugins: [bearer(), apiKey({ enableSessionForAPIKeys: true, enableMetadata: true, defaultPrefix: KEY_PREFIX, rateLimit: NO_KEY_LIMIT, schema: { apikey: { modelName: "auth_apikey" } } }), deviceClient(cli), ...oauth(origin)],
|
|
75
|
+
});
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Generated from internal/options.ts by scripts/auth-schema.ts. Do not edit.
|
|
2
|
+
/** Better Auth's tables, each statement safe to run again. */
|
|
3
|
+
export const SCHEMA = [
|
|
4
|
+
"create table if not exists \"auth_user\" (\"id\" text not null primary key, \"name\" text not null, \"email\" text not null unique, \"emailVerified\" integer not null, \"image\" text, \"createdAt\" date not null, \"updatedAt\" date not null)",
|
|
5
|
+
"create table if not exists \"auth_session\" (\"id\" text not null primary key, \"expiresAt\" date not null, \"token\" text not null unique, \"createdAt\" date not null, \"updatedAt\" date not null, \"ipAddress\" text, \"userAgent\" text, \"userId\" text not null references \"auth_user\" (\"id\") on delete cascade)",
|
|
6
|
+
"create table if not exists \"auth_account\" (\"id\" text not null primary key, \"accountId\" text not null, \"providerId\" text not null, \"userId\" text not null references \"auth_user\" (\"id\") on delete cascade, \"accessToken\" text, \"refreshToken\" text, \"idToken\" text, \"accessTokenExpiresAt\" date, \"refreshTokenExpiresAt\" date, \"scope\" text, \"password\" text, \"createdAt\" date not null, \"updatedAt\" date not null)",
|
|
7
|
+
"create table if not exists \"auth_verification\" (\"id\" text not null primary key, \"identifier\" text not null, \"value\" text not null, \"expiresAt\" date not null, \"createdAt\" date not null, \"updatedAt\" date not null)",
|
|
8
|
+
"create table if not exists \"auth_apikey\" (\"id\" text not null primary key, \"configId\" text not null, \"name\" text, \"start\" text, \"referenceId\" text not null, \"prefix\" text, \"key\" text not null, \"refillInterval\" integer, \"refillAmount\" integer, \"lastRefillAt\" date, \"enabled\" integer, \"rateLimitEnabled\" integer, \"rateLimitTimeWindow\" integer, \"rateLimitMax\" integer, \"requestCount\" integer, \"remaining\" integer, \"lastRequest\" date, \"expiresAt\" date, \"createdAt\" date not null, \"updatedAt\" date not null, \"permissions\" text, \"metadata\" text)",
|
|
9
|
+
"create table if not exists \"auth_device_code\" (\"id\" text not null primary key, \"deviceCode\" text not null, \"userCode\" text not null, \"userId\" text, \"expiresAt\" date not null, \"status\" text not null, \"lastPolledAt\" date, \"pollingInterval\" integer, \"clientId\" text, \"scope\" text)",
|
|
10
|
+
"create table if not exists \"auth_jwks\" (\"id\" text not null primary key, \"publicKey\" text not null, \"privateKey\" text not null, \"createdAt\" date not null, \"expiresAt\" date, \"alg\" text, \"crv\" text)",
|
|
11
|
+
"create table if not exists \"auth_oauth_client\" (\"id\" text not null primary key, \"clientId\" text not null unique, \"clientSecret\" text, \"clientDiscoveryId\" text, \"disabled\" integer, \"skipConsent\" integer, \"enableEndSession\" integer, \"subjectType\" text, \"scopes\" text, \"clientCredentialsScopes\" text, \"userId\" text references \"auth_user\" (\"id\") on delete cascade, \"createdAt\" date, \"updatedAt\" date, \"name\" text, \"uri\" text, \"icon\" text, \"contacts\" text, \"tos\" text, \"policy\" text, \"softwareId\" text, \"softwareVersion\" text, \"softwareStatement\" text, \"redirectUris\" text not null, \"postLogoutRedirectUris\" text, \"backchannelLogoutUri\" text, \"backchannelLogoutSessionRequired\" integer, \"tokenEndpointAuthMethod\" text, \"applicationType\" text, \"jwks\" text, \"jwksUri\" text, \"grantTypes\" text, \"responseTypes\" text, \"requirePKCE\" integer, \"dpopBoundAccessTokens\" integer, \"referenceId\" text, \"metadata\" text)",
|
|
12
|
+
"create table if not exists \"auth_oauth_resource\" (\"id\" text not null primary key, \"identifier\" text not null unique, \"name\" text not null, \"accessTokenTtl\" integer, \"refreshTokenTtl\" integer, \"signingAlgorithm\" text, \"signingKeyId\" text, \"allowedScopes\" text, \"customClaims\" text, \"dpopBoundAccessTokensRequired\" integer, \"disabled\" integer, \"createdAt\" date, \"updatedAt\" date, \"policyVersion\" integer, \"metadata\" text)",
|
|
13
|
+
"create table if not exists \"auth_oauth_client_resource\" (\"id\" text not null primary key, \"clientId\" text not null references \"auth_oauth_client\" (\"clientId\") on delete cascade, \"resourceId\" text not null references \"auth_oauth_resource\" (\"identifier\") on delete cascade, \"metadata\" text, \"createdAt\" date)",
|
|
14
|
+
"create table if not exists \"auth_oauth_refresh_token\" (\"id\" text not null primary key, \"token\" text not null unique, \"clientId\" text not null references \"auth_oauth_client\" (\"clientId\") on delete cascade, \"sessionId\" text references \"auth_session\" (\"id\") on delete set null, \"userId\" text not null references \"auth_user\" (\"id\") on delete cascade, \"referenceId\" text, \"authorizationCodeId\" text, \"resources\" text, \"requestedUserInfoClaims\" text, \"expiresAt\" date not null, \"createdAt\" date not null, \"revoked\" date, \"rotatedAt\" date, \"rotationReplayResponse\" text, \"rotationReplayExpiresAt\" date, \"authTime\" date, \"confirmation\" text, \"scopes\" text not null)",
|
|
15
|
+
"create table if not exists \"auth_oauth_access_token\" (\"id\" text not null primary key, \"token\" text not null unique, \"clientId\" text not null references \"auth_oauth_client\" (\"clientId\") on delete cascade, \"sessionId\" text references \"auth_session\" (\"id\") on delete set null, \"userId\" text references \"auth_user\" (\"id\") on delete cascade, \"referenceId\" text, \"authorizationCodeId\" text, \"resources\" text, \"requestedUserInfoClaims\" text, \"refreshId\" text references \"auth_oauth_refresh_token\" (\"id\") on delete cascade, \"expiresAt\" date not null, \"createdAt\" date not null, \"revoked\" date, \"confirmation\" text, \"scopes\" text not null)",
|
|
16
|
+
"create table if not exists \"auth_oauth_consent\" (\"id\" text not null primary key, \"clientId\" text not null references \"auth_oauth_client\" (\"clientId\") on delete cascade, \"userId\" text references \"auth_user\" (\"id\") on delete cascade, \"referenceId\" text, \"resources\" text, \"requestedUserInfoClaims\" text, \"scopes\" text not null, \"createdAt\" date not null, \"updatedAt\" date not null)",
|
|
17
|
+
"create table if not exists \"auth_oauth_client_assertion\" (\"id\" text not null primary key, \"expiresAt\" date not null)",
|
|
18
|
+
"create index if not exists \"auth_session_userId_idx\" on \"auth_session\" (\"userId\")",
|
|
19
|
+
"create index if not exists \"auth_account_userId_idx\" on \"auth_account\" (\"userId\")",
|
|
20
|
+
"create index if not exists \"auth_verification_identifier_idx\" on \"auth_verification\" (\"identifier\")",
|
|
21
|
+
"create index if not exists \"auth_apikey_configId_idx\" on \"auth_apikey\" (\"configId\")",
|
|
22
|
+
"create index if not exists \"auth_apikey_referenceId_idx\" on \"auth_apikey\" (\"referenceId\")",
|
|
23
|
+
"create index if not exists \"auth_apikey_key_idx\" on \"auth_apikey\" (\"key\")",
|
|
24
|
+
"create index if not exists \"auth_oauth_client_userId_idx\" on \"auth_oauth_client\" (\"userId\")",
|
|
25
|
+
"create index if not exists \"auth_oauth_client_resource_clientId_idx\" on \"auth_oauth_client_resource\" (\"clientId\")",
|
|
26
|
+
"create index if not exists \"auth_oauth_client_resource_resourceId_idx\" on \"auth_oauth_client_resource\" (\"resourceId\")",
|
|
27
|
+
"create index if not exists \"auth_oauth_refresh_token_clientId_idx\" on \"auth_oauth_refresh_token\" (\"clientId\")",
|
|
28
|
+
"create index if not exists \"auth_oauth_refresh_token_sessionId_idx\" on \"auth_oauth_refresh_token\" (\"sessionId\")",
|
|
29
|
+
"create index if not exists \"auth_oauth_refresh_token_userId_idx\" on \"auth_oauth_refresh_token\" (\"userId\")",
|
|
30
|
+
"create index if not exists \"auth_oauth_refresh_token_authorizationCodeId_idx\" on \"auth_oauth_refresh_token\" (\"authorizationCodeId\")",
|
|
31
|
+
"create index if not exists \"auth_oauth_access_token_clientId_idx\" on \"auth_oauth_access_token\" (\"clientId\")",
|
|
32
|
+
"create index if not exists \"auth_oauth_access_token_sessionId_idx\" on \"auth_oauth_access_token\" (\"sessionId\")",
|
|
33
|
+
"create index if not exists \"auth_oauth_access_token_userId_idx\" on \"auth_oauth_access_token\" (\"userId\")",
|
|
34
|
+
"create index if not exists \"auth_oauth_access_token_authorizationCodeId_idx\" on \"auth_oauth_access_token\" (\"authorizationCodeId\")",
|
|
35
|
+
"create index if not exists \"auth_oauth_access_token_refreshId_idx\" on \"auth_oauth_access_token\" (\"refreshId\")",
|
|
36
|
+
"create index if not exists \"auth_oauth_consent_clientId_idx\" on \"auth_oauth_consent\" (\"clientId\")",
|
|
37
|
+
"create index if not exists \"auth_oauth_consent_userId_idx\" on \"auth_oauth_consent\" (\"userId\")",
|
|
38
|
+
"create unique index if not exists \"auth_device_code_deviceCode_uidx\" on \"auth_device_code\" (\"deviceCode\")",
|
|
39
|
+
"create unique index if not exists \"auth_device_code_userCode_uidx\" on \"auth_device_code\" (\"userCode\")",
|
|
40
|
+
"create unique index if not exists \"auth_oauth_client_resource_clientId_resourceId_uidx\" on \"auth_oauth_client_resource\" (\"clientId\", \"resourceId\")"
|
|
41
|
+
];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Principal } from "orthograph";
|
|
3
|
+
/** What a world token starts with, so a bearer credential says which kind it is. */
|
|
4
|
+
export declare const WORLD_PREFIX = "wld_";
|
|
5
|
+
/** Who a world token is for. */
|
|
6
|
+
export type WorldCaller = {
|
|
7
|
+
readonly kind: "system";
|
|
8
|
+
} | {
|
|
9
|
+
readonly kind: "service";
|
|
10
|
+
readonly mount: string;
|
|
11
|
+
};
|
|
12
|
+
/** `wld_<payload in hex>.<signature>`: the caller it is for, signed. */
|
|
13
|
+
export declare const mint: (secret: string, caller: WorldCaller) => Effect.Effect<string>;
|
|
14
|
+
/** The principal a world token is for, or anonymous when it is not signed by this world's secret. A bad token is never an error. */
|
|
15
|
+
export declare const principalOf: (secret: string, token: string) => Effect.Effect<Principal>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// A world's token for a caller no sign-in makes: the system (the runtime's own work) and a service (an adapter's door).
|
|
2
|
+
// Neither has a credential in a real environment; a journey needs one to be either, so a world signs one with its own secret
|
|
3
|
+
// (M2-auth, fork 3). The server accepts it only where `/_world/*` is answered, so staging and production cannot be fooled by one.
|
|
4
|
+
import { Effect, Option, Schema } from "effect";
|
|
5
|
+
/** What a world token starts with, so a bearer credential says which kind it is. */
|
|
6
|
+
export const WORLD_PREFIX = "wld_";
|
|
7
|
+
const Caller = Schema.Union([
|
|
8
|
+
Schema.Struct({ kind: Schema.Literal("system") }),
|
|
9
|
+
Schema.Struct({ kind: Schema.Literal("service"), mount: Schema.String }),
|
|
10
|
+
]);
|
|
11
|
+
const parse = Schema.decodeUnknownOption(Schema.fromJsonString(Caller));
|
|
12
|
+
const HEX = /^[0-9a-f]*$/;
|
|
13
|
+
const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
14
|
+
const unhex = (text) => new Uint8Array(text.match(/../g)?.map((pair) => Number.parseInt(pair, 16)) ?? []);
|
|
15
|
+
/** The signature of `payload` under `secret`: HMAC-SHA-256, domain-separated from every other use of the secret. */
|
|
16
|
+
const sign = (secret, payload) => Effect.promise(() => {
|
|
17
|
+
const encoder = new TextEncoder();
|
|
18
|
+
return crypto.subtle
|
|
19
|
+
.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
|
|
20
|
+
.then((key) => crypto.subtle.sign("HMAC", key, encoder.encode(`world-token|${payload}`)))
|
|
21
|
+
.then((signature) => hex(new Uint8Array(signature)));
|
|
22
|
+
});
|
|
23
|
+
/** `wld_<payload in hex>.<signature>`: the caller it is for, signed. */
|
|
24
|
+
export const mint = (secret, caller) => {
|
|
25
|
+
const payload = hex(new TextEncoder().encode(JSON.stringify(caller)));
|
|
26
|
+
return sign(secret, payload).pipe(Effect.map((signature) => `${WORLD_PREFIX}${payload}.${signature}`));
|
|
27
|
+
};
|
|
28
|
+
const ANONYMOUS = { kind: "anonymous" };
|
|
29
|
+
/** The principal a world token is for, or anonymous when it is not signed by this world's secret. A bad token is never an error. */
|
|
30
|
+
export const principalOf = (secret, token) => {
|
|
31
|
+
const [payload = "", signature = ""] = token.slice(WORLD_PREFIX.length).split(".");
|
|
32
|
+
if (!HEX.test(payload) || payload.length % 2 !== 0)
|
|
33
|
+
return Effect.succeed(ANONYMOUS);
|
|
34
|
+
return sign(secret, payload).pipe(Effect.map((expected) => {
|
|
35
|
+
if (expected !== signature)
|
|
36
|
+
return ANONYMOUS;
|
|
37
|
+
const caller = parse(new TextDecoder().decode(unhex(payload)));
|
|
38
|
+
return Option.isSome(caller) ? caller.value : ANONYMOUS;
|
|
39
|
+
}));
|
|
40
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AuthD1Api } from "./types.ts";
|
|
2
|
+
/**
|
|
3
|
+
* A key is a credential for the API and the MCP door, never for Better Auth's own routes (M2-auth, fork 2; snag 446). With
|
|
4
|
+
* `enableSessionForAPIKeys` a key stands for its person's session at every route Better Auth serves, so an agent's key could mint a key
|
|
5
|
+
* with no agent mark, or upgrade one. The one door to `/api/auth/*` refuses any request that carries a key, whatever the route: a person
|
|
6
|
+
* signs in to make a key, and the server reads keys itself, through `Principals`, never through this door.
|
|
7
|
+
*/
|
|
8
|
+
export declare const carriesAKey: (request: Request) => boolean;
|
|
9
|
+
export declare const AuthD1: AuthD1Api;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { Effect, Layer, Option, Schema } from "effect";
|
|
2
|
+
import { Auth, AuthRefused, Principals } from "@orthograph/language-effect";
|
|
3
|
+
import { held, instance, statusOf } from "./internal/instance.js";
|
|
4
|
+
import { ACTS_FOR_AN_AGENT, KEY_PREFIX } from "./internal/options.js";
|
|
5
|
+
import * as worldToken from "./internal/world-token.js";
|
|
6
|
+
import * as oauth from "./internal/oauth.js";
|
|
7
|
+
const ANONYMOUS = { kind: "anonymous" };
|
|
8
|
+
/** Run a Better Auth call once its tables exist. A failure Better Auth didn't give a status is a defect. */
|
|
9
|
+
const call = (a, f) => Effect.tryPromise({ try: () => held(a).auth().then(f), catch: (e) => e });
|
|
10
|
+
const Acts = Schema.Struct({ acts: Schema.optionalKey(Schema.Unknown) });
|
|
11
|
+
const parseMark = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.NullOr(Acts)));
|
|
12
|
+
/**
|
|
13
|
+
* The mark of the key Better Auth just resolved: read from that key's own row (`session.id` is the key's id), once, with no second
|
|
14
|
+
* `verifyApiKey` to charge the key's rate limit again. Fails closed: a row that is missing, or whose metadata cannot be read, is
|
|
15
|
+
* `unreadable`, and an unreadable key is no one (review of #297, round 2).
|
|
16
|
+
*/
|
|
17
|
+
const markOf = (a, keyId) => Effect.tryPromise(() => held(a).db.prepare(`SELECT "metadata" FROM "auth_apikey" WHERE "id" = ?`).bind(keyId).first()).pipe(Effect.map((row) => {
|
|
18
|
+
if (row === null)
|
|
19
|
+
return "unreadable";
|
|
20
|
+
if (row.metadata === null || row.metadata === "")
|
|
21
|
+
return "plain";
|
|
22
|
+
const parsed = parseMark(row.metadata);
|
|
23
|
+
return Option.isNone(parsed) ? "unreadable" : parsed.value?.acts === ACTS_FOR_AN_AGENT ? "agent" : "plain";
|
|
24
|
+
}), Effect.orElseSucceed(() => "unreadable"));
|
|
25
|
+
/**
|
|
26
|
+
* The one place a resolved person becomes a principal, for every door (M2-auth, fork 2): a session is a person by session; a key is a person
|
|
27
|
+
* by key, or an agent when its row says so; a key whose row cannot be read is no one; at the MCP door every credential is an agent.
|
|
28
|
+
*/
|
|
29
|
+
const principalFor = (who, way, mark, door) => mark === "unreadable" ? ANONYMOUS
|
|
30
|
+
: door === "mcp" || mark === "agent" ? { kind: "agent", ...who, via: "agent" }
|
|
31
|
+
: { kind: "person", ...who, via: way };
|
|
32
|
+
/**
|
|
33
|
+
* Who a credential is. A session token is a person by session; an `ak_` key is a person by key, or an agent when it was made for one; a
|
|
34
|
+
* world's token is the system or a service, where worlds are hosted. Nothing, or a credential that is not good or cannot be read, is
|
|
35
|
+
* anonymous, never an error and never a person.
|
|
36
|
+
*/
|
|
37
|
+
const principalOf = (a, authorization, door = "api") => {
|
|
38
|
+
const credential = authorization?.match(/^Bearer\s+(\S+)$/i)?.[1];
|
|
39
|
+
if (!credential)
|
|
40
|
+
return Effect.succeed(ANONYMOUS);
|
|
41
|
+
if (credential.startsWith(worldToken.WORLD_PREFIX))
|
|
42
|
+
return held(a).worlds ? worldToken.principalOf(held(a).secret, credential) : Effect.succeed(ANONYMOUS);
|
|
43
|
+
const isKey = credential.startsWith(KEY_PREFIX);
|
|
44
|
+
const headers = new Headers(isKey ? { "x-api-key": credential } : { authorization: `Bearer ${credential}` });
|
|
45
|
+
return call(a, (auth) => auth.api.getSession({ headers })).pipe(Effect.flatMap((s) => {
|
|
46
|
+
if (!s)
|
|
47
|
+
return Effect.succeed(ANONYMOUS);
|
|
48
|
+
const who = { person: s.user.id, email: s.user.email };
|
|
49
|
+
return (isKey ? markOf(a, s.session.id) : Effect.succeed("plain")).pipe(Effect.map((mark) => principalFor(who, isKey ? "key" : "session", mark, door)));
|
|
50
|
+
}), Effect.orElseSucceed(() => ANONYMOUS));
|
|
51
|
+
};
|
|
52
|
+
const refused = (reason, status) => (e) => statusOf(e) === status ? Effect.fail(new AuthRefused({ reason })) : Effect.die(e);
|
|
53
|
+
const layer = (a) => Layer.mergeAll(Layer.succeed(Principals, { of: (authorization, door) => principalOf(a, authorization, door) }), Layer.succeed(Auth, {
|
|
54
|
+
signUp: (body) => call(a, (auth) => auth.api.signUpEmail({ body })).pipe(Effect.map((r) => ({ person: r.user.id })), Effect.catch(refused("taken", 422))),
|
|
55
|
+
signIn: (body) => call(a, (auth) => auth.api.signInEmail({ body })).pipe(Effect.catch(refused("credentials", 401)), Effect.flatMap((r) => call(a, (auth) => auth.api.getSession({ headers: new Headers({ authorization: `Bearer ${r.token}` }) })).pipe(Effect.orDie, Effect.flatMap((s) => (s ? Effect.succeed({ session: s.session.id, token: r.token }) : Effect.die(new Error("a new session didn't resolve"))))))),
|
|
56
|
+
// With no request headers: the server's own call, on the person's behalf.
|
|
57
|
+
createApiKey: ({ person, name }) => call(a, (auth) => auth.api.createApiKey({ body: { userId: person, name } })).pipe(Effect.map((r) => ({ apiKey: r.id, key: r.key })), Effect.orDie),
|
|
58
|
+
}));
|
|
59
|
+
/**
|
|
60
|
+
* A key is a credential for the API and the MCP door, never for Better Auth's own routes (M2-auth, fork 2; snag 446). With
|
|
61
|
+
* `enableSessionForAPIKeys` a key stands for its person's session at every route Better Auth serves, so an agent's key could mint a key
|
|
62
|
+
* with no agent mark, or upgrade one. The one door to `/api/auth/*` refuses any request that carries a key, whatever the route: a person
|
|
63
|
+
* signs in to make a key, and the server reads keys itself, through `Principals`, never through this door.
|
|
64
|
+
*/
|
|
65
|
+
export const carriesAKey = (request) => request.headers.has("x-api-key") || /^Bearer\s+ak_/i.test(request.headers.get("authorization") ?? "");
|
|
66
|
+
// A registration is capped before Better Auth sees it (D3 #123); everything else is Better Auth's.
|
|
67
|
+
const handle = (a, request) => Effect.gen(function* () {
|
|
68
|
+
if (carriesAKey(request))
|
|
69
|
+
return Response.json({ error: "a key is not a credential for the sign-in routes: sign in to use them" }, { status: 401 });
|
|
70
|
+
// Better Auth's own tables must exist before the guard counts one.
|
|
71
|
+
const refused = oauth.isRegistration(request) ? yield* Effect.tryPromise(() => held(a).auth()).pipe(Effect.andThen(oauth.registrationGuard(a))) : undefined;
|
|
72
|
+
return refused ?? (yield* Effect.tryPromise(() => held(a).auth(originOf(request)).then((auth) => auth.handler(request))));
|
|
73
|
+
}).pipe(Effect.orDie);
|
|
74
|
+
// OAuth's issuer and the MCP resource are the address a request was reached on: each is answered by the instance for its origin.
|
|
75
|
+
const originOf = (request) => new URL(request.url).origin;
|
|
76
|
+
const oauthApi = {
|
|
77
|
+
discovery: (a, request) => Effect.tryPromise(() => held(a).auth(originOf(request))).pipe(Effect.flatMap((auth) => oauth.discovery(auth, request)), Effect.orDie),
|
|
78
|
+
bearer: (a, request) => Effect.tryPromise(() => held(a).auth(originOf(request))).pipe(Effect.flatMap((auth) => oauth.bearer(a, auth, request)), Effect.orDie),
|
|
79
|
+
challenge: (request, error) => oauth.challenge(request, error),
|
|
80
|
+
};
|
|
81
|
+
const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
82
|
+
const random = (n) => Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => ALPHABET[b % 36]).join("");
|
|
83
|
+
const castMember = (a, name, anonymous, stored) => Effect.gen(function* () {
|
|
84
|
+
const member = stored ?? { email: `${name}.${random(8)}@world.test`, password: random(24) };
|
|
85
|
+
if (anonymous)
|
|
86
|
+
return { email: member.email, password: member.password };
|
|
87
|
+
const person = member.person ?? (yield* call(a, (auth) => auth.api.signUpEmail({ body: { email: member.email, password: member.password, name } })).pipe(Effect.orDie)).user.id;
|
|
88
|
+
const { token } = yield* call(a, (auth) => auth.api.signInEmail({ body: { email: member.email, password: member.password } })).pipe(Effect.orDie);
|
|
89
|
+
return { person, token, email: member.email, password: member.password };
|
|
90
|
+
});
|
|
91
|
+
const credential = (a, spec) => spec.kind === "system" || spec.kind === "service"
|
|
92
|
+
? worldToken.mint(held(a).secret, spec.kind === "system" ? { kind: "system" } : { kind: "service", mount: spec.mount }).pipe(Effect.map((token) => ({ token })))
|
|
93
|
+
: call(a, (auth) => auth.api.createApiKey({
|
|
94
|
+
body: { userId: spec.person, name: `world ${spec.kind}`, ...(spec.kind === "agent" ? { metadata: { acts: ACTS_FOR_AN_AGENT } } : {}) },
|
|
95
|
+
})).pipe(Effect.map((r) => ({ token: r.key })), Effect.orDie);
|
|
96
|
+
export const AuthD1 = { make: instance, layer, handle, oauth: oauthApi, castMember, credential };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Effect, Layer } from "effect";
|
|
2
|
+
import type { Principal } from "orthograph";
|
|
3
|
+
import type { Auth, Principals } from "@orthograph/language-effect";
|
|
4
|
+
export interface AuthOptions {
|
|
5
|
+
readonly db: D1Database;
|
|
6
|
+
/** At least 32 characters. Made fresh per local world; a named secret per deployed environment. */
|
|
7
|
+
readonly secret: string;
|
|
8
|
+
/** The device flow's one client id, the project's CLI (`acme-cli`); any other is refused. Defaults to `cli`. */
|
|
9
|
+
readonly cli?: string;
|
|
10
|
+
/**
|
|
11
|
+
* This server hosts worlds (`/_world/*` is answered): it accepts a world's token for the system or a service. Anywhere else, in staging
|
|
12
|
+
* and in production, such a token is anonymous.
|
|
13
|
+
*/
|
|
14
|
+
readonly worlds?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/** One Better Auth instance and the promise that its tables exist. Opaque outside this module. */
|
|
17
|
+
export interface AuthInstance {
|
|
18
|
+
readonly kind: "auth-d1";
|
|
19
|
+
}
|
|
20
|
+
/** A cast member: signed up (`person`, a fresh `token`) unless cast as anyone, and always their email and password. */
|
|
21
|
+
export interface CastMember {
|
|
22
|
+
readonly person?: string;
|
|
23
|
+
readonly token?: string;
|
|
24
|
+
readonly email: string;
|
|
25
|
+
readonly password: string;
|
|
26
|
+
}
|
|
27
|
+
/** Who an OAuth access token is for: the person, nobody (no token), or a token that is not good. */
|
|
28
|
+
export type Bearer = {
|
|
29
|
+
readonly kind: "person";
|
|
30
|
+
readonly principal: Principal;
|
|
31
|
+
} | {
|
|
32
|
+
readonly kind: "none";
|
|
33
|
+
} | {
|
|
34
|
+
readonly kind: "invalid";
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* A credential a world mints for a journey (`POST /_world/credential`): a key made for a person, a key made for an agent acting for
|
|
38
|
+
* a person, or a token for the system or a service, which no sign-in makes.
|
|
39
|
+
*/
|
|
40
|
+
export type CredentialSpec = {
|
|
41
|
+
readonly kind: "key";
|
|
42
|
+
readonly person: string;
|
|
43
|
+
} | {
|
|
44
|
+
readonly kind: "agent";
|
|
45
|
+
readonly person: string;
|
|
46
|
+
} | {
|
|
47
|
+
readonly kind: "system";
|
|
48
|
+
} | {
|
|
49
|
+
readonly kind: "service";
|
|
50
|
+
readonly mount: string;
|
|
51
|
+
};
|
|
52
|
+
export interface AuthD1Api {
|
|
53
|
+
readonly make: (options: AuthOptions) => AuthInstance;
|
|
54
|
+
/** `Principals` from a bearer session token or an `ak_` API key, and `Auth` for handlers. */
|
|
55
|
+
readonly layer: (auth: AuthInstance) => Layer.Layer<Principals | Auth>;
|
|
56
|
+
/** Better Auth's own routes (`/api/auth/*`: the device flow, sessions), answered as a `Response`. */
|
|
57
|
+
readonly handle: (auth: AuthInstance, request: Request) => Effect.Effect<Response>;
|
|
58
|
+
/**
|
|
59
|
+
* The OAuth side of the remote MCP server (D3 #122). OAuth's issuer (`<origin>/api/auth`) and the MCP resource
|
|
60
|
+
* (`<origin>/mcp`) are the address a request was reached on, so each is answered by the instance for that origin. The discovery
|
|
61
|
+
* documents Better Auth doesn't serve at the paths clients ask for (`undefined` for any other request), the check of an
|
|
62
|
+
* access token, and the `WWW-Authenticate` challenge.
|
|
63
|
+
*/
|
|
64
|
+
readonly oauth: {
|
|
65
|
+
readonly discovery: (auth: AuthInstance, request: Request) => Effect.Effect<Response | undefined>;
|
|
66
|
+
readonly bearer: (auth: AuthInstance, request: Request) => Effect.Effect<Bearer>;
|
|
67
|
+
readonly challenge: (request: Request, error?: "invalid_token") => string;
|
|
68
|
+
};
|
|
69
|
+
/** A credential for a journey's cast member, minted by a world. A key or an agent's key is the person's own; the others are signed by the world. */
|
|
70
|
+
readonly credential: (auth: AuthInstance, spec: CredentialSpec) => Effect.Effect<{
|
|
71
|
+
readonly token: string;
|
|
72
|
+
}>;
|
|
73
|
+
/** Sign `name` up (once; `stored` remembers) and in, or for an anonymous member only make up their credentials. */
|
|
74
|
+
readonly castMember: (auth: AuthInstance, name: string, anonymous: boolean, stored: CastMember | undefined) => Effect.Effect<CastMember>;
|
|
75
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { BusyBox } from "@orthograph/language-effect";
|
|
2
|
+
import type { ClockSource } from "../types.ts";
|
|
3
|
+
/** Replace the global `Date` with the proxy. Safe to call again. */
|
|
4
|
+
export declare const install: () => void;
|
|
5
|
+
/** Run `f` with the proxy reading `source` for it and everything it starts. */
|
|
6
|
+
export declare const inWorld: <A>(source: ClockSource, f: () => A) => A;
|
|
7
|
+
/**
|
|
8
|
+
* Run an entry in its world's time under its request's box. `end` gives the box's token back when the entry ends, whatever
|
|
9
|
+
* way it ends; a callback that throws before it returns a promise is a rejection like any other, so the cleanup is always attached.
|
|
10
|
+
*/
|
|
11
|
+
export declare const inEntry: <A>(source: ClockSource, box: BusyBox, f: () => Promise<A>, end: (box: BusyBox) => Promise<unknown>) => Promise<A>;
|
|
12
|
+
/** The box of the request that is running; nothing outside a request, or in a real world. */
|
|
13
|
+
export declare const boxOf: () => BusyBox | undefined;
|
|
14
|
+
/** Point the running request at a fresh source, as a durable sleep's wake does: only this request's cell, never another's. False outside a request. */
|
|
15
|
+
export declare const refresh: (source: ClockSource) => boolean;
|
|
16
|
+
/** The wall clock, whatever the proxy says. */
|
|
17
|
+
export declare const wall: () => number;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// The `Date` proxy (M8.05): one replacement of the global, installed once, whose `now()` and argument-less `new Date()`
|
|
2
|
+
// read the world's time for the request that is running. The store holds a clock source, not a number: a stepped world's
|
|
3
|
+
// instant stands still, and a scaled world's reads work out `worldAnchor + (real now - realAnchor) * speed` each time,
|
|
4
|
+
// from the real clock captured before the proxy went in, so a request that awaits I/O sees the world move on.
|
|
5
|
+
// Libraries inside the world (Better Auth, jose, Effect's default `Clock`) read `Date` at call time, so one patch reaches
|
|
6
|
+
// them all. Outside any request the proxy reads real time.
|
|
7
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
8
|
+
const RealDate = globalThis.Date;
|
|
9
|
+
const store = new AsyncLocalStorage();
|
|
10
|
+
const read = (source) => source === undefined ? RealDate.now() : source.kind === "stepped" ? source.instant : Math.floor(source.worldAnchor + (RealDate.now() - source.realAnchor) * source.speed);
|
|
11
|
+
const now = () => read(store.getStore()?.source);
|
|
12
|
+
const WorldDate = new Proxy(RealDate, {
|
|
13
|
+
// `newTarget` is forwarded so a subclass of Date keeps its own prototype and methods.
|
|
14
|
+
construct: (target, args, newTarget) => Reflect.construct(target, args.length === 0 ? [now()] : args, newTarget),
|
|
15
|
+
// `Date()` called without `new` returns a string.
|
|
16
|
+
apply: () => new RealDate(now()).toString(),
|
|
17
|
+
get: (target, key) => (key === "now" ? now : Reflect.get(target, key, target)),
|
|
18
|
+
});
|
|
19
|
+
/** Replace the global `Date` with the proxy. Safe to call again. */
|
|
20
|
+
export const install = () => {
|
|
21
|
+
if (globalThis.Date !== WorldDate)
|
|
22
|
+
globalThis.Date = WorldDate;
|
|
23
|
+
};
|
|
24
|
+
/** Run `f` with the proxy reading `source` for it and everything it starts. */
|
|
25
|
+
export const inWorld = (source, f) => store.run({ source }, f);
|
|
26
|
+
/**
|
|
27
|
+
* Run an entry in its world's time under its request's box. `end` gives the box's token back when the entry ends, whatever
|
|
28
|
+
* way it ends; a callback that throws before it returns a promise is a rejection like any other, so the cleanup is always attached.
|
|
29
|
+
*/
|
|
30
|
+
export const inEntry = (source, box, f, end) => {
|
|
31
|
+
const cell = { source, box };
|
|
32
|
+
return new Promise((resolve) => { resolve(store.run(cell, f)); }).finally(() => end(box));
|
|
33
|
+
};
|
|
34
|
+
/** The box of the request that is running; nothing outside a request, or in a real world. */
|
|
35
|
+
export const boxOf = () => store.getStore()?.box;
|
|
36
|
+
/** Point the running request at a fresh source, as a durable sleep's wake does: only this request's cell, never another's. False outside a request. */
|
|
37
|
+
export const refresh = (source) => {
|
|
38
|
+
const cell = store.getStore();
|
|
39
|
+
if (cell === undefined)
|
|
40
|
+
return false;
|
|
41
|
+
cell.source = source;
|
|
42
|
+
return true;
|
|
43
|
+
};
|
|
44
|
+
/** The wall clock, whatever the proxy says. */
|
|
45
|
+
export const wall = () => RealDate.now();
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The world's clock door, beside `cast` and `facts` (M8-checks call 9):
|
|
2
|
+
// GET /_world/clock { kind, now, timers }
|
|
3
|
+
// POST /_world/clock/advance { span } -> { now, fired }
|
|
4
|
+
// POST /_world/clock/move-to { to } -> { now, fired }
|
|
5
|
+
// A real clock refuses a move with 409 `ClockNotMovable`. With a controller (the world's timers, M8.07) a move settles:
|
|
6
|
+
// it fires what is due on the way, waits for quiet, and fails as 409 `NeverQuiet` naming who is busy. Without one it only
|
|
7
|
+
// sets the instant.
|
|
8
|
+
import { Effect } from "effect";
|
|
9
|
+
const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
10
|
+
const iso = (millis) => new Date(millis).toISOString();
|
|
11
|
+
/** Every refusal says where the world's clock stands now (`now`), so a caller that was refused after a move reached something still knows the instant. */
|
|
12
|
+
const refusal = (moved, now) => json({ ...moved.body, now }, moved.status);
|
|
13
|
+
const unsettled = (why, now) => why._tag === "Refused"
|
|
14
|
+
? json({ ...why.body, now }, why.status)
|
|
15
|
+
: why._tag === "WorldReset"
|
|
16
|
+
? json({ _tag: "WorldReset", now, message: "the world was reset while this move was running: nothing was moved after it" }, 409)
|
|
17
|
+
: why._tag === "NeverQuiet"
|
|
18
|
+
? json({ _tag: "NeverQuiet", busy: why.busy, now, message: `the world is never quiet: still busy ${why.busy.join(", ")}` }, 409)
|
|
19
|
+
: json({ _tag: "WakeFailed", owner: why.owner, name: why.name, now, message: `the timer ${why.owner} ${why.name} failed to wake: ${why.message}` }, 500);
|
|
20
|
+
/** A planned move, made: settled by the controller, or only set when the world has none. */
|
|
21
|
+
const make = (state, plan, controller) => {
|
|
22
|
+
if (controller === undefined) {
|
|
23
|
+
const planned = plan();
|
|
24
|
+
if (!planned.ok)
|
|
25
|
+
return Promise.resolve(refusal(planned, iso(state.now())));
|
|
26
|
+
const moved = state.moveTo(iso(planned.target));
|
|
27
|
+
return Promise.resolve(moved.ok ? json({ now: iso(moved.now), fired: [] }) : refusal(moved, iso(state.now())));
|
|
28
|
+
}
|
|
29
|
+
return Effect.runPromise(controller.settle(plan).pipe(Effect.match({
|
|
30
|
+
onSuccess: (settled) => json(settled),
|
|
31
|
+
onFailure: (why) => unsettled(why, iso(state.now())),
|
|
32
|
+
})));
|
|
33
|
+
};
|
|
34
|
+
export const clockDoor = (state, request, controller) => {
|
|
35
|
+
const { pathname } = new URL(request.url);
|
|
36
|
+
if (pathname === "/_world/clock" && request.method === "GET") {
|
|
37
|
+
const reading = { kind: state.kind, now: iso(state.now()), timers: controller?.timers() ?? [] };
|
|
38
|
+
return Promise.resolve(json(reading));
|
|
39
|
+
}
|
|
40
|
+
if (request.method !== "POST" || (pathname !== "/_world/clock/advance" && pathname !== "/_world/clock/move-to"))
|
|
41
|
+
return undefined;
|
|
42
|
+
return request.json().catch(() => ({})).then((body) => {
|
|
43
|
+
const { span, to } = body;
|
|
44
|
+
if (pathname === "/_world/clock/advance") {
|
|
45
|
+
return typeof span === "string" ? make(state, () => state.plan({ span }), controller) : Promise.resolve(json({ _tag: "BadMove", now: iso(state.now()), message: "advance names a span: { \"span\": \"1 month\" }" }, 400));
|
|
46
|
+
}
|
|
47
|
+
return typeof to === "string" ? make(state, () => state.plan({ to }), controller) : Promise.resolve(json({ _tag: "BadMove", now: iso(state.now()), message: "move-to names an instant: { \"to\": \"2027-01-10T09:00:00Z\" }" }, 400));
|
|
48
|
+
});
|
|
49
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ClockDeclaration, ClockState } from "../types.ts";
|
|
2
|
+
/** `from` plus a span in words: seconds to weeks are fixed lengths; months and years go by the calendar, in UTC. */
|
|
3
|
+
export declare const plus: (from: number, span: string) => number | undefined;
|
|
4
|
+
/** A world's clock over its storage. A real clock keeps nothing and refuses every move. */
|
|
5
|
+
export declare const stateOf: (sql: SqlStorage, declaration: ClockDeclaration) => ClockState;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// The instant a world keeps: one row in the world's own SQLite storage. Stepped time stands still until it is moved;
|
|
2
|
+
// scaled time flows at its speed from the real instant the row was last written; real time is the wall clock and has no row.
|
|
3
|
+
import { DateTime, Option } from "effect";
|
|
4
|
+
import { Spans } from "orthograph/server";
|
|
5
|
+
import { wall } from "./date.js";
|
|
6
|
+
const UNIT_MS = { second: 1_000, minute: 60_000, hour: 3_600_000, day: 86_400_000, week: 604_800_000 };
|
|
7
|
+
/** The furthest instant a `Date` can hold, in milliseconds from the epoch. */
|
|
8
|
+
const MAX_INSTANT = 8.64e15;
|
|
9
|
+
const refused = (status, _tag, message) => ({ ok: false, status, body: { _tag, message } });
|
|
10
|
+
/** `from` plus a span in words: seconds to weeks are fixed lengths; months and years go by the calendar, in UTC. */
|
|
11
|
+
export const plus = (from, span) => {
|
|
12
|
+
const read = Spans.read(span);
|
|
13
|
+
if (read === undefined)
|
|
14
|
+
return undefined;
|
|
15
|
+
if (read.unit === "month" || read.unit === "year") {
|
|
16
|
+
return DateTime.toEpochMillis(DateTime.add(DateTime.makeUnsafe(from), read.unit === "month" ? { months: read.count } : { years: read.count }));
|
|
17
|
+
}
|
|
18
|
+
return from + read.count * UNIT_MS[read.unit];
|
|
19
|
+
};
|
|
20
|
+
const SCHEMA = "CREATE TABLE IF NOT EXISTS clock (one INTEGER PRIMARY KEY CHECK (one = 1), instant INTEGER NOT NULL, speed REAL NOT NULL, anchor INTEGER NOT NULL)";
|
|
21
|
+
/** A world's clock over its storage. A real clock keeps nothing and refuses every move. */
|
|
22
|
+
export const stateOf = (sql, declaration) => {
|
|
23
|
+
if (declaration.kind === "real") {
|
|
24
|
+
const no = () => refused(409, "ClockNotMovable", "this world runs on the real clock, which nothing can move");
|
|
25
|
+
return { kind: "real", now: wall, source: () => undefined, reset: () => undefined, plan: no, advance: no, moveTo: no };
|
|
26
|
+
}
|
|
27
|
+
sql.exec(SCHEMA);
|
|
28
|
+
const speed = declaration.kind === "scaled" ? declaration.speed : 0;
|
|
29
|
+
const starts = Option.getOrElse(Option.map(DateTime.make(declaration.starts), DateTime.toEpochMillis), () => wall());
|
|
30
|
+
sql.exec("INSERT OR IGNORE INTO clock (one, instant, speed, anchor) VALUES (1, ?, ?, ?)", starts, speed, wall());
|
|
31
|
+
const row = () => sql.exec("SELECT instant, speed, anchor FROM clock WHERE one = 1").one();
|
|
32
|
+
const now = () => {
|
|
33
|
+
const r = row();
|
|
34
|
+
return r.speed === 0 ? r.instant : Math.floor(r.instant + (wall() - r.anchor) * r.speed);
|
|
35
|
+
};
|
|
36
|
+
const set = (to) => {
|
|
37
|
+
// A `Date` holds at most 8.64e15 ms either side of the epoch; past that (or NaN) the world would be poisoned, so nothing is stored.
|
|
38
|
+
if (!Number.isFinite(to) || Math.abs(to) > MAX_INSTANT)
|
|
39
|
+
return refused(400, "BadMove", "that is further than any instant can be: the world's clock stays where it is");
|
|
40
|
+
sql.exec("UPDATE clock SET instant = ?, anchor = ? WHERE one = 1", to, wall());
|
|
41
|
+
return { ok: true, now: to };
|
|
42
|
+
};
|
|
43
|
+
const fits = (target) => !Number.isFinite(target) || Math.abs(target) > MAX_INSTANT
|
|
44
|
+
? refused(400, "BadMove", "that is further than any instant can be: the world's clock stays where it is")
|
|
45
|
+
: { ok: true, target };
|
|
46
|
+
const planSpan = (span) => {
|
|
47
|
+
const target = plus(now(), span);
|
|
48
|
+
return target === undefined ? refused(400, "BadMove", `"${span}" isn't a span: a whole number of seconds, minutes, hours, days, weeks, months or years, like "1 month"`) : fits(target);
|
|
49
|
+
};
|
|
50
|
+
const planTo = (to) => {
|
|
51
|
+
const at = DateTime.make(to);
|
|
52
|
+
if (Option.isNone(at))
|
|
53
|
+
return refused(400, "BadMove", `"${to}" isn't an instant (ISO 8601, like 2027-01-10T09:00:00Z)`);
|
|
54
|
+
const target = DateTime.toEpochMillis(at.value);
|
|
55
|
+
return target < now() ? refused(400, "BadMove", `the world's clock never goes back: it is at ${new Date(now()).toISOString()}`) : fits(target);
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
kind: declaration.kind,
|
|
59
|
+
now,
|
|
60
|
+
plan: (move) => ("span" in move ? planSpan(move.span) : planTo(move.to)),
|
|
61
|
+
reset: () => void sql.exec("UPDATE clock SET instant = ?, anchor = ? WHERE one = 1", starts, wall()),
|
|
62
|
+
source: () => {
|
|
63
|
+
const r = row();
|
|
64
|
+
return r.speed === 0 ? { kind: "stepped", instant: r.instant } : { kind: "scaled", realAnchor: r.anchor, worldAnchor: r.instant, speed: r.speed };
|
|
65
|
+
},
|
|
66
|
+
advance: (span) => {
|
|
67
|
+
const target = plus(now(), span);
|
|
68
|
+
return target === undefined ? refused(400, "BadMove", `"${span}" isn't a span: a whole number of seconds, minutes, hours, days, weeks, months or years, like "1 month"`) : set(target);
|
|
69
|
+
},
|
|
70
|
+
moveTo: (to) => {
|
|
71
|
+
const at = DateTime.make(to);
|
|
72
|
+
if (Option.isNone(at))
|
|
73
|
+
return refused(400, "BadMove", `"${to}" isn't an instant (ISO 8601, like 2027-01-10T09:00:00Z)`);
|
|
74
|
+
const target = DateTime.toEpochMillis(at.value);
|
|
75
|
+
return target < now() ? refused(400, "BadMove", `the world's clock never goes back: it is at ${new Date(now()).toISOString()}`) : set(target);
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
};
|