@deslop/auth 0.1.1268 → 0.1.1270

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/dist/server.js CHANGED
@@ -5700,6 +5700,28 @@ const toSeconds = (self) => match$7(fromInputUnsafe$1(self), {
5700
5700
  onNegativeInfinity: () => -Infinity
5701
5701
  });
5702
5702
  /**
5703
+ * Converts a Duration to minutes.
5704
+ *
5705
+ * **Example** (Converting durations to minutes)
5706
+ *
5707
+ * ```ts import.meta.vitest
5708
+ * import { Duration } from "effect"
5709
+ *
5710
+ * Duration.toMinutes(Duration.seconds(120)) // => 2
5711
+ * Duration.toMinutes(Duration.hours(1)) // => 60
5712
+ * ```
5713
+ *
5714
+ * @stability stable
5715
+ * @category getters
5716
+ * @since 3.8.0
5717
+ */
5718
+ const toMinutes = (self) => match$7(fromInputUnsafe$1(self), {
5719
+ onMillis: (millis) => millis / 6e4,
5720
+ onNanos: (nanos) => nanosToUnit(nanos, 6e10),
5721
+ onInfinity: () => Infinity,
5722
+ onNegativeInfinity: () => -Infinity
5723
+ });
5724
+ /**
5703
5725
  * Gets the duration in nanoseconds as a bigint.
5704
5726
  *
5705
5727
  * **When to use**
@@ -89617,7 +89639,6 @@ var AuthError = class extends TaggedError()("AuthError", {
89617
89639
  "invalid_client_metadata",
89618
89640
  "invalid_redirect_uri",
89619
89641
  "invalid_grant",
89620
- "invalid_target",
89621
89642
  "invalid_scope",
89622
89643
  "unsupported_grant_type",
89623
89644
  "unsupported_response_type",
@@ -90411,6 +90432,12 @@ function layerOtlp(serviceName, url, runtime, version) {
90411
90432
  const AUTH_URL = "https://auth.mp281x.xyz";
90412
90433
  const ISSUER_PATH = "/api/auth";
90413
90434
  const APPS_PATH = "/api/apps";
90435
+ const COOKIE = {
90436
+ httpOnly: true,
90437
+ path: "/",
90438
+ sameSite: "lax",
90439
+ secure: true
90440
+ };
90414
90441
  const SESSION_COOKIE = "__Host-session";
90415
90442
  function matchingSessions(saved, userId) {
90416
90443
  return sort(filter$6(getSomes(saved), (session) => session.value.user.id === userId), mapInput(flip$1(Number$6), (session) => session.value.expiresAt));
@@ -91926,13 +91953,6 @@ function layerMcpAuth(resource) {
91926
91953
  // ../../packages/runtime/src/server.ts
91927
91954
  const LOOPBACK = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/iu;
91928
91955
  const OTLP = ["/v1/traces", "/v1/logs"];
91929
- const COOKIE$1 = {
91930
- httpOnly: true,
91931
- path: "/",
91932
- sameSite: "lax",
91933
- secure: true
91934
- };
91935
- const SIGN_IN_COOKIE = "__Host-sign-in";
91936
91956
  const packageRoot = match$1(endsWith(".ts")(import.meta.url), {
91937
91957
  onFalse: () => fileURLToPath(new URL("..", import.meta.url)),
91938
91958
  onTrue: cwd
@@ -92067,112 +92087,6 @@ const layerRoutes = use((router) => gen(function* () {
92067
92087
  }, { headers: { "cache-control": "no-store" } });
92068
92088
  }));
92069
92089
  }));
92070
- const SignInState = fromJsonString(Struct({
92071
- next: String$6,
92072
- state: String$6,
92073
- verifier: String$6
92074
- }));
92075
- const CallbackParams$1 = Struct({
92076
- code: optionalKey(String$6),
92077
- error: optionalKey(String$6),
92078
- iss: optionalKey(String$6),
92079
- state: optionalKey(String$6)
92080
- });
92081
- function signedOut(next, cause) {
92082
- return as(logWarning("The sign-in did not complete", cause), expireCookieUnsafe(redirect(next), SIGN_IN_COOKIE, COOKIE$1));
92083
- }
92084
- function layerSignIn(issuer) {
92085
- return use((router) => gen(function* () {
92086
- const sessions = yield* Sessions;
92087
- const random = yield* SecureRandom;
92088
- const digest = yield* Digest;
92089
- const canonical = new URL(yield* String$5("APP_URL")).origin;
92090
- const callback = new URL(CALLBACK_PATH, canonical).href;
92091
- const clientId = yield* cached(map$5(appName, (name) => clientIdOf({
92092
- name: capitalize(name),
92093
- redirects: [callback]
92094
- })));
92095
- function ended(headers) {
92096
- return match$8(sessionIdOf(headers), {
92097
- onNone: () => void_$1,
92098
- onSome: (id) => ignore$1(sessions.end(id), {
92099
- log: "Warn",
92100
- message: "The session could not be ended"
92101
- })
92102
- });
92103
- }
92104
- function toNext(handle) {
92105
- return flatMap$2(HttpServerRequest, (request) => match$8(filter$8(liftThrowable(() => new URL(new URL(request.url, canonical).searchParams.get("next") ?? canonical, canonical))(), (next) => next.origin === canonical), {
92106
- onNone: () => succeed$5(empty({ status: 400 })),
92107
- onSome: (next) => handle(request, next)
92108
- }));
92109
- }
92110
- yield* router.add("GET", "/auth/sign-in", toNext(fnUntraced(function* (_, next) {
92111
- const verifier = encode$3(yield* random.randomBytes(32));
92112
- const state = encode$3(yield* random.randomBytes(16));
92113
- const authorize = new URL(AUTHORIZE_PATH, issuer);
92114
- authorize.search = `${new URLSearchParams({
92115
- client_id: yield* clientId,
92116
- code_challenge: encode$3(yield* digest.digest(sha256, new TextEncoder().encode(verifier))),
92117
- code_challenge_method: "S256",
92118
- redirect_uri: callback,
92119
- response_type: "code",
92120
- scope: "deslop offline_access",
92121
- state
92122
- })}`;
92123
- return setCookieUnsafe(redirect(authorize.href), SIGN_IN_COOKIE, yield* encodeEffect(SignInState)({
92124
- next: next.href,
92125
- state,
92126
- verifier
92127
- }), {
92128
- ...COOKIE$1,
92129
- maxAge: "10 minutes"
92130
- });
92131
- })));
92132
- yield* router.add("GET", CALLBACK_PATH, gen(function* () {
92133
- const request = yield* HttpServerRequest;
92134
- return yield* match$8(yield* option$1(decodeUnknownEffect(SignInState)(request.cookies[SIGN_IN_COOKIE])), {
92135
- onNone: () => signedOut(canonical, "The sign-in expired or began in another browser"),
92136
- onSome: fnUntraced(function* (saved) {
92137
- const started = yield* result$1(gen(function* () {
92138
- const params = yield* schemaSearchParams(CallbackParams$1);
92139
- if (params.state !== saved.state) return yield* AuthError.make({ message: "The sign-in began in another browser" });
92140
- if (params.error !== void 0 || params.code === void 0) return yield* AuthError.make({ message: `Auth answered ${params.error ?? "without a code"}` });
92141
- if (params.iss !== new URL("/api/auth", issuer).href) return yield* AuthError.make({ message: "The answer came from another issuer" });
92142
- return yield* sessions.start({
92143
- client_id: yield* clientId,
92144
- code: params.code,
92145
- code_verifier: saved.verifier,
92146
- redirect_uri: callback
92147
- });
92148
- }));
92149
- if (isFailure$1(started)) return yield* signedOut(saved.next, started.failure);
92150
- return pipe(redirect(saved.next), expireCookieUnsafe(SIGN_IN_COOKIE, COOKIE$1), setCookieUnsafe(SESSION_COOKIE, started.success, {
92151
- ...COOKIE$1,
92152
- maxAge: "365 days"
92153
- }));
92154
- })
92155
- });
92156
- }));
92157
- yield* router.add("POST", "/auth/session", gen(function* () {
92158
- const started = yield* result$1(pipe(schemaBodyJson(CodeGrant), rejected("The sign-in request is invalid"), flatMap$2(sessions.start)));
92159
- if (isFailure$1(started)) return text(started.failure.message, failureOptions(started.failure, 400));
92160
- return yield* schemaJson(SessionHandle)({ session: started.success }, { headers: { "cache-control": "no-store" } });
92161
- }));
92162
- yield* router.add("GET", "/auth/sign-out", toNext((request, next) => as(ended(request.headers), expireCookieUnsafe(redirect(`${new URL("/", issuer).href}?${new URLSearchParams({
92163
- next: next.href,
92164
- "sign-out": ""
92165
- })}`), SESSION_COOKIE, COOKIE$1))));
92166
- yield* router.add("POST", "/auth/sign-out", as(flatMap$2(HttpServerRequest, (request) => ended(request.headers)), empty({ status: 204 })));
92167
- }));
92168
- }
92169
- const notConfigured = text("Sign-in is not configured for this app", { status: 503 });
92170
- const layerSessionRoutes = unwrap$7(gen(function* () {
92171
- return match$8(yield* option(String$5("AUTH_URL")), {
92172
- onNone: () => mergeAll$1(add("GET", "/auth/sign-in", notConfigured), add("GET", "/auth/sign-out", notConfigured)),
92173
- onSome: layerSignIn
92174
- });
92175
- }));
92176
92090
  const layerAnnounce = effectDiscard(gen(function* () {
92177
92091
  const origin = new URL(yield* String$5("APP_URL")).origin;
92178
92092
  const client = pipe(yield* HttpClient, filterStatusOk, timeout("10 seconds"), retryTransient({
@@ -92302,6 +92216,113 @@ var AiGateway = class AiGateway extends Service$1()("@deslop/runtime/ai/service/
92302
92216
  });
92303
92217
  }));
92304
92218
  };
92219
+ // ../../packages/runtime/src/auth/routes.ts
92220
+ const SIGN_IN_COOKIE = "__Host-sign-in";
92221
+ const SignInState = fromJsonString(Struct({
92222
+ next: String$6,
92223
+ state: String$6,
92224
+ verifier: String$6
92225
+ }));
92226
+ const CallbackParams$1 = Struct({
92227
+ code: optionalKey(String$6),
92228
+ error: optionalKey(String$6),
92229
+ iss: optionalKey(String$6),
92230
+ state: optionalKey(String$6)
92231
+ });
92232
+ function signedOut(next, cause) {
92233
+ return as(logWarning("The sign-in did not complete", cause), expireCookieUnsafe(redirect(next), SIGN_IN_COOKIE, COOKIE));
92234
+ }
92235
+ function layerSignIn(issuer) {
92236
+ return use((router) => gen(function* () {
92237
+ const sessions = yield* Sessions;
92238
+ const random = yield* SecureRandom;
92239
+ const digest = yield* Digest;
92240
+ const canonical = new URL(yield* String$5("APP_URL")).origin;
92241
+ const callback = new URL(CALLBACK_PATH, canonical).href;
92242
+ const clientId = yield* cached(map$5(appName, (name) => clientIdOf({
92243
+ name: capitalize(name),
92244
+ redirects: [callback]
92245
+ })));
92246
+ function ended(headers) {
92247
+ return match$8(sessionIdOf(headers), {
92248
+ onNone: () => void_$1,
92249
+ onSome: (id) => ignore$1(sessions.end(id), {
92250
+ log: "Warn",
92251
+ message: "The session could not be ended"
92252
+ })
92253
+ });
92254
+ }
92255
+ function toNext(handle) {
92256
+ return flatMap$2(HttpServerRequest, (request) => match$8(filter$8(liftThrowable(() => new URL(new URL(request.url, canonical).searchParams.get("next") ?? canonical, canonical))(), (next) => next.origin === canonical), {
92257
+ onNone: () => succeed$5(empty({ status: 400 })),
92258
+ onSome: (next) => handle(request, next)
92259
+ }));
92260
+ }
92261
+ yield* router.add("GET", "/auth/sign-in", toNext(fnUntraced(function* (_, next) {
92262
+ const verifier = encode$3(yield* random.randomBytes(32));
92263
+ const state = encode$3(yield* random.randomBytes(16));
92264
+ const authorize = new URL(AUTHORIZE_PATH, issuer);
92265
+ authorize.search = `${new URLSearchParams({
92266
+ client_id: yield* clientId,
92267
+ code_challenge: encode$3(yield* digest.digest(sha256, new TextEncoder().encode(verifier))),
92268
+ code_challenge_method: "S256",
92269
+ redirect_uri: callback,
92270
+ response_type: "code",
92271
+ scope: "deslop offline_access",
92272
+ state
92273
+ })}`;
92274
+ return setCookieUnsafe(redirect(authorize.href), SIGN_IN_COOKIE, yield* encodeEffect(SignInState)({
92275
+ next: next.href,
92276
+ state,
92277
+ verifier
92278
+ }), {
92279
+ ...COOKIE,
92280
+ maxAge: "10 minutes"
92281
+ });
92282
+ })));
92283
+ yield* router.add("GET", CALLBACK_PATH, gen(function* () {
92284
+ const request = yield* HttpServerRequest;
92285
+ return yield* match$8(yield* option$1(decodeUnknownEffect(SignInState)(request.cookies[SIGN_IN_COOKIE])), {
92286
+ onNone: () => signedOut(canonical, "The sign-in expired or began in another browser"),
92287
+ onSome: fnUntraced(function* (saved) {
92288
+ const started = yield* result$1(gen(function* () {
92289
+ const params = yield* schemaSearchParams(CallbackParams$1);
92290
+ if (params.state !== saved.state) return yield* AuthError.make({ message: "The sign-in began in another browser" });
92291
+ if (params.error !== void 0 || params.code === void 0) return yield* AuthError.make({ message: `Auth answered ${params.error ?? "without a code"}` });
92292
+ if (params.iss !== new URL("/api/auth", issuer).href) return yield* AuthError.make({ message: "The answer came from another issuer" });
92293
+ return yield* sessions.start({
92294
+ client_id: yield* clientId,
92295
+ code: params.code,
92296
+ code_verifier: saved.verifier,
92297
+ redirect_uri: callback
92298
+ });
92299
+ }));
92300
+ if (isFailure$1(started)) return yield* signedOut(saved.next, started.failure);
92301
+ return pipe(redirect(saved.next), expireCookieUnsafe(SIGN_IN_COOKIE, COOKIE), setCookieUnsafe(SESSION_COOKIE, started.success, {
92302
+ ...COOKIE,
92303
+ maxAge: "365 days"
92304
+ }));
92305
+ })
92306
+ });
92307
+ }));
92308
+ yield* router.add("POST", "/auth/session", gen(function* () {
92309
+ const started = yield* result$1(pipe(schemaBodyJson(CodeGrant), rejected("The sign-in request is invalid"), flatMap$2(sessions.start)));
92310
+ if (isFailure$1(started)) return text(started.failure.message, failureOptions(started.failure, 400));
92311
+ return yield* schemaJson(SessionHandle)({ session: started.success }, { headers: { "cache-control": "no-store" } });
92312
+ }));
92313
+ yield* router.add("GET", "/auth/sign-out", toNext((request, next) => as(ended(request.headers), expireCookieUnsafe(redirect(`${new URL("/", issuer).href}?${new URLSearchParams({
92314
+ next: next.href,
92315
+ "sign-out": ""
92316
+ })}`), SESSION_COOKIE, COOKIE))));
92317
+ yield* router.add("POST", "/auth/sign-out", as(flatMap$2(HttpServerRequest, (request) => ended(request.headers)), empty({ status: 204 })));
92318
+ }));
92319
+ }
92320
+ const layerSessionRoutes = unwrap$7(gen(function* () {
92321
+ return match$8(yield* option(String$5("AUTH_URL")), {
92322
+ onNone: () => empty$11,
92323
+ onSome: layerSignIn
92324
+ });
92325
+ }));
92305
92326
  // ../../packages/runtime/src/cli/schema.ts
92306
92327
  var AppError = class extends TaggedError()("AppError", {
92307
92328
  cause: optional$8(Defect()),
@@ -92677,10 +92698,10 @@ const SessionVia = Literals([
92677
92698
  "GitHub",
92678
92699
  "Passkey"
92679
92700
  ]);
92701
+ const StoredOrigin = Struct({ address: optionalKey(String$6) });
92680
92702
  const Grants = Record$1(String$6, Struct({
92681
92703
  ...CredentialOwner.fields,
92682
92704
  client: String$6,
92683
- createdAt: Finite,
92684
92705
  credential: TaggedUnion({
92685
92706
  App: {
92686
92707
  clientId: NonEmptyString,
@@ -92697,21 +92718,18 @@ const Grants = Record$1(String$6, Struct({
92697
92718
  }),
92698
92719
  device: String$6,
92699
92720
  lastActive: Finite,
92700
- origin: Origin,
92721
+ origin: StoredOrigin,
92701
92722
  parent: optionalKey(NonEmptyString)
92702
92723
  }));
92703
92724
  const SignedInApp = Struct({
92704
92725
  address: optionalKey(String$6),
92705
92726
  client: String$6,
92706
- createdAt: Finite,
92707
92727
  device: String$6,
92708
- expiresAt: Finite,
92709
92728
  family: NonEmptyString,
92710
92729
  kind: Literals(["App", "Browser"]),
92711
92730
  lastActive: Finite,
92712
92731
  parent: optionalKey(NonEmptyString)
92713
92732
  });
92714
- Struct({ family: NonEmptyString });
92715
92733
  const RevokeParams = Struct({
92716
92734
  client_id: NonEmptyString,
92717
92735
  token: NonEmptyString
@@ -92753,7 +92771,195 @@ const AdmitParams = Struct({
92753
92771
  allow: Boolean$5,
92754
92772
  id: NonEmptyString
92755
92773
  });
92756
- Struct({ id: NonEmptyString });
92774
+ // src/services/tokens/lib/utils.ts
92775
+ const WORKERS = {
92776
+ "77.237.236.132": "dev",
92777
+ "100.68.201.107": "dev",
92778
+ "100.97.120.3": "desktop",
92779
+ "100.115.207.60": "macbook-pro"
92780
+ };
92781
+ function browserToken(headers) {
92782
+ return parseHeader(headers["cookie"] ?? "")["__Host-session"] ?? "";
92783
+ }
92784
+ function sameOwner(left, right) {
92785
+ return left.user.id === right.user.id && left.incarnation === right.incarnation;
92786
+ }
92787
+ function storedOrigin(origin) {
92788
+ return match$8(fromUndefinedOr(origin.address), {
92789
+ onNone: () => ({}),
92790
+ onSome: (address) => ({ address })
92791
+ });
92792
+ }
92793
+ function randomTokenOf(random) {
92794
+ return (bytes) => map$5(random.randomBytes(bytes), encode$3);
92795
+ }
92796
+ function hashOf(digest) {
92797
+ return (value) => map$5(digest.digest(sha256, new TextEncoder().encode(value)), encode$3);
92798
+ }
92799
+ function live$1(grants, now) {
92800
+ const current = filter$7(grants, (grant) => grant.credential.expiresAt > now);
92801
+ return filter$7(current, (grant) => grant.parent === void 0 || exists(get$13(current, grant.parent), (parent) => parent.credential._tag === "Browser"));
92802
+ }
92803
+ function signedInApps(grants, now, owner) {
92804
+ return pipe(toEntries(live$1(grants, now)), filter$6((entry) => sameOwner(entry[1], owner)), map$8((entry) => ({
92805
+ client: entry[1].client,
92806
+ device: entry[1].device,
92807
+ family: entry[0],
92808
+ kind: entry[1].credential._tag,
92809
+ lastActive: entry[1].lastActive,
92810
+ ...pick(entry[1], ["parent"]),
92811
+ ...match$8(fromUndefinedOr(entry[1].origin.address), {
92812
+ onNone: () => ({}),
92813
+ onSome: (address) => ({ address })
92814
+ })
92815
+ })), sort(flip$1(mapInput(Number$6, (app) => app.lastActive))));
92816
+ }
92817
+ function withChildActivity(signIns) {
92818
+ const children = groupBy(filter$6(signIns, (signIn) => signIn.parent !== void 0), (signIn) => signIn.parent ?? "");
92819
+ return map$8(filter$6(signIns, (signIn) => signIn.parent === void 0), (signIn) => {
92820
+ const latest = reduce(getOrElse(get$13(children, signIn.family), () => []), signIn, max$2(mapInput(Number$6, (app) => app.lastActive)));
92821
+ return {
92822
+ ...omit(signIn, ["address"]),
92823
+ lastActive: latest.lastActive,
92824
+ ...pick(latest, ["address"])
92825
+ };
92826
+ });
92827
+ }
92828
+ function parsedAddress(address) {
92829
+ return pipe(getSuccess(ipFromString(address)), map$11((ip) => {
92830
+ if (isIpv6Address(ip)) return getOrElse(fromIpv4Mapped(ip), () => ip);
92831
+ return ip;
92832
+ }));
92833
+ }
92834
+ function isPrivateOrUniqueLocal(ip) {
92835
+ if (isIpv4Address(ip)) return isPrivate(ip);
92836
+ return isUniqueLocal(ip);
92837
+ }
92838
+ function addressGroup(address) {
92839
+ return match$8(parsedAddress(address), {
92840
+ onNone: () => address,
92841
+ onSome: (ip) => {
92842
+ if (isIpv4Address(ip)) return formatIp(ip);
92843
+ return join$2(map$8(take$3(ipv6ToSegments(ip), 4), (segment) => segment.toString(16)), ":");
92844
+ }
92845
+ });
92846
+ }
92847
+ function clientAddress(headers, remote) {
92848
+ return pipe(get$6(headers, "x-forwarded-for"), flatMap$7((forwarded) => last(split$2(",")(forwarded))), map$11(trim), filter$8(isNonEmpty$1), orElse$3(() => remote));
92849
+ }
92850
+ function originFrom(headers, remote) {
92851
+ return {
92852
+ ...match$8(clientAddress(headers, remote), {
92853
+ onNone: () => ({}),
92854
+ onSome: (address) => ({ address })
92855
+ }),
92856
+ ...match$8(get$6(headers, "user-agent"), {
92857
+ onNone: () => ({}),
92858
+ onSome: (agent) => ({ userAgent: slice$1(0, 200)(agent) })
92859
+ })
92860
+ };
92861
+ }
92862
+ function clientLabel(name) {
92863
+ return pipe(name, replace(/\s*\([^)]*\)$/u, ""), trim, capitalize, liftPredicate(isNonEmpty$1), getOrElse(() => "Unknown client"));
92864
+ }
92865
+ function platform(userAgent) {
92866
+ if (includes("iPhone")(userAgent)) return some$1("iPhone");
92867
+ if (includes("iPad")(userAgent)) return some$1("iPad");
92868
+ if (includes("CFNetwork/")(userAgent)) return some$1("iPhone");
92869
+ if (includes("Android")(userAgent)) return some$1("Android");
92870
+ if (includes("Macintosh")(userAgent)) return some$1("Mac");
92871
+ if (includes("Windows")(userAgent)) return some$1("Windows");
92872
+ if (includes("Linux")(userAgent)) return some$1("Linux");
92873
+ return none();
92874
+ }
92875
+ function browserLabel(origin) {
92876
+ const agent = origin.userAgent ?? "";
92877
+ if (includes("Edg/")(agent)) return "Edge";
92878
+ if (includes("Firefox/")(agent)) return "Firefox";
92879
+ if (includes("Chrome/")(agent)) return "Chrome";
92880
+ if (includes("Safari/")(agent)) return "Safari";
92881
+ return "Browser";
92882
+ }
92883
+ function deviceLabel(origin) {
92884
+ return pipe(flatMap$7(fromUndefinedOr(origin.address), (address) => {
92885
+ if (exists(parsedAddress(address), (ip) => isLinkLocal(ip) || isLoopback(ip) || isPrivateOrUniqueLocal(ip))) return some$1("dev");
92886
+ return get$13(WORKERS, address);
92887
+ }), orElse$3(() => flatMap$7(fromUndefinedOr(origin.userAgent), platform)), getOrElse(() => origin.address ?? "unknown"));
92888
+ }
92889
+ function loopback(redirect) {
92890
+ return filter$8(getSuccess(fromString(redirect)), (target) => target.protocol === "http:" && contains([
92891
+ "127.0.0.1",
92892
+ "[::1]",
92893
+ "localhost"
92894
+ ], target.hostname) && isEmpty$1(target.username) && isEmpty$1(target.password) && isEmpty$1(target.search) && isEmpty$1(target.hash));
92895
+ }
92896
+ function webRedirect(redirect) {
92897
+ return isSome(match$3(/^https:\/\/[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?\.mp281x\.xyz\/auth\/callback$/u)(redirect));
92898
+ }
92899
+ function allowedRedirect(redirect) {
92900
+ return webRedirect(redirect) || isSome(match$3(/^https:\/\/gateway\.mp281x\.xyz\/oauth\/callback\/[a-z0-9][a-z0-9_-]{0,23}$/u)(redirect)) || contains([
92901
+ "stash://auth/callback",
92902
+ "stash-dev://auth/callback",
92903
+ "opm://auth/callback",
92904
+ "opm-dev://auth/callback",
92905
+ "trips://auth/callback",
92906
+ "trips-dev://auth/callback"
92907
+ ], redirect) || isSome(loopback(redirect));
92908
+ }
92909
+ function clientOf(clientId) {
92910
+ return pipe(decodeString$2(clientId), getSuccess, flatMap$7(decodeUnknownOption(fromJsonString(ClientInfo))), filter$8((client) => every$1(client.redirects, allowedRedirect)));
92911
+ }
92912
+ function portless(redirect) {
92913
+ return map$11(filter$8(match$3(/^(?<origin>http:\/\/(?:127\.0\.0\.1|\[::1\]|localhost))(?::\d{1,5})?(?<rest>\/.*)?$/u)(redirect), () => isSome(loopback(redirect))), (found) => `${found.groups?.["origin"] ?? ""}${found.groups?.["rest"] ?? ""}`);
92914
+ }
92915
+ function matchingRedirect(client, requested) {
92916
+ return match$8(requested, {
92917
+ onNone: () => filter$8(head(client.redirects), () => client.redirects.length === 1),
92918
+ onSome: (asked) => as$2(findFirst(client.redirects, (redirect) => {
92919
+ if (redirect === asked) return true;
92920
+ return isSome(flatMap$7(portless(redirect), (saved) => filter$8(portless(asked), (target) => target === saved)));
92921
+ }), asked)
92922
+ });
92923
+ }
92924
+ function given(value) {
92925
+ return filter$8(fromUndefinedOr(value), isNonEmpty$1);
92926
+ }
92927
+ const clientRequest = fnUntraced(function* (asked, client, params) {
92928
+ if (isNone(given(params.response_type))) return yield* AuthError.make({ message: "Send response_type=code" });
92929
+ if (params.response_type !== "code") return yield* AuthError.make({
92930
+ error: "unsupported_response_type",
92931
+ message: "Only response_type=code is supported"
92932
+ });
92933
+ if (params.code_challenge === void 0 || params.code_challenge_method !== "S256") return yield* AuthError.make({ message: "Send a PKCE code_challenge with code_challenge_method=S256" });
92934
+ if (!every$1(filter$6(split$2(params.scope ?? "", " "), isNonEmpty$1), (scope) => scope === "deslop" || scope === "offline_access")) return yield* AuthError.make({
92935
+ error: "invalid_scope",
92936
+ message: "Only the deslop scope is supported"
92937
+ });
92938
+ return ClientRequest.make({
92939
+ challenge: params.code_challenge,
92940
+ clientId: asked.client_id,
92941
+ clientName: client.clientName,
92942
+ redirectUri: client.redirectUri,
92943
+ ...match$8(given(asked.state), {
92944
+ onNone: () => ({}),
92945
+ onSome: (state) => ({ state })
92946
+ })
92947
+ });
92948
+ });
92949
+ function callbackUrl(request, answer, issuer) {
92950
+ const target = new URL(request.redirectUri);
92951
+ for (const entry of toEntries(answer)) target.searchParams.set(entry[0], entry[1]);
92952
+ map$11(given(request.state), (sent) => target.searchParams.set("state", sent));
92953
+ target.searchParams.set("iss", issuer);
92954
+ return target.href;
92955
+ }
92956
+ function returnable(next, url) {
92957
+ const domain = "mp281x.xyz";
92958
+ return match$6(fromString(next), {
92959
+ onFailure: () => false,
92960
+ onSuccess: (target) => (target.origin === new URL(url).origin || target.protocol === "https:" && (target.hostname === domain || endsWith(`.${domain}`)(target.hostname))) && isEmpty$1(target.username) && isEmpty$1(target.password)
92961
+ });
92962
+ }
92757
92963
  // src/services/github/service.ts
92758
92964
  const HEADERS = {
92759
92965
  accept: "application/vnd.github+json",
@@ -92766,13 +92972,12 @@ const DEVELOPER_PROFILE = GitHubUser.make({
92766
92972
  });
92767
92973
  var GitHub = class GitHub extends Service$1()("@deslop/auth/services/github/service/GitHub") {
92768
92974
  static layer = effect(GitHub, gen(function* () {
92769
- const random = yield* SecureRandom;
92770
92975
  const flows = yield* make$22({
92771
92976
  capacity: 256,
92772
92977
  lookup: () => fail$8(AuthError.make({ message: "The sign-in expired" })),
92773
92978
  timeToLive: "10 minutes"
92774
92979
  });
92775
- const nonce = map$5(random.randomBytes(32), encode$3);
92980
+ const nonce = randomTokenOf(yield* SecureRandom)(32);
92776
92981
  const take = fnUntraced(function* (state) {
92777
92982
  const flow = yield* get$2(flows, state);
92778
92983
  yield* invalidate(flows, state);
@@ -92803,7 +93008,7 @@ var GitHub = class GitHub extends Service$1()("@deslop/auth/services/github/serv
92803
93008
  })
92804
93009
  });
92805
93010
  const client = filterStatusOk(yield* HttpClient);
92806
- const digest = yield* Digest;
93011
+ const hash = hashOf(yield* Digest);
92807
93012
  const provider = yield* all({
92808
93013
  clientId: String$5("GITHUB_CLIENT_ID"),
92809
93014
  secret: Redacted("GITHUB_CLIENT_SECRET")
@@ -92840,7 +93045,7 @@ var GitHub = class GitHub extends Service$1()("@deslop/auth/services/github/serv
92840
93045
  const url = new URL("https://github.com/login/oauth/authorize");
92841
93046
  url.search = toString$1(fromInput({
92842
93047
  client_id: provider.clientId,
92843
- code_challenge: encode$3(yield* digest.digest(sha256, new TextEncoder().encode(verifier))),
93048
+ code_challenge: yield* hash(verifier),
92844
93049
  code_challenge_method: "S256",
92845
93050
  redirect_uri: CALLBACK,
92846
93051
  state
@@ -92946,18 +93151,14 @@ const StoredPasskeys = ArraySchema(Struct({
92946
93151
  ...StoredOwner.fields,
92947
93152
  addedFrom: String$6,
92948
93153
  counter: Int$1,
92949
- createdAt: Finite,
92950
93154
  id: NonEmptyString,
92951
- lastUsed: Finite,
92952
93155
  publicKey: NonEmptyString,
92953
93156
  synced: Boolean$5,
92954
93157
  transports: ArraySchema(Transport)
92955
93158
  }));
92956
93159
  const Passkey = Struct({
92957
93160
  addedFrom: String$6,
92958
- createdAt: Finite,
92959
93161
  id: NonEmptyString,
92960
- lastUsed: Finite,
92961
93162
  synced: Boolean$5
92962
93163
  });
92963
93164
  const PasskeyParams = Struct({ id: NonEmptyString });
@@ -114442,185 +114643,6 @@ async function verifyAuthenticationResponse(options) {
114442
114643
  }
114443
114644
  };
114444
114645
  }
114445
- // src/services/tokens/lib/utils.ts
114446
- const WORKERS = {
114447
- "77.237.236.132": "dev",
114448
- "100.68.201.107": "dev",
114449
- "100.97.120.3": "desktop",
114450
- "100.115.207.60": "macbook-pro"
114451
- };
114452
- function browserToken(headers) {
114453
- return parseHeader(headers["cookie"] ?? "")["__Host-session"] ?? "";
114454
- }
114455
- function sameOwner(left, right) {
114456
- return left.user.id === right.user.id && left.incarnation === right.incarnation;
114457
- }
114458
- function live$1(grants, now) {
114459
- const current = filter$7(grants, (grant) => grant.credential.expiresAt > now);
114460
- return filter$7(current, (grant) => grant.parent === void 0 || exists(get$13(current, grant.parent), (parent) => parent.credential._tag === "Browser"));
114461
- }
114462
- function signedInApps(grants, now, owner) {
114463
- return pipe(toEntries(live$1(grants, now)), filter$6((entry) => sameOwner(entry[1], owner)), map$8((entry) => ({
114464
- client: entry[1].client,
114465
- createdAt: entry[1].createdAt,
114466
- device: entry[1].device,
114467
- expiresAt: entry[1].credential.expiresAt,
114468
- family: entry[0],
114469
- kind: entry[1].credential._tag,
114470
- lastActive: entry[1].lastActive,
114471
- ...pick(entry[1], ["parent"]),
114472
- ...match$8(fromUndefinedOr(entry[1].origin.address), {
114473
- onNone: () => ({}),
114474
- onSome: (address) => ({ address })
114475
- })
114476
- })), sort(flip$1(mapInput(Number$6, (app) => app.lastActive))));
114477
- }
114478
- function withChildActivity(signIns) {
114479
- const children = groupBy(filter$6(signIns, (signIn) => signIn.parent !== void 0), (signIn) => signIn.parent ?? "");
114480
- return map$8(filter$6(signIns, (signIn) => signIn.parent === void 0), (signIn) => {
114481
- const latest = reduce(getOrElse(get$13(children, signIn.family), () => []), signIn, max$2(mapInput(Number$6, (app) => app.lastActive)));
114482
- return {
114483
- ...omit(signIn, ["address"]),
114484
- lastActive: latest.lastActive,
114485
- ...pick(latest, ["address"])
114486
- };
114487
- });
114488
- }
114489
- function parsedAddress(address) {
114490
- return pipe(getSuccess(ipFromString(address)), map$11((ip) => {
114491
- if (isIpv6Address(ip)) return getOrElse(fromIpv4Mapped(ip), () => ip);
114492
- return ip;
114493
- }));
114494
- }
114495
- function isPrivateOrUniqueLocal(ip) {
114496
- if (isIpv4Address(ip)) return isPrivate(ip);
114497
- return isUniqueLocal(ip);
114498
- }
114499
- function addressGroup(address) {
114500
- return match$8(parsedAddress(address), {
114501
- onNone: () => address,
114502
- onSome: (ip) => {
114503
- if (isIpv4Address(ip)) return formatIp(ip);
114504
- return join$2(map$8(take$3(ipv6ToSegments(ip), 4), (segment) => segment.toString(16)), ":");
114505
- }
114506
- });
114507
- }
114508
- function clientAddress(headers, remote) {
114509
- return pipe(get$6(headers, "x-forwarded-for"), flatMap$7((forwarded) => last(split$2(",")(forwarded))), map$11(trim), filter$8(isNonEmpty$1), orElse$3(() => remote));
114510
- }
114511
- function originFrom(headers, remote) {
114512
- return {
114513
- ...match$8(clientAddress(headers, remote), {
114514
- onNone: () => ({}),
114515
- onSome: (address) => ({ address })
114516
- }),
114517
- ...match$8(get$6(headers, "user-agent"), {
114518
- onNone: () => ({}),
114519
- onSome: (agent) => ({ userAgent: slice$1(0, 200)(agent) })
114520
- })
114521
- };
114522
- }
114523
- function clientLabel(name) {
114524
- return pipe(name, replace(/\s*\([^)]*\)$/u, ""), trim, capitalize, liftPredicate(isNonEmpty$1), getOrElse(() => "Unknown client"));
114525
- }
114526
- function platform(userAgent) {
114527
- if (includes("iPhone")(userAgent)) return some$1("iPhone");
114528
- if (includes("iPad")(userAgent)) return some$1("iPad");
114529
- if (includes("CFNetwork/")(userAgent)) return some$1("iPhone");
114530
- if (includes("Android")(userAgent)) return some$1("Android");
114531
- if (includes("Macintosh")(userAgent)) return some$1("Mac");
114532
- if (includes("Windows")(userAgent)) return some$1("Windows");
114533
- if (includes("Linux")(userAgent)) return some$1("Linux");
114534
- return none();
114535
- }
114536
- function browserLabel(origin) {
114537
- const agent = origin.userAgent ?? "";
114538
- if (includes("Edg/")(agent)) return "Edge";
114539
- if (includes("Firefox/")(agent)) return "Firefox";
114540
- if (includes("Chrome/")(agent)) return "Chrome";
114541
- if (includes("Safari/")(agent)) return "Safari";
114542
- return "Browser";
114543
- }
114544
- function deviceLabel(origin) {
114545
- return pipe(flatMap$7(fromUndefinedOr(origin.address), (address) => {
114546
- if (exists(parsedAddress(address), (ip) => isLinkLocal(ip) || isLoopback(ip) || isPrivateOrUniqueLocal(ip))) return some$1("dev");
114547
- return get$13(WORKERS, address);
114548
- }), orElse$3(() => flatMap$7(fromUndefinedOr(origin.userAgent), platform)), getOrElse(() => origin.address ?? "unknown"));
114549
- }
114550
- function loopback(redirect) {
114551
- return filter$8(getSuccess(fromString(redirect)), (target) => target.protocol === "http:" && contains([
114552
- "127.0.0.1",
114553
- "[::1]",
114554
- "localhost"
114555
- ], target.hostname) && isEmpty$1(target.username) && isEmpty$1(target.password) && isEmpty$1(target.search) && isEmpty$1(target.hash));
114556
- }
114557
- function webRedirect(redirect) {
114558
- return isSome(match$3(/^https:\/\/[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?\.mp281x\.xyz\/auth\/callback$/u)(redirect));
114559
- }
114560
- function allowedRedirect(redirect) {
114561
- return webRedirect(redirect) || isSome(match$3(/^https:\/\/gateway\.mp281x\.xyz\/oauth\/callback\/[a-z0-9][a-z0-9_-]{0,23}$/u)(redirect)) || contains([
114562
- "stash://auth/callback",
114563
- "stash-dev://auth/callback",
114564
- "opm://auth/callback",
114565
- "opm-dev://auth/callback",
114566
- "trips://auth/callback",
114567
- "trips-dev://auth/callback"
114568
- ], redirect) || isSome(loopback(redirect));
114569
- }
114570
- function clientOf(clientId) {
114571
- return pipe(decodeString$2(clientId), getSuccess, flatMap$7(decodeUnknownOption(fromJsonString(ClientInfo))), filter$8((client) => every$1(client.redirects, allowedRedirect)));
114572
- }
114573
- function portless(redirect) {
114574
- return map$11(filter$8(match$3(/^(?<origin>http:\/\/(?:127\.0\.0\.1|\[::1\]|localhost))(?::\d{1,5})?(?<rest>\/.*)?$/u)(redirect), () => isSome(loopback(redirect))), (found) => `${found.groups?.["origin"] ?? ""}${found.groups?.["rest"] ?? ""}`);
114575
- }
114576
- function matchingRedirect(client, requested) {
114577
- return match$8(requested, {
114578
- onNone: () => filter$8(head(client.redirects), () => client.redirects.length === 1),
114579
- onSome: (asked) => as$2(findFirst(client.redirects, (redirect) => {
114580
- if (redirect === asked) return true;
114581
- return isSome(flatMap$7(portless(redirect), (saved) => filter$8(portless(asked), (target) => target === saved)));
114582
- }), asked)
114583
- });
114584
- }
114585
- function given(value) {
114586
- return filter$8(fromUndefinedOr(value), isNonEmpty$1);
114587
- }
114588
- const clientRequest = fnUntraced(function* (asked, client, params) {
114589
- if (isNone(given(params.response_type))) return yield* AuthError.make({ message: "Send response_type=code" });
114590
- if (params.response_type !== "code") return yield* AuthError.make({
114591
- error: "unsupported_response_type",
114592
- message: "Only response_type=code is supported"
114593
- });
114594
- if (params.code_challenge === void 0 || params.code_challenge_method !== "S256") return yield* AuthError.make({ message: "Send a PKCE code_challenge with code_challenge_method=S256" });
114595
- if (!every$1(filter$6(split$2(params.scope ?? "", " "), isNonEmpty$1), (scope) => scope === "deslop" || scope === "offline_access")) return yield* AuthError.make({
114596
- error: "invalid_scope",
114597
- message: "Only the deslop scope is supported"
114598
- });
114599
- return ClientRequest.make({
114600
- challenge: params.code_challenge,
114601
- clientId: asked.client_id,
114602
- clientName: client.clientName,
114603
- redirectUri: client.redirectUri,
114604
- ...match$8(given(asked.state), {
114605
- onNone: () => ({}),
114606
- onSome: (state) => ({ state })
114607
- })
114608
- });
114609
- });
114610
- function callbackUrl(request, answer, issuer) {
114611
- const target = new URL(request.redirectUri);
114612
- for (const entry of toEntries(answer)) target.searchParams.set(entry[0], entry[1]);
114613
- map$11(given(request.state), (sent) => target.searchParams.set("state", sent));
114614
- target.searchParams.set("iss", issuer);
114615
- return target.href;
114616
- }
114617
- function returnable(next, url) {
114618
- const domain = "mp281x.xyz";
114619
- return match$6(fromString(next), {
114620
- onFailure: () => false,
114621
- onSuccess: (target) => (target.origin === new URL(url).origin || target.protocol === "https:" && (target.hostname === domain || endsWith(`.${domain}`)(target.hostname))) && isEmpty$1(target.username) && isEmpty$1(target.password)
114622
- });
114623
- }
114624
114646
  // src/services/passkeys/service.ts
114625
114647
  const LIFETIME = 3e5;
114626
114648
  function invalid(cause) {
@@ -114693,9 +114715,7 @@ var Passkeys = class Passkeys extends Service$1()("@deslop/auth/services/passkey
114693
114715
  return [...current, {
114694
114716
  addedFrom: `${browserLabel(from)} · ${deviceLabel(from)}`,
114695
114717
  counter: credential.counter,
114696
- createdAt: now,
114697
114718
  id: credential.id,
114698
- lastUsed: now,
114699
114719
  publicKey: encode$3(credential.publicKey),
114700
114720
  synced: verified.registrationInfo.credentialDeviceType === "multiDevice",
114701
114721
  transports,
@@ -114709,9 +114729,7 @@ var Passkeys = class Passkeys extends Service$1()("@deslop/auth/services/passkey
114709
114729
  }, rejected("Cannot remove the account’s passkeys")),
114710
114730
  list: (owner) => map$3(changes(state), (current) => map$8(filter$6(current, (found) => sameOwner(found, owner)), (found) => ({
114711
114731
  addedFrom: found.addedFrom,
114712
- createdAt: found.createdAt,
114713
114732
  id: found.id,
114714
- lastUsed: found.lastUsed,
114715
114733
  synced: found.synced
114716
114734
  }))),
114717
114735
  registration: fn("Passkeys.registration")(function* (owner, via) {
@@ -114781,8 +114799,7 @@ var Passkeys = class Passkeys extends Service$1()("@deslop/auth/services/passkey
114781
114799
  if (stored.id !== found.id) return stored;
114782
114800
  return {
114783
114801
  ...stored,
114784
- counter: max(stored.counter, verified.authenticationInfo.newCounter),
114785
- lastUsed: now
114802
+ counter: max(stored.counter, verified.authenticationInfo.newCounter)
114786
114803
  };
114787
114804
  })));
114788
114805
  return {
@@ -114798,7 +114815,6 @@ const SignInKind = Literals(["App", "Browser"]);
114798
114815
  const PendingAuthorization = Struct({
114799
114816
  address: optionalKey(String$6),
114800
114817
  clientName: String$6,
114801
- createdAt: Finite,
114802
114818
  device: String$6,
114803
114819
  expiresAt: Finite,
114804
114820
  id: NonEmptyString,
@@ -114886,9 +114902,9 @@ var RpcContracts = class extends make$31(make$35("auth.lookup", {
114886
114902
  }))) {};
114887
114903
  // src/services/people/lib/utils.ts
114888
114904
  const ROLE_ORDER = {
114889
- Admin: 0,
114905
+ Admin: 1,
114890
114906
  Member: 2,
114891
- Waiting: 1
114907
+ Waiting: 0
114892
114908
  };
114893
114909
  function ownerOf(row) {
114894
114910
  return {
@@ -114992,6 +115008,21 @@ function parts(token) {
114992
115008
  function end(grants, family) {
114993
115009
  return filter$7(grants, (grant, key) => key !== family && grant.parent !== family);
114994
115010
  }
115011
+ function touch(current, family, now) {
115012
+ return match$8(get$13(current, family), {
115013
+ onNone: () => current,
115014
+ onSome: (grant) => match$1(now - grant.lastActive > 6e4, {
115015
+ onFalse: () => current,
115016
+ onTrue: () => ({
115017
+ ...current,
115018
+ [family]: {
115019
+ ...grant,
115020
+ lastActive: now
115021
+ }
115022
+ })
115023
+ })
115024
+ });
115025
+ }
114995
115026
  var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/service/Tokens") {
114996
115027
  static layer = effect(Tokens, gen(function* () {
114997
115028
  const storage = yield* KeyValueStore;
@@ -115015,14 +115046,8 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115015
115046
  const signature = yield* Signature;
115016
115047
  const codes = yield* make$58(empty$4());
115017
115048
  const redeeming = yield* make$71(1);
115018
- const random = yield* SecureRandom;
115019
- const digest = yield* Digest;
115020
- function secret(bytes) {
115021
- return map$5(random.randomBytes(bytes), encode$3);
115022
- }
115023
- const hash = fnUntraced(function* (value) {
115024
- return encode$3(yield* digest.digest(sha256, new TextEncoder().encode(value)));
115025
- });
115049
+ const randomToken = randomTokenOf(yield* SecureRandom);
115050
+ const hash = hashOf(yield* Digest);
115026
115051
  const change = fnUntraced(function* (update) {
115027
115052
  return yield* modifyEffect(grants, (current) => gen(function* () {
115028
115053
  const now = yield* currentTimeMillis;
@@ -115073,19 +115098,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115073
115098
  grant: signedIn,
115074
115099
  now
115075
115100
  };
115076
- if (found.now - found.grant.lastActive > 6e4) yield* pipe(change((current) => succeed$5([void 0, match$8(get$13(current, found.family), {
115077
- onNone: () => current,
115078
- onSome: (grant) => match$1(found.now - grant.lastActive > 6e4, {
115079
- onFalse: () => current,
115080
- onTrue: () => ({
115081
- ...current,
115082
- [found.family]: {
115083
- ...grant,
115084
- lastActive: found.now
115085
- }
115086
- })
115087
- })
115088
- })])), ignore$1({
115101
+ if (found.now - found.grant.lastActive > 6e4) yield* pipe(change((current) => succeed$5([void 0, touch(current, found.family, found.now)])), ignore$1({
115089
115102
  log: "Warn",
115090
115103
  message: "The token’s last use could not be saved"
115091
115104
  }));
@@ -115095,7 +115108,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115095
115108
  };
115096
115109
  }, rejected("Sign in first"));
115097
115110
  const mint = fnUntraced(function* (family, generation, owner, client, now) {
115098
- const refreshSecret = yield* secret(32);
115111
+ const refreshSecret = yield* randomToken(32);
115099
115112
  const iat = Math.floor(now / 1e3);
115100
115113
  const access = yield* provideService(sign(AccessClaims, {
115101
115114
  aud: "deslop",
@@ -115128,7 +115141,6 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115128
115141
  const minted = yield* pipe(mint(family, 0, owner, clientLabel(request.clientName), now), rejected("Cannot sign the access token"));
115129
115142
  const grant = {
115130
115143
  client: clientLabel(request.clientName),
115131
- createdAt: now,
115132
115144
  credential: {
115133
115145
  _tag: "App",
115134
115146
  clientId: request.clientId,
@@ -115138,7 +115150,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115138
115150
  },
115139
115151
  device: deviceLabel(origin),
115140
115152
  lastActive: now,
115141
- origin,
115153
+ origin: storedOrigin(origin),
115142
115154
  ...pick(request, ["parent"]),
115143
115155
  ...owner
115144
115156
  };
@@ -115151,7 +115163,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115151
115163
  const redeem = fnUntraced(function* (params, origin, allowed) {
115152
115164
  const key = yield* hash(params.code);
115153
115165
  const verifier = yield* hash(params.code_verifier);
115154
- const family = yield* secret(16);
115166
+ const family = yield* randomToken(16);
115155
115167
  const result = yield* change((current, now) => gen(function* () {
115156
115168
  const code = yield* pipe(get$4(yield* get$7(codes), key), filter$8((entry) => entry.expiresAt > now), fromOption, mapError$2(() => expired$1));
115157
115169
  if (code.state._tag === "Used") return [Exchange.cases.Replayed.make({ message: "This authorization code was already used, so the tokens it gave are revoked; sign in again" }), remove$6(current, code.state.family)];
@@ -115200,7 +115212,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115200
115212
  },
115201
115213
  device: deviceLabel(origin),
115202
115214
  lastActive: now,
115203
- origin
115215
+ origin: storedOrigin(origin)
115204
115216
  }
115205
115217
  }];
115206
115218
  }));
@@ -115228,7 +115240,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115228
115240
  };
115229
115241
  }),
115230
115242
  device: fn("Tokens.device")(function* (request, owner, origin) {
115231
- const family = yield* secret(16);
115243
+ const family = yield* randomToken(16);
115232
115244
  return yield* change((current, now) => signIn(current, now, family, request, owner, origin));
115233
115245
  }, rejected("Cannot sign the command in")),
115234
115246
  disconnect: fn("Tokens.disconnect")(function* (family, owner) {
@@ -115252,7 +115264,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115252
115264
  yield* update$3(codes, filter((entry) => entry.state._tag === "Used" || !sameOwner(entry.state.owner, owner)));
115253
115265
  }, rejected("Cannot sign this account out")),
115254
115266
  issue: fn("Tokens.issue")(function* (request, owner) {
115255
- const code = yield* secret(32);
115267
+ const code = yield* randomToken(32);
115256
115268
  const key = yield* hash(code);
115257
115269
  const now = yield* currentTimeMillis;
115258
115270
  yield* update$3(codes, (current) => set$1(filter(current, (entry) => entry.expiresAt > now), key, {
@@ -115282,8 +115294,8 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115282
115294
  session,
115283
115295
  sessionVia,
115284
115296
  startSession: fn("Tokens.startSession")(function* (owner, origin, via, previousToken) {
115285
- const family = yield* secret(16);
115286
- const sessionSecret = yield* secret(32);
115297
+ const family = yield* randomToken(16);
115298
+ const sessionSecret = yield* randomToken(32);
115287
115299
  const seconds = pipe(value(via), when("Code", () => 2592e3), when("GitHub", () => 31536e3), when("Passkey", () => 31536e3), exhaustive);
115288
115300
  const sessionHash = yield* hash(sessionSecret);
115289
115301
  const previous = yield* transposeOption(map$11(parts(previousToken), (prior) => map$5(hash(prior.secret), (presented) => ({
@@ -115302,7 +115314,6 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115302
115314
  ...retained,
115303
115315
  [family]: {
115304
115316
  client: browserLabel(origin),
115305
- createdAt: now,
115306
115317
  credential: {
115307
115318
  _tag: "Browser",
115308
115319
  expiresAt: now + seconds * 1e3,
@@ -115311,7 +115322,7 @@ var Tokens = class Tokens extends Service$1()("@deslop/auth/services/tokens/serv
115311
115322
  },
115312
115323
  device: deviceLabel(origin),
115313
115324
  lastActive: now,
115314
- origin,
115325
+ origin: storedOrigin(origin),
115315
115326
  ...owner
115316
115327
  }
115317
115328
  }]);
@@ -115337,8 +115348,8 @@ var People = class People extends Service$1()("@deslop/auth/services/people/serv
115337
115348
  const passkeys = yield* Passkeys;
115338
115349
  const github = yield* GitHub;
115339
115350
  const admins = yield* adminIds;
115340
- const random = yield* SecureRandom;
115341
115351
  const local = yield* localAuth;
115352
+ const randomToken = randomTokenOf(yield* SecureRandom);
115342
115353
  const developer = {
115343
115354
  incarnation: "local",
115344
115355
  user: DEVELOPER
@@ -115439,7 +115450,7 @@ var People = class People extends Service$1()("@deslop/auth/services/people/serv
115439
115450
  return registerMember(current, admins, profile, since, yield* match$8(member(`github:${profile.id}`, current), {
115440
115451
  onNone: () => {
115441
115452
  if (local && profile.id === 0) return succeed$5("local");
115442
- return map$5(random.randomBytes(32), encode$3);
115453
+ return randomToken(32);
115443
115454
  },
115444
115455
  onSome: (row) => succeed$5(row.incarnation)
115445
115456
  }));
@@ -115476,6 +115487,7 @@ const layerIssuerAuth = effectContext(gen(function* () {
115476
115487
  }));
115477
115488
  // src/services/sign-ins/lib/utils.ts
115478
115489
  const CODE_LETTERS = "BCDFGHJKLMNPQRSTVWXZ";
115490
+ const SIGN_IN_LIFETIME = minutes(10);
115479
115491
  function typedCode(text) {
115480
115492
  return toUpperCase(replaceAll(/[^a-z]/giu, "")(text));
115481
115493
  }
@@ -122744,7 +122756,7 @@ const start = start$1;
122744
122756
  // src/services/sign-ins/service.ts
122745
122757
  const REQUEST_COOKIE = "__Host-request-";
122746
122758
  const expired = AuthError.make({ message: "This sign-in expired. Start it again in the app." });
122747
- const notWaiting = AuthError.make({ message: "No waiting sign-in has this code: it is mistyped, already answered or expired after 10 minutes. Read the code again from the page or command that is still waiting; start a new sign-in only if none is." });
122759
+ const notWaiting = AuthError.make({ message: `No waiting sign-in has this code: it is mistyped, already answered or expired after ${toMinutes(SIGN_IN_LIFETIME)} minutes. Read the code again from the page or command that is still waiting; start a new sign-in only if none is.` });
122748
122760
  const deliver = fnUntraced(function* (input) {
122749
122761
  const tokens = yield* Tokens;
122750
122762
  const people = yield* People;
@@ -122805,7 +122817,7 @@ const SignIn = make({
122805
122817
  }),
122806
122818
  input: SignInInput,
122807
122819
  root: SignInStates,
122808
- timers: { lifetime: "10 minutes" }
122820
+ timers: { lifetime: SIGN_IN_LIFETIME }
122809
122821
  }).handle({
122810
122822
  initial: {
122811
122823
  data: (transition) => transition.input,
@@ -122876,13 +122888,11 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
122876
122888
  const tokens = yield* Tokens;
122877
122889
  const people = yield* People;
122878
122890
  const random = yield* SecureRandom;
122879
- const digest = yield* Digest;
122891
+ const randomToken = randomTokenOf(random);
122892
+ const hash = hashOf(yield* Digest);
122880
122893
  const scope$2 = yield* scope;
122881
122894
  const open = yield* make$18(empty$4());
122882
122895
  const answering = yield* make$71(1);
122883
- const hash = fnUntraced(function* (value) {
122884
- return encode$3(yield* digest.digest(sha256, new TextEncoder().encode(value)));
122885
- });
122886
122896
  function find(code) {
122887
122897
  return map$5(get(open), get$4(typedCode(code)));
122888
122898
  }
@@ -122963,7 +122973,7 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
122963
122973
  start: fn("SignIns.start")(function* (delivery, origin) {
122964
122974
  const code = codeFrom(yield* random.randomBytes(8));
122965
122975
  const now = yield* currentTimeMillis;
122966
- const receiver = encode$3(yield* random.randomBytes(32));
122976
+ const receiver = yield* randomToken(32);
122967
122977
  const owned = yield* fork(scope$2);
122968
122978
  const ref = yield* pipe(run({
122969
122979
  delivery,
@@ -122992,8 +123002,7 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
122992
123002
  kind: "App"
122993
123003
  })
122994
123004
  }),
122995
- createdAt: now,
122996
- expiresAt: now + 6e5,
123005
+ expiresAt: now + toMillis(SIGN_IN_LIFETIME),
122997
123006
  id: code
122998
123007
  }),
122999
123008
  receiver: yield* hash(receiver),
@@ -123032,12 +123041,6 @@ var SignIns = class SignIns extends Service$1()("@deslop/auth/services/sign-ins/
123032
123041
  }));
123033
123042
  };
123034
123043
  // src/http/handlers.ts
123035
- const COOKIE = {
123036
- httpOnly: true,
123037
- path: "/",
123038
- sameSite: "lax",
123039
- secure: true
123040
- };
123041
123044
  const LOGIN_COOKIE = "__Host-login";
123042
123045
  function session(seconds) {
123043
123046
  return {
@@ -123199,7 +123202,7 @@ const HttpHandlers = use((router) => gen(function* () {
123199
123202
  }, originOf(request));
123200
123203
  return jsonUnsafe({
123201
123204
  device_code: started.receiver,
123202
- expires_in: 600,
123205
+ expires_in: toSeconds(SIGN_IN_LIFETIME),
123203
123206
  interval: 2,
123204
123207
  user_code: started.code,
123205
123208
  verification_uri: `${origin}/`,
@@ -123400,7 +123403,7 @@ const ToolHandlers = Tools.toLayer(gen(function* () {
123400
123403
  });
123401
123404
  }));
123402
123405
  // src/main.server.ts
123403
- const layerServices = pipe(mergeAll$1(SignIns.layer, layer$2), provideMerge(People.layer), provideMerge(mergeAll$1(Tokens.layer, Passkeys.layer, GitHub.layer, Apps.layer, layerStoreMemory)), provide$2(layerDataStore), provide$2(succeed$6(RequestInit, { redirect: "error" })));
123406
+ const layerServices = pipe(mergeAll$1(SignIns.layer, provide$2(layer$2, layerStoreMemory)), provideMerge(People.layer), provideMerge(mergeAll$1(Tokens.layer, Passkeys.layer, GitHub.layer, Apps.layer)), provide$2(succeed$6(RequestInit, { redirect: "error" })));
123404
123407
  runApp({
123405
123408
  auth: provide$2(layerIssuerAuth, layerServices),
123406
123409
  icon: icon_default,